Compare commits

..

5 Commits

Author SHA1 Message Date
vh c62b4eecb3 feat(#20): agents/tier3 family onto the wt adapter + model→role fold (slice-4)
Cut ratatoskr's consumer agent-lifecycle routes over to worldtree-sdk
(issue #20 slice-4). Five routes now flow through `ratatoskr.wt` over the
SDK's `client.agents.*`, returning open-world dicts and mapping the SDK's
undiscriminated `ApiError` floor by route+(status,error_code) per INV-CUT-2:

- `list_agents`      → `agents.list`
- `get_persona_state`→ `agents.persona_state` (404 persona_not_configured /
                        404 agent_not_available / 403 auth_scope_denied)
- `define_agent`     → `agents.define` (429→Tier3QuotaExceeded(retry_after=0),
                        403→Tier3UserIdUnsupported, 422 layer_deferred→…)
- `patch_agent`      → `agents.patch`  (404→Tier3AgentNotFound, 422 field_not_mutable)
- `delete_agent`     → `agents.delete` (404→Tier3AgentNotFound; NOT hide-existence)

Rewired call-sites: the `python -m ratatoskr.tier3` CLI (define/patch/delete)
and the web `_agents_endpoint` / `_persona_state_endpoint`, both catching the
SDK's `ConnectFailed` transport-failure normalization. Deleted the hand-rolled
paths: `sessions.list_agents` / `get_persona_state` / `AgentInfo`, and
`tier3.define/patch/delete_agent` / `Tier3AgentInfo` / parse+extract helpers.

model→role fold (scope B): the define/patch response echoes `role` (spec 1.2 /
b128), read off the open-world dict; `LocalAgentEntry.model`→`.role`,
local-index schema v1→2 (old index discarded, no-backwards-compat).

The Tier-3 caller-semantic exceptions move to `sessions.py`: running the CLI
as `__main__` while `wt` imports `ratatoskr.tier3` bound two copies of each
exception class, so a raised `Tier3AgentNotFound` escaped the CLI's `except`
as an uncaught traceback. Homing them in `sessions` (never `__main__`) makes
the class identity single. The live smoke — not the unit tests, which call
`main()` in-process — caught this.

Error-map rows + slice-4 notes added to the cutover contract; coverage-map
re-anchored. LIVE-SMOKE on personal :8081 (b128): define(thoughtful-character)
→ patch → list(6 agents) → persona_state(→PersonaNotConfigured mapped) →
delete → index empty; non-existent-id patch via `-m` → [agent_not_found]
exit 20. Suite 465 green.
2026-07-19 09:58:01 -07:00
vh 4f92a21cb9 memory: /snapshot — worldtree-sdk cutover slice-3 complete (ca9a339+fc256bb) 2026-07-19 09:20:18 -07:00
vh fc256bbaa4 fix(#20): heid-bug-hunt fixups — probe ConnectFailed + adapter finite-PAD (slice-3)
The slice-3 heid-bug-hunt panel (3/3) caught a real regression the cutover
introduced, plus a chokepoint-invariant gap:

- ConnectFailed escaped both rewired CLI probes. When --set-persona-pad and
  --seed-first-message moved off raw httpx onto the wt adapter, transport failures
  changed class: the SDK normalizes any pre-response transport error to
  worldtree_sdk.ConnectFailed (request.py), a WorldtreeError (not ApiError), so it
  passed the adapter unmapped AND the probes' httpx-only except tuples → an uncaught
  traceback instead of the graceful [network_error] exit 21. _amain (slice-2) already
  handled it; the probes lagged. Fix: add ConnectFailed to both probe except tuples
  (mirrors _amain). Live-verified at a refused host → [network_error] exit 21.

- Finite-PAD enforced only at the CLI, not the adapter chokepoint. wt.set_persona_state
  delegated finiteness to the caller (documented), so a direct/non-CLI caller passing
  nan/inf got a raw SDK ConfigurationError. Fix: assert finiteness in the adapter
  precondition (consistent with its other precondition asserts) so the invariant holds
  at the chokepoint in ratatoskr's own terms; the CLI pre-check stays for the friendly
  usage error.

Triaged-and-declined (all correct per the panel + Heid's source-check): the deleted
sessions.py exports (intended no-shim cutover, zero un-migrated importers), the
session["session_id"] index (accept-known-risk, matches --new), and Regin's "web
indefinite block" (refuted — the seed is asyncio.wait_for-bounded). The concurrent
heid-code-review panel returned zero drift, no code change.

TDD: 3 RED tests (both probes' ConnectFailed → exit 21; adapter nan/inf/-inf →
AssertionError, never reaches the SDK) → GREEN. Suite 469; ruff clean; mypy no new errors.
2026-07-19 09:13:47 -07:00
vh ca9a339050 feat(#20): persona + authored-history + first-message onto the wt adapter (slice-3)
Slice-3 of the worldtree-sdk cutover: migrate the session persona-state write,
the #347 authored-history write, and get_session_messages onto ratatoskr.wt, and
route the first-message preset seed through the adapter. Retire the last
hand-rolled sessions.py paths the --seed-first-message probe kept alive
(create_session + SessionInfo, set_persona_state, write_authored_history,
get_session_messages, _bifrost_error_from).

- wt.set_persona_state (SDK PadState) — the CLI passes three finite PAD axes; the
  SDK owns the {"pad": {...}} wire (#317). No route-specific error row → the
  SessionApiFailed default.
- wt.write_authored_history (SDK write_history) — v1 author=assistant; 404 →
  AuthoredHistoryUnavailable (hide-existence; the route is the discriminator,
  never the body); every other ApiError → the default. Drops the unused
  author/effects/claimed_original_at params (no caller uses them).
- first_message.seed_preset_first_message now takes a WorldtreeClient and routes
  through wt.write_authored_history; the best-effort invariants (INV-001..004,
  never-raise/never-block/one-write/zero-worldtree-source-import) are unchanged.
  Tests drive a fake WorldtreeClient — the wire is the SDK's to prove.
- CLI --set-persona-pad / --seed-first-message + the _amain and web create-path
  first-message seeds rewired onto the adapter. --set-persona-pad pre-validates
  PAD finiteness (clean usage_error, never a crash on the SDK ConfigurationError).

LIVE-SMOKE on personal :8081 (b128, INV-CUT-5): --seed-first-message → 201
(seq=0, phase=seeded) → read-back verbatim; --set-persona-pad → 204; the --new
create-path preset seed observed routing through the adapter. All slice-3 route
families proven end-to-end through the ratatoskr surface.

docs/coverage-map.md + first_message.contract.md re-anchored onto the adapter;
the slice-2 create/stream/cancel rows re-anchored too (they still named the
deleted sse_client/sessions symbols).

Suite 466 green; mypy no new errors (baseline 22 → 20 in the touched modules);
ruff clean. INV-CUT-1..5 held. Bifrost provider planes untouched.
2026-07-19 08:53:45 -07:00
vh 0b23334c68 memory: /snapshot — worldtree-sdk cutover slice-1+2 complete + pushed (aba1730)
Slice-2 (sessions/turn) done end-to-end through the House Code Discipline; both heid
gates triaged+fixed. Captures the KEY ADAPTER FACTS foot-guns for slices 3-7 (open-world
dicts, body-derived turn_id, ConnectFailed(0) transport normalization, consumer_key
bound-only, nested-detail error_code parsing) + the two-lens gate value proof. Slice-3
(persona/authored-history) next.
2026-07-19 08:23:23 -07:00
23 changed files with 1262 additions and 2169 deletions
+8
View File
@@ -142,6 +142,14 @@ _Archived 2026-07-18._
_Archived 2026-07-18._
`[2026-06-17]` **#296 triage sent to worldtree-dev** (`01KVBBH0…`): extraction SUBJECT-INVERSION (promotes assistant prose, drops the user's fact) + META-DESCRIPTION-not-content; verbose-persona aggravator. WAD-vs-bug resolved to BUG (extraction quality), not idle-gating.
_Archived 2026-07-19._
`[2026-06-18]` **Tier-3 memory PROVEN end-to-end live**`ratatoskr:terse-probe` recalled a seeded user fact in a COLD history-free session (scope_any → 1 hit @ cosine 0.6994). Closes the opening "how far from Tier-3 memory" question for normal agents.
_Archived 2026-07-19._
## Tried and abandoned (archived)
The 2026-05-20 → 2026-05-28 cluster: original-build-era foot-guns. Archived 2026-06-18.
+21 -20
View File
@@ -13,11 +13,12 @@ scope: >
replacement for a system-prompt "startup" instruction. Two entry points:
`preset_for` (lookup) and `seed_preset_first_message` (best-effort seed).
Consumed by ratatoskr.cli (the `--new` session path) and ratatoskr.web.server
(the POST /api/sessions endpoint). Depends on ratatoskr.sessions
(write_authored_history + its exceptions); no core.* / worldtree.* imports.
(the POST /api/sessions endpoint). Depends on ratatoskr.wt
(`wt.write_authored_history` + AuthoredHistoryUnavailable) over a WorldtreeClient
(worldtree-sdk cutover slice-3, #20); no core.* / worldtree.* SOURCE imports.
depends_on:
- "httpx"
- "ratatoskr.sessions"
- "worldtree_sdk"
- "ratatoskr.wt"
used_by:
- "ratatoskr.cli"
- "ratatoskr.web.server"
@@ -26,7 +27,7 @@ complexity: "low"
estimated_loc: 60
confidence: 0.9
assumptions:
- "write_authored_history (contract #2 amendment 2026-07-06) is the seed primitive: 200/201 → ack dict, 404 → AuthoredHistoryUnavailable (hide-existence), other non-2xx → SessionApiFailed."
- "wt.write_authored_history (the SDK-adapter seed primitive, #20) writes over the worldtree-sdk client: success → ack mapping, 404 → AuthoredHistoryUnavailable (hide-existence), other ApiError → wt.SessionApiFailed. Behavior/semantics unchanged from the retired hand-rolled path — only the transport moved to the SDK."
- "The preset registry is a static in-module dict keyed by agent_id; editing it is how an operator tunes an agent's opening. Seeded with ratatoskr:sindra only."
- "Auto-seed is BEST-EFFORT and MUST NOT block session creation: an instance without the session.history.write grant returns the hide-404, which is swallowed (session opens with no seeded greeting)."
---
@@ -47,8 +48,8 @@ every new session for a preset agent opens in-character regardless of surface.
## Data flow
**In:** a live `httpx.AsyncClient` (caller-owned, base_url + bearer set), a fresh
`session_id`, and the bound `agent_id`.
**In:** a `WorldtreeClient` (the wt-adapter client, built over ratatoskr's
caller-owned transport), a fresh `session_id`, and the bound `agent_id`.
**Out:** on a preset agent, one `POST /sessions/{session_id}/history` (author=assistant,
the preset text, per-content idempotency key). Returns the seeded content on
@@ -104,19 +105,19 @@ TESTS:
preset_miss [happy]: preset_for("mimir") is None
empty_agent_id [adversarial]: preset_for("") → AssertionError
FN seed_preset_first_message(client: httpx.AsyncClient, session_id: str, agent_id: str) -> str | None
BRIEF: Best-effort seed of an agent's preset opening as a #347 authored first-message on session_id. If agent_id has a preset, POST it via write_authored_history (author=assistant, per-content idempotency key, the await bounded by asyncio.wait_for(_SEED_TIMEOUT_S)) and return the seeded content; on no-preset, a malformed input, OR ANY exception except asyncio.CancelledError, return None WITHOUT raising. Never raises (except CancelledError, which propagates) and never blocks session creation — it is wired into three create paths.
FN seed_preset_first_message(client: WorldtreeClient, session_id: str, agent_id: str) -> str | None
BRIEF: Best-effort seed of an agent's preset opening as a #347 authored first-message on session_id. If agent_id has a preset, write it via wt.write_authored_history (author=assistant, per-content idempotency key, the await bounded by asyncio.wait_for(_SEED_TIMEOUT_S)) and return the seeded content; on no-preset, a malformed input, OR ANY exception except asyncio.CancelledError, return None WITHOUT raising. Never raises (except CancelledError, which propagates) and never blocks session creation — it is wired into the CLI + web create paths.
PRE: [PRE-001 hard] client is not None -- soft-guarded: return None (NOT assert) if violated, so a wiring bug can't crash the create path (INV-001)
PRE: [PRE-002 hard] session_id is a non-empty str -- soft-guarded: return None if violated
PRE: [PRE-003 hard] agent_id is a non-empty str -- soft-guarded: return None if violated (also guards FIRST_MESSAGE_PRESETS.get against a non-hashable/non-str id)
POST: [POST-001 return_value] preset agent + successful write → returns the preset text; no-preset, malformed input, OR any swallowed failure → None
POST: [POST-002 side_effect] a no-preset / malformed-input call issues ZERO HTTP; a preset agent issues exactly one POST /sessions/{session_id}/history with body author="assistant", content=preset, idempotency_key="ratatoskr-preset-"+sha256(preset)[:12], the await bounded by _SEED_TIMEOUT_S so a stalled response cannot block
POST: [POST-002 side_effect] a no-preset / malformed-input call issues ZERO writes; a preset agent issues exactly one authored-history write (POST /sessions/{session_id}/history via the SDK) with entry author="assistant", content=preset, idempotency_key="ratatoskr-preset-"+sha256(preset)[:12], the await bounded by _SEED_TIMEOUT_S so a stalled response cannot block
ERROR_ROUTING:
asyncio.CancelledError:
local_handling: RE-RAISE (cancellation is not a seed failure; never swallow it — and it is a BaseException, so `except Exception` would miss it anyway)
flow_control: propagate
state_recovery: n/a
any other Exception (hide-404 AuthoredHistoryUnavailable, SessionApiFailed 409/422/etc., httpx.HTTPError, TimeoutError from wait_for, any unexpected error):
any other Exception (hide-404 AuthoredHistoryUnavailable, wt.SessionApiFailed 409/422/etc., SDK ConnectFailed, TimeoutError from wait_for, any unexpected error):
local_handling: swallow; return None
flow_control: continue (never blocks session create)
state_recovery: session opens with no seeded greeting
@@ -125,18 +126,18 @@ STEPS:
2. [sequential, prescriptive] content = FIRST_MESSAGE_PRESETS.get(agent_id); IF content is None: RETURN None (INV-002 — zero HTTP)
3. [sequential, prescriptive] Soft-guard: IF client is None OR session_id is not a non-empty str: RETURN None
4. [sequential, prescriptive] key = "ratatoskr-preset-" + sha256(content utf-8)[:12]
5. [sequential, prescriptive] TRY: await asyncio.wait_for(write_authored_history(client, session_id, content=content, idempotency_key=key), timeout=_SEED_TIMEOUT_S)
5. [sequential, prescriptive] TRY: await asyncio.wait_for(wt.write_authored_history(client, session_id, content=content, idempotency_key=key), timeout=_SEED_TIMEOUT_S)
tool: { destructive: false, idempotent: true, read_only: false, open_world: false }
6. [branch, prescriptive] EXCEPT asyncio.CancelledError: RAISE; EXCEPT Exception: RETURN None
7. [cleanup, prescriptive] RETURN content
TESTS:
seeds_preset [happy,tracer]: preset agent, mock 201 → returns the preset text; exactly one POST /sessions/{id}/history; body author="assistant" + content=preset + idempotency_key="ratatoskr-preset-"+sha256(preset)[:12]
no_preset_zero_http [happy]: agent "mimir" → returns None; NO HTTP issued
feature_absent_swallowed [error]: preset agent, mock 404 session_not_found → returns None, no raise
session_api_failed_swallowed [error]: preset agent, mock 409 → returns None, no raise
transport_error_swallowed [error]: preset agent, mock httpx.ConnectError → returns None, no raise
TESTS: (driven through a fake WorldtreeClient whose sessions.write_history returns/raises — the wire is the SDK's to prove via its parity corpus)
seeds_preset [happy,tracer]: preset agent, fake write_history returns an ack → returns the preset text; exactly one write_history call; entry author="assistant" + content=preset + idempotency_key="ratatoskr-preset-"+sha256(preset)[:12]
no_preset_zero_write [happy]: agent "mimir" → returns None; ZERO write_history call
feature_absent_swallowed [error]: preset agent, fake raises ApiError(404) → adapter maps to AuthoredHistoryUnavailable → returns None, no raise
session_api_failed_swallowed [error]: preset agent, fake raises ApiError(409) → wt.SessionApiFailed → returns None, no raise
transport_error_swallowed [error]: preset agent, fake raises SDK ConnectFailed → returns None, no raise
unexpected_exception_swallowed [error]: preset agent, write raises ValueError → returns None, no raise (INV-001 broad never-raise)
cancellation_propagates [error]: preset agent, write raises asyncio.CancelledError → RE-RAISED (never swallowed)
malformed_agent_id_no_http [adversarial]: agent_id=123 (non-str) OR "" → None; NO HTTP; no raise
empty_session_id [adversarial]: session_id="" (preset agent) → None (soft guard); NO HTTP; no raise
malformed_agent_id_no_write [adversarial]: agent_id=123 (non-str) OR "" → None; ZERO write; no raise
empty_session_id [adversarial]: session_id="" (preset agent) → None (soft guard); ZERO write; no raise
```
@@ -164,7 +164,15 @@ others, they get their own row here — the default is NOT a general "any 404
| `ApiError(404)` on `sessions.write_history` | `AuthoredHistoryUnavailable` (hide-existence) |
| `ApiError(422 cursor_invalid)` on `sessions.list` | `InvalidCursor` (dual-key: status 422 AND error_code; the flat cursor body surfaces the code) |
| `ApiError(502)` on bound `sessions.create` | `BifrostHandshakeFailed` — NOT gated on error_code (unlike list's 422): INV-002, the synchronous handshake is the SOLE bound-502 cause; and the SDK's envelope parser prefers the nested `detail` (which carries `bifrost_error`, not `error_code`), so no distinguishing top-level `error_code` surfaces. The route+status IS the discriminator. |
| **`ApiError` (any other status/route) — the default** | `SessionApiFailed(status, error_code, body)` |
| `ApiError(429)` on `agents.define` (slice-4) | `Tier3QuotaExceeded(retry_after=0)` — the SDK's `ApiError` floor carries no response headers, so the `Retry-After` header the hand-rolled path read is unavailable; spec §2675 pins Phase-2.0 quota to `Retry-After: 0`, so the adapter defaults to 0. A non-zero forward-compat value is unrecoverable until the SDK surfaces headers (INFORM wtsdk-dev; reference-impl posture). |
| `ApiError(403 tier3_user_id_unsupported)` on `agents.define` (slice-4) | `Tier3UserIdUnsupported` (dual-key: status 403 AND error_code) |
| `ApiError(422 layer_deferred)` on `agents.define` (slice-4) | `Tier3LayerDeferred(field)``field` parsed from the body (`detail.field` / flat `field`); the SDK carries `error_code` but not `field`, so the adapter body-parses it (same posture as bound-502's `bifrost_error`) |
| `ApiError(404)` on `agents.patch` / `agents.delete` (slice-4) | `Tier3AgentNotFound` (route-discriminated; agents CRUD is NOT a hide-existence route — a 404 there IS "no such agent") |
| `ApiError(422 field_not_mutable)` on `agents.patch` (slice-4) | `Tier3FieldNotMutable(field)` (dual-key status+error_code; `field` body-parsed) |
| `ApiError(404 persona_not_configured)` on `agents.persona_state` (slice-4) | `PersonaNotConfigured` (dual-key) |
| `ApiError(404 agent_not_available)` on `agents.persona_state` (slice-4) | `AgentNotAvailable` (the persona-surface `sessions.AgentNotAvailable`, distinct from the eager-turn `sse_client.AgentNotAvailable`; dual-key) |
| `ApiError(403 auth_scope_denied)` on `agents.persona_state` (slice-4) | `AuthScopeDenied(scope="persona.read")` (dual-key) |
| **`ApiError` (any other status/route, incl. `agents.list` and any unmatched agent-route code) — the default** | `SessionApiFailed(status, error_code, body)` |
The default row is load-bearing: any `ApiError` not matched above surfaces as the
generic `SessionApiFailed` carrying the raw `status`/`error_code`/`body` — the
@@ -206,6 +214,32 @@ re-anchor its coverage-map rows.
SSE parsing); retire contracts #2/#15; final coverage-map re-anchor; minor bump
(DEC-6, operator approval).
### Slice-4 notes (Agents/Tier-3 + `model`→`role` fold, decided at TDD)
- **`model``role` cutover folds in here (scope B).** Worldtree spec 1.2 (`v1.0.0b128`,
live on :8080/:8081) made the `/agents/define` response echo `role`, closing the
old W-4 `model` echo. The adapter returns the SDK's OPEN-WORLD `DefinedAgent` /
`PatchedAgent` dicts verbatim (parity posture); callers read `info["role"]`. The
frozen `Tier3AgentInfo` dataclass (which read `body["model"]` and would KeyError
post-b128) is DELETED — no dataclass normalization layer survives.
- **`ratatoskr.local_agents` schema bump.** `LocalAgentEntry.model``.role` (the
field stores what the wire now calls a role); `_SCHEMA_VERSION` 1→2 so any
pre-cutover on-disk index is discarded cleanly (no-backwards-compat, DEC-3).
- **`AgentNotAvailable` name collision.** `sessions.AgentNotAvailable` (persona-state
404 `agent_not_available`) and `sse_client.AgentNotAvailable` (eager-turn 409) are
distinct types that share a name; `wt` already imports the sse_client one for the
stream, so it imports the persona one ALIASED (`PersonaAgentNotAvailable`) and
raises it from `get_persona_state`. The web endpoint keeps importing the persona
`AgentNotAvailable` from `sessions` (same class), so its `except` is unchanged.
- **`ConnectFailed` at every rewired caller (slice-3 foot-gun).** The SDK normalizes
ANY transport failure to `ConnectFailed(status=0)` (`request.py`), not a raw httpx
error. The rewired tier3 CLI and both web endpoints (`_agents_endpoint`,
`_persona_state_endpoint`) catch `wtsdk.ConnectFailed` → their existing
network-error surface (CLI exit 21 / web 502). The web `test_network_error_returns_502`
(respx `httpx.ConnectError` side-effect) is the RED that proves this.
- **`agents.get(agent_id)`** (SDK `GET /agents/{id}`) is NOT wrapped — ratatoskr has no
`get_agent` consumer; only list/persona_state/define/patch/delete are in coverage.
## Out of scope
- Bifrost PROVIDER planes (memory/affect) — hand-rolled, ADR-0009, untouched.
+11 -11
View File
@@ -84,16 +84,16 @@ sub-gap).
| Endpoint | Status | Where consumed | Note |
|---|---|---|---|
| `POST /sessions` | ✅ | `sessions.py` `create_session` `cli.py`,`tui.py`,`web/server.py` | + `end_user_id`, `bifrost` binding; 404→AgentNotFound, 502→BifrostHandshakeFailed. **v0.21.2 (#19): ephemeral-template (Echo) create**`config` passthrough (`--system-prompt`), `role` not `model` (W-4), `kind`/`config` captured; 422 ephemeral_requires_config now reachable-and-handled. Depth enhancement to an already-covered route — count unchanged |
| `POST /sessions/{id}/messages` (turn stream, SSE) | ✅ | `sse_client.py:484` `stream_turn` → cli/tui/web | the primary surface; 409→AgentNotAvailable, 503→TurnLaunchUnavailable (b2 #331) |
| `POST /sessions/{id}/history` (authored-history-write, #347) | ✅ | `sessions.py:583` `write_authored_history``cli.py:758` `--seed-first-message` | v1: author=assistant, effects=none, per-session idempotency; 404→AuthoredHistoryUnavailable (hide-existence: feature-absent, never probe); 409/422 mapped. **LIVE-PROVEN 2026-07-06** on personal :8081 (grant applied via a rule-based Heimdall allow, worldtree-dev): create mimir session → seed → **201** (seq=0, phase=seeded, turn_id=1798) → GET /messages reads it back as a plain role=assistant turn (model-invisible provenance confirmed). Hide-404 for ungranted is unit+probe covered |
| `GET /sessions/{id}/messages` (history) | ✅ | `sessions.py:635` `get_session_messages``cli.py:758` `--seed-first-message` read-back | un-deferred as the #347 seed read-back — confirms model-invisible provenance (a seed reads back as a normal `role=assistant` turn) |
| `POST /sessions/{id}/turns/{turn_id}/cancel` | ✅ | `sse_client.py:581` → cli/tui/web | two-stage Ctrl-C; 404/409 mapped |
| `GET /agents` | ✅ | `sessions.py:341``tui.py:1472`,`web/server.py:100` | Tier-1 roster; merged with local index |
| `GET /agents/{id}/persona_state` | ✅ | `sessions.py:384``tui.py:1132`,`web/server.py:386` | persona hydrate; 404/403 mapped |
| `POST /agents/define` | ✅ | `tier3.py:175``_run_define` | Tier-3 create |
| `PATCH /agents/{id}` | ✅ | `tier3.py:219``_run_patch` | Tier-3 mutate (system_prompt/model) |
| `DELETE /agents/{id}` | ✅ | `tier3.py:242``_run_delete` | Tier-3 hard-delete |
| `POST /sessions` | ✅ | `wt.py` `create_session` (SDK `sessions.create`) → `cli.py`,`web/server.py` | **wt-adapter re-anchored (slice-2, #20)** — + `end_user_id`, `bifrost` binding (consumer-key via SDK per-request auth), `config` passthrough; 404→AgentNotFound, bound-502→BifrostHandshakeFailed. Ephemeral-template (Echo) create (#19) carried through the adapter. Depth enhancement to an already-covered route — count unchanged |
| `POST /sessions/{id}/messages` (turn stream, SSE) | ✅ | `wt.py` `stream_turn` (SDK resilient `sessions.stream_turn`, auto-resume) → cli/web | **wt-adapter re-anchored (slice-2, #20)** the primary surface; 409→AgentNotAvailable, 503→TurnLaunchUnavailable, drop→SseConnectionDropped, protocol→same-named; absorbs the old `reconnect_turn` |
| `POST /sessions/{id}/history` (authored-history-write, #347) | ✅ | `wt.py` `write_authored_history` (SDK `sessions.write_history`)`cli.py` `--seed-first-message`, `first_message.py` `seed_preset_first_message` (create-path seed) | **wt-adapter re-anchored (slice-3, #20)** — SDK owns the entry shape; v1 author=assistant; 404→AuthoredHistoryUnavailable (hide-existence, route is the discriminator, never probe); 409/422→SessionApiFailed default. **LIVE-SMOKE 2026-07-19** on personal :8081 (b128): `--seed-first-message` on a sindra session → **201** (seq=0, phase=seeded, turn_id=2294) → read-back verbatim; create-path preset seed observed via `--new`. (Prior 2026-07-06 hand-rolled proof superseded.) |
| `GET /sessions/{id}/messages` (history) | ✅ | `wt.py` `get_session_messages` (SDK `sessions.messages`)`cli.py` `--seed-first-message` read-back, `web/server.py` messages proxy | **wt-adapter re-anchored (slice-3, #20)** — the #347 seed read-back; open-world passthrough. **LIVE-SMOKE 2026-07-19**: read-back rendered the seeded seq-0 turn as a plain role=assistant message (model-invisible provenance confirmed) |
| `POST /sessions/{id}/turns/{turn_id}/cancel` | ✅ | `wt.py` `cancel_turn` (SDK `sessions.cancel_turn`) → cli/web | **wt-adapter re-anchored (slice-2, #20)** — two-stage Ctrl-C; 404→CancelTurnNotFound, 409→CancelAlreadyCompleted, late-cancel 200 (`cancelled=False`) is a benign result, not an error |
| `GET /agents` | ✅ | `wt.py` `list_agents` (SDK `agents.list`) → `web/server.py` `_agents_endpoint` | **wt-adapter re-anchored (slice-4, #20)** — open-world array verbatim (no AgentInfo normalization), merged with the local tier3 index (remote-wins); error→SessionApiFailed default, transport→ConnectFailed→502. **LIVE-SMOKE 2026-07-19** on personal :8081 (b128): 6 agents returned (forseti/lofn/mask/mimir/vili/…) |
| `GET /agents/{id}/persona_state` | ✅ | `wt.py` `get_persona_state` (SDK `agents.persona_state`) → `web/server.py` `_persona_state_endpoint` | **wt-adapter re-anchored (slice-4, #20)** — open-world snapshot; dual-key (status,error_code) map: 404 persona_not_configured→PersonaNotConfigured, 404 agent_not_available→AgentNotAvailable, 403 auth_scope_denied→AuthScopeDenied, else default. **LIVE-SMOKE 2026-07-19**: a tier3 agent → correctly mapped `PersonaNotConfigured` (route+code adapter proven) |
| `POST /agents/define` | ✅ | `wt.py` `define_agent` (SDK `agents.define`) → `tier3.py` `_run_define` | **wt-adapter re-anchored (slice-4, #20)** — sends AgentDefineInput `{agent_name,role,system_prompt}`, returns open-world `DefinedAgent` (echoes `role`, b128); slug pre-validated; 429→Tier3QuotaExceeded(retry_after=0, header-less floor), 403→Tier3UserIdUnsupported, 422 layer_deferred→Tier3LayerDeferred. **LIVE-SMOKE 2026-07-19**: `define --role thoughtful-character``defined ratatoskr:slice4-smoke (thoughtful-character)` |
| `PATCH /agents/{id}` | ✅ | `wt.py` `patch_agent` (SDK `agents.patch`) → `tier3.py` `_run_patch` | **wt-adapter re-anchored (slice-4, #20)** — Tier-3 mutate (system_prompt/**role**, model→role folded in); 404→Tier3AgentNotFound, 422 field_not_mutable→Tier3FieldNotMutable. **LIVE-SMOKE 2026-07-19**: `patched ratatoskr:slice4-smoke`; a non-existent id via `python -m``[agent_not_found]` (exit 20, class-identity fix proven) |
| `DELETE /agents/{id}` | ✅ | `wt.py` `delete_agent` (SDK `agents.delete`) → `tier3.py` `_run_delete` | **wt-adapter re-anchored (slice-4, #20)** — 204→None; 404→Tier3AgentNotFound (route-discriminated, NOT hide-existence). **LIVE-SMOKE 2026-07-19**: `deleted ratatoskr:slice4-smoke` + local index → `[]` |
| `GET /me` | ✅ | `sessions.py:411` `get_me``cli.py` `--whoami` | identity/whoami probe; 401→SessionApiFailed |
| `GET /capabilities` | ✅ | `sessions.py` `get_capabilities``cli.py` `--whoami` | Echo ephemeral-template discovery. **v0.21.2: `--whoami` renderer reads `allowed_roles`/`default_role`** (was the dead `allowed_models`/`default_model`) + tolerates malformed caps; matches conversation-api-spec **v1.1** (`b4a278c`) |
| `GET /sessions/{id}/tools` | ✅ | `sessions.py:411` `get_session_tools``tui.py` `_hydrate_session_tools` | owner-scoped tool inventory in the TUI Tools pane (#183) |
@@ -103,7 +103,7 @@ sub-gap).
| `POST /characters` | ✅ | `sessions.py` `create_character``cli.py` `--characters` | create transient character (#161) |
| `GET /characters/{id}/state` | ✅ | `sessions.py` `get_character_state``cli.py` `--characters` | live character PAD/emotions (#161) |
| `DELETE /characters/{id}` | ✅ | `sessions.py` `delete_character``cli.py` `--characters` | remove transient character (#161) |
| `POST /sessions/{id}/persona_state` | ✅ | `sessions.py` `set_persona_state``cli.py` `--set-persona-pad` | persona-state write / affect injection (freeform body — unpinned in the frozen surface) |
| `POST /sessions/{id}/persona_state` | ✅ | `wt.py` `set_persona_state` (SDK `sessions.set_persona_state`, `PadState`)`cli.py` `--set-persona-pad` | **wt-adapter re-anchored (slice-3, #20)** — SDK owns the canonical `{"pad": {...}}` wire (#317); CLI passes the 3 PAD axes (finiteness pre-validated); 204→None, else SessionApiFailed default. **LIVE-SMOKE 2026-07-19** on personal :8081: `--set-persona-pad 0.4,0.1,-0.2`**204** |
**Sub-gaps inside ✅ path groups** (the method we use is live; a sibling method
on the same path is an unwired frontier item — see frontier Tier 1):
@@ -0,0 +1,57 @@
`[2026-07-19]` **worldtree-sdk cutover — SLICE-1 + SLICE-2 COMPLETE + PUSHED (origin `aba1730`, v0.21.10).**
The consumer client layer's biggest, riskiest slice (sessions/turn) is fully migrated onto
`worldtree-sdk (Python) 1.0.0` behind the `ratatoskr.wt` adapter, run end-to-end through the House Code
Discipline. Pushed 2026-07-19 (12-commit arc `b1fbadd``aba1730`, tags v0.21.3.10). Suite **497 green**.
## The arc (all on origin/main)
| Part | Commit | What |
|---|---|---|
| Slice-1 foundation | `12cd864` (v0.21.3) | `build_client` + `translate_error` DEFAULT (ApiError→SessionApiFailed) + passthrough; INV-CUT-1 (injected transport, `_owns_client=False`) test-proven |
| Slice-2 adapter (read/create) | `bb158ae` (v0.21.4) | create/list/messages/tools over `client.sessions.*`, per-route error mapping |
| Slice-2 adapter (stream/cancel) | `b907a7b` (v0.21.5) | resilient `stream_turn` + `cancel_turn`; SDK stream errors re-wrapped → ratatoskr caller-semantic exceptions (DEC-2) |
| Slice-2 CLI rewire | `e3a10ad` (v0.21.6) | `_amain`/`_run_turn`/render onto SDK `TurnEvent`s + open dicts |
| Slice-2 web rewire | `5c595b8` (v0.21.7) | Starlette endpoints + SSE→JSON serialization; browser contract preserved |
| Slice-2 deletion | `59602fe` (v0.21.8) | sse_client 714→224, sessions 677→608; orphaned turn-stream family + Event model removed; **DEC-4 live-smoke PASSED first** |
| heid-code-review fixup | `74d41eb` (v0.21.9) | INV-CUT-2 completeness (cancel/stream ApiError default) + contract error-map amendments |
| heid-bug-hunt fixup | `aba1730` (v0.21.10) | 4 confirmed bugs + open-world render hardening |
## KEY ADAPTER FACTS (foot-guns for slices 3-7)
- **The SDK returns open-world dicts** (`Mapping`, NOT typed objects) for session reads → presenters read
mappings (`info["session_id"]`), never attributes. Ratatoskr's typed `SessionInfo`/`SessionPage` retired.
- **SDK `TurnEvent` shape:** `sse_id: str` (the composite `"{turn}:{seq}"`) + a **body-derived `turn_id`
that is ABSENT (None) on text/thinking frames.** The mid-stream cancel target must parse the turn from
`sse_id`, NOT read `event.turn_id`. (This was a live bug — sigint-cancel saw "no event".)
- **The SDK normalizes transport failures to `ConnectFailed(status=0)`** (not raw httpx errors) → presenters
catch `wtsdk.ConnectFailed` for network paths; a stream `ConnectFailed` maps → `SseConnectFailed`.
- **The adapter re-wraps SDK stream errors → ratatoskr's caller-semantic exceptions** (DEC-2 keeps ratatoskr's
typed exceptions; SessionRetired→SessionApiFailed, ConnectionDropped→SseConnectionDropped, Malformed*/
TurnIdFlip→same-named, ConnectFailed/terminal ResumeError→SseConnectFailed).
- **`consumer_key` is BOUND-create-only** — the adapter nulls it when `bifrost is None`, else the SDK's
credential precedence auths as the consumer instead of the default bearer.
- **The SDK's error-envelope parser PREFERS the nested `detail`** dict when present, so a top-level
`error_code` doesn't surface. That's why create's bound-502 is NOT gated on error_code (unlike list's
422+cursor_invalid, whose flat body surfaces the code) — INV-002 also makes the handshake the sole
bound-502 cause. This is a genuine cross-frontier triage win: 2/3 heid arms flagged the missing gate; it
was correctly REJECTED as category-5 wrong-grounding (the SDK parser wasn't in the arms' file set).
## The two heid gates (the value proof)
- **heid-code-review** (Gróa+Hulda substantive, Regin zero=weak): adopted the cancel/stream ApiError-default
completeness + error-map table amendments; correctly rejected the bound-502-gate finding (above).
- **heid-bug-hunt** (Gróa 8 / Hulda 6 / Regin 6; Heid source-checked, refuted 2 Regin FPs): caught **4 real
confirmed bugs the conformance lens structurally could not see** — SessionRetired(410) uncaught by both
presenters (crash/dropped-stream), cli consumer_key forwarded on unbound create (auth divergence), sse_id
None-crash, cancel never-raise gap — plus open-world render hardening. Rejected 4 as verified FPs (incl.
Hulda's "deleted funcs break callers" — grep-verified zero callers pre-deletion). Both surfaces re-smoked
live after fixup: create+stream+cancel round-trip clean on :8081 (b128).
## What's still hand-rolled (later slices)
`create_session`/`get_session_messages` (the `--seed-first-message` probe uses them — retire in slice-3);
`set_persona_state`/`write_authored_history`/`first_message` (slice-3); agents/tier3 incl. `model``role`
(slice-4, deploy live b128); characters/me/capabilities/models (slice-5); `stream_admin_events`/
`get_session_bifrost` (slice-6). Slice-7 teardown: retire contracts #2/#15, drop `httpx-sse`, minor bump
(DEC-6, operator approval). Full design → auto-memory `project_worldtree_sdk_cutover`.
@@ -0,0 +1,66 @@
# worldtree-sdk cutover — SLICE-3 complete (2026-07-19)
Slice-3 of the #20 consumer-layer cutover: **persona + authored-history +
first-message** migrated onto the `ratatoskr.wt` adapter, and the last
hand-rolled `sessions.py` paths retired. Two commits: `ca9a339` (feat) +
`fc256bb` (heid-bug-hunt fixups), tags v0.21.11 / v0.21.12. Suite **469 green**.
## What moved / what was deleted
- **`wt.set_persona_state`** — passes 3 PAD axes; SDK owns the `{"pad": {…}}` wire
(#317) via `PadState`. No route-specific error row → `SessionApiFailed` default.
Finiteness enforced at the adapter precondition (chokepoint) AND the CLI.
- **`wt.write_authored_history`** — SDK `write_history`; v1 fixes `author="assistant"`
(dropped the unused `author`/`effects`/`claimed_original_at` params — no caller
used them, and a 3-key literal type-checks against the SDK's private
`AuthoredHistoryInput` without importing a non-public symbol). 404 →
`AuthoredHistoryUnavailable` (hide-existence; the ROUTE is the discriminator,
never the body); else the default.
- **`first_message.seed_preset_first_message`** — now takes a `WorldtreeClient`,
routes through `wt.write_authored_history`; best-effort invariants (INV-001..004)
unchanged. Tests rewritten to drive a fake `WorldtreeClient` (the wire is the
SDK's to prove via its parity corpus, not first_message's).
- **CLI `--set-persona-pad` / `--seed-first-message`** + the `_amain` and web
create-path first-message seeds rewired onto the adapter.
- **DELETED from `sessions.py`**: `create_session` + `SessionInfo`,
`set_persona_state`, `write_authored_history`, `get_session_messages`,
`_bifrost_error_from`. (The exceptions + `BifrostBinding` + `AgentInfo` +
slice-4/5/6 functions stay.)
## Live-smoke (INV-CUT-5, personal :8081 b128)
`--seed-first-message` → 201 (seq=0, phase=seeded) → read-back verbatim;
`--set-persona-pad 0.4,0.1,-0.2` → 204; `--new` create-path preset seed observed
routing through the adapter. All three route families proven end-to-end.
## Both heid gates cleared
- **heid-code-review (panel, cutover contract):** ZERO code-vs-contract drift, all
three arms. Regin's 3 secondary items all self-graded `accept` (non-slice-3
routes / web-not-unit-tested / slice-2 stream test) — correctly declined.
- **heid-bug-hunt (panel):** earned its keep — caught **a real regression I shipped
in `ca9a339`**: when the two CLI probes moved off raw httpx onto the adapter,
transport failures changed class — the SDK normalizes ANY pre-response transport
failure to `worldtree_sdk.ConnectFailed` (`request.py:196`), a `WorldtreeError`
(not `ApiError`), so it escaped the adapter unmapped AND the probes' httpx-only
`except` tuples → uncaught traceback instead of `[network_error]` exit 21.
`_amain` (slice-2) already handled it; the probes lagged. **Fix:** add
`ConnectFailed` to both probe tuples (live-verified at a refused host → exit 21).
Second finding (3/3): finite-PAD enforced only at the CLI, not the adapter
chokepoint → **fix:** adapter precondition assert. Declined (correctly): deleted
`sessions.py` exports (intended no-shim cutover, zero un-migrated importers),
`session["session_id"]` index (accept-known-risk, matches `--new`), Regin's
"web hangs forever" (refuted by Heid from source — the seed is `wait_for`-bounded).
## Foot-gun banked
**The SDK wraps ALL transport failures into `ConnectFailed(status=0)`** (not raw
httpx). Every ratatoskr caller that goes through the adapter must `except
ConnectFailed` on its network path — the httpx-only catches are now dead. This bit
the slice-3 probes; watch for it in slice-4+ call-site rewires.
## Next
Slice-4 (agents/Tier-3 — list/get/define/patch/delete/persona_state) which FOLDS
the pending `model``role` cutover ([[project-tier3-agents-model-to-role-pending]]).
See [[2026-07-19-worldtree-sdk-cutover-slice-1-2-complete]] for the slice-1+2 arc.
+39 -37
View File
@@ -1,6 +1,6 @@
# Persistent memory — ratatoskr
_Last updated: 2026-07-18_
_Last updated: 2026-07-19_
> **Always check for `/tmp/ratatoskr-dev-handoff.md`** — if it exists and its
> `Written:` stamp is under an hour old, read it (it carries the in-flight
@@ -44,34 +44,36 @@ upstream API key stays server-side (INV-003).
## Current state / in-flight
_As of 2026-07-18 (evening):_
_As of 2026-07-19:_
**🔨 ACTIVE MIGRATION — worldtree-sdk cutover (issue #20), starting slice-1.** Operator ruled ADOPT
(2026-07-18): ratatoskr cuts its CONSUMER client layer over to consume **worldtree-sdk (Python) 1.0.0**
retire the hand-rolled httpx wrappers (`sessions`/`sse_client`/`tier3`) behind a thin `ratatoskr.wt`
adapter over the SDK. Both TS + Python SDK 1.0.0 are GA (**Python live + pip-installable on the gitea
PyPI** — DEC-5 gate cleared). Ratatoskr's own **parity pass shaped the Python spine** (open-world reads,
caller-injected transport, per-wire role/model). Design locked (6 DECs, vor-cross'd with worldtree-codex,
heid-panel-reviewed → error-map table added); contract `docs/contracts/worldtree_sdk_cutover.contract.md`
(committed `e45640c`). **SLICE-1 IN PROGRESS:** ✅ dep integrated + DEC-5 verified + committed (`29c4fda`) `worldtree-sdk==1.0.0`
installs from the gitea registry (reuses bifrost's index auth, NO new token; core dep + `[tool.uv.sources]`),
`WorldtreeClient` constructs with an injected transport (`_owns_client=False`, INV-CUT-1 confirmed live),
suite 534 green. **NEXT = the adapter** `src/ratatoskr/wt.py` (TDD): `build_client(base_url, *, api_key,
admin_key, transport)``WorldtreeClient(auth=, admin_auth=, transport=)` (DESIGN CARE: SDK does per-request
auth via the providers; our injected `httpx.AsyncClient` carries base_url/UA/timeout, NOT the Authorization
header — read the SDK `client.py` @ `~/development/worldtree-sdk` for the split, INV-CUT-1) + `translate_error`
DEFAULT (SDK `ApiError``SessionApiFailed`, discriminated `WorldtreeError` subclasses passthrough; route-specific
rows come in later slices). Unit-test; NO surface wiring (slice-2). Then slices 2-7 (route-family + deletions,
live-smoke per slice). Scope: consumer layer ONLY;
Bifrost provider planes untouched. Multi-session grind. Full design → auto-memory
`project_worldtree_sdk_cutover`. This SUPERSEDES the #371 "repin rides the later Python milestone" framing
below (that milestone shipped; we're adopting, not just repinning).
**🔨 ACTIVE MIGRATION — worldtree-sdk cutover (issue #20): SLICE-1 + SLICE-2 + SLICE-3 COMPLETE, slice-4 next.**
Operator ruled ADOPT (2026-07-18): ratatoskr cuts its CONSUMER client layer over to **worldtree-sdk (Python)
1.0.0**, retiring the hand-rolled httpx wrappers behind a thin `ratatoskr.wt` adapter. Design locked (6 DECs,
vor-cross'd, heid-panel-reviewed); contract `docs/contracts/worldtree_sdk_cutover.contract.md`. **SLICE-1+2
(foundation + sessions/turn) ✅ PUSHED** origin `aba1730` (arc `b1fbadd``aba1730`, tags v0.21.3.10). **SLICE-3
(persona + authored-history + first-message) ✅ DONE** — `ca9a339` (feat) + `fc256bb` (heid-bug-hunt fixups),
tags v0.21.11.12; full House Code Discipline (TDD → heid-code-review CLEAN/zero-drift → heid-bug-hunt).
Suite **469 green**. Slice-3 migrated `set_persona_state` (SDK `PadState`), `write_authored_history`
(`write_history`, 404→AuthoredHistoryUnavailable hide-existence), `get_session_messages`, + routed
`first_message` seed through the adapter; DELETED the last hand-rolled `sessions.py` paths (`create_session`+
`SessionInfo`, `set_persona_state`, `write_authored_history`, `get_session_messages`, `_bifrost_error_from`).
LIVE-SMOKE on :8081 (b128): seed→201(seq0)→read-back; persona→204; create-path preset seed. **KEY ADAPTER FACTS
(foot-guns for slices 4-7):** SDK returns **open-world dicts** for reads → `info["session_id"]`; `TurnEvent`
carries `sse_id` + a **`turn_id` ABSENT on text/thinking frames** → parse cancel-target from `sse_id`; the SDK
**normalizes ANY transport failure to `ConnectFailed(status=0)`** (`request.py:196`, NOT raw httpx) — every
caller through the adapter must `except ConnectFailed` (the slice-3 bug-hunt caught both probes missing it);
`consumer_key` is BOUND-create-only; the SDK's envelope parser **prefers nested `detail`** (why bound-502 isn't
error_code-gated). **NEXT = slice-4** (agents/tier3 — list/get/define/patch/delete/persona_state, FOLDS the
`model``role` cutover); then slice-5 (characters/me/caps), slice-6 (admin — `stream_admin_events` +
`get_session_bifrost` still hand-rolled), slice-7 (teardown: retire contracts #2/#15, drop `httpx-sse`, minor
bump per DEC-6 w/ operator approval). Scope: consumer layer ONLY; Bifrost provider planes untouched. Full
design → auto-memory `project_worldtree_sdk_cutover`.
**⏸️ DEFERRED — tier3 agents `model``role` (scope B), on worldtree-dev's deploy flag.** WT renames the
agents-RESPONSE selector `model``role` (spec 1.2, commit `387c67b`, NOT yet deployed). `_parse_tier3_agent_info`
reads `body["model"]` → KeyErrors post-deploy. Operator chose scope B (full tier3 `model``role` incl.
contract #15 + CLI `--model``--role`). Implement ON the deploy flag, not before (breaks the current demo);
folds into cutover slice-4. Auto-memory `project_tier3_agents_model_to_role_pending`.
**⏸️ DEFERRED — tier3 agents `model``role` (scope B), folds into cutover slice-4.** WT renamed the
agents-RESPONSE selector `model``role` (spec 1.2). **DEPLOY NOW LIVE** on :8080/:8081 (v1.0.0b128,
worldtree-dev confirmed 2026-07-19 — was the deploy-flag gate; acked). Operator chose scope B (full tier3
`model``role` incl. contract #15 + CLI `--model``--role`); lands in cutover slice-4 where tier3.py routes
through the SDK (doing it standalone now = throwaway). Auto-memory `project_tier3_agents_model_to_role_pending`.
**✅ RESOLVED — the "app product" workstreams leave Rata entirely (operator 2026-07-18).**
**No arbo fork, no SillyTavern-on-Rata** — a NEW repo (template-dev standing up) takes over BOTH
@@ -115,13 +117,13 @@ Full record → `persistent-memory.d/2026-07-18-368-silo-test-passed.md`. Siblin
(2) R39 Phase-2 **matched-quartets rebuild** (confirmatory, "whenever"); (3) bifrost **snapshot-cursor
adoption** (ruled normative, not blocking → `persistent-memory.d/2026-07-16-bifrost-cursor-conformance.md`).
**Substrate / environment:** branch `main` at **v0.21.2**. **origin at `b1fbadd`** (pushed 2026-07-18:
canonical syncs `5d06a27`/`80c8d58`, ephemeral-Echo `c7016f2` #19, coverage-map→SDK-surface `b1fbadd`).
**UNPUSHED local commits** (cutover work — operator hasn't pushed): cutover contract `e45640c` #20, the
`memory:` snapshot, dep-integration `29c4fda` (worldtree-sdk==1.0.0), + this snapshot — **push is the
operator's call**. origin `git@gitea.phasefinal.com:vh/ratatoskr.git`. **NEW core dep: `worldtree-sdk==1.0.0`**
(gitea PyPI, `[tool.uv.sources]`). bifrost **`==1.1.4`** / wire v0.7; WT openapi vendored 2.3.0,
**conversation-api-spec re-synced to v1.1** (`b4a278c`); **suite 534 green**. Personal WT on **b127**
**Substrate / environment:** branch `main` at **v0.21.12**, **PUSHED to origin** (slice-3 arc `ca9a339`+
`fc256bb` + this snapshot, tags v0.21.11.12, pushed 2026-07-19; slice-1+2 arc `b1fbadd``aba1730` +
v0.21.3.10 earlier). origin `git@gitea.phasefinal.com:vh/ratatoskr.git`. **NEW core dep:
`worldtree-sdk==1.0.0`** (gitea PyPI, `[tool.uv.sources]`; `httpx-sse` retires at slice-7). bifrost
**`==1.1.4`** / wire v0.7; WT openapi vendored 2.3.0, **conversation-api-spec re-synced to v1.1** (`b4a278c`);
**suite 469 green** (was 497 post-slice-2; net delta = slice-3 adapter/probe tests added, ~50 deleted
hand-rolled sessions tests). Personal WT on **b128**
(`http://10.250.50.152:8081`; #368 silo + #364 promotion-hygiene live both instances). The combined
**:8392** provider (memory+affect) + **:8765** web are THE surfaces, dev-box BACKGROUND SHELLS —
restart via `scratchpad/relaunch_by_pid.py <pid>` (pid via `ss -ltnp | grep <port>`). `env.sh` sets
@@ -144,8 +146,6 @@ relational-dynamics verify (bind `--bifrost-url :8392`); WT #356 resume-durabili
Chronological log of decisions with `[YYYY-MM-DD]` prefix. One line per
decision. Captures rationale that won't be obvious from code alone.
- `[2026-06-17]` **#296 triage sent to worldtree-dev** (`01KVBBH0…`): extraction SUBJECT-INVERSION (promotes assistant prose, drops the user's fact) + META-DESCRIPTION-not-content; verbose-persona aggravator. WAD-vs-bug resolved to BUG (extraction quality), not idle-gating.
- `[2026-06-18]` **Tier-3 memory PROVEN end-to-end live**`ratatoskr:terse-probe` recalled a seeded user fact in a COLD history-free session (scope_any → 1 hit @ cosine 0.6994). Closes the opening "how far from Tier-3 memory" question for normal agents.
- `[2026-06-19]` **#18 D2 SHIPPED (`v0.17.14`, `39eebd1`) and the full #17+#18 arc PUSHED to origin** → `persistent-memory.d/2026-06-19-18-d2-shipped-v0-17-14-39eebd1-and-the-full-1.md`
- `[2026-06-19]` **bifrost repinned 0.8.0→0.10.0; `affect.fetch` became MANDATORY (strong-or-absent)**`persistent-memory.d/2026-06-19-bifrost-repinned-0-8-0-0-10-0-affect-fetch-be.md`
@@ -271,8 +271,10 @@ decision. Captures rationale that won't be obvious from code alone.
- `[2026-07-18]` **ephemeral-template (Echo) create SHIPPED (`v0.21.2`, `c7016f2`, #19)**`config` passthrough + `--system-prompt` + `SessionInfo.kind/config` + `--whoami` roles fix. Diagnosed from the ignored `session_api_failed` startup line; role/model drift resolved w/ worldtree-dev (spec re-synced v1.1). TDD + heid contract-review + bug-hunt.
- `[2026-07-18]` **Rata = THE reference consumer of the worldtree-sdk Python spine** — parity pass (12 grounded findings) shaped its contract BEFORE build (open-world reads, caller-injected transport, per-wire role/model — adopted); coverage-map re-anchored to the SDK's 41-op ratified surface (`b1fbadd`); 4 ergonomics items parked post-v1 with wtsdk-dev.
- `[2026-07-18]` **worldtree-sdk cutover DECIDED — adopt the Python SDK for the consumer client layer** (operator, overriding "stay hand-rolled"). Issue #20; contract `docs/contracts/worldtree_sdk_cutover.contract.md` (`e45640c`, vor-cross'd + heid-reviewed); auto-memory `project_worldtree_sdk_cutover`. Consumer layer only, Bifrost provider untouched; slice-1 foundation next. See in-flight.
- `[2026-07-19]` **worldtree-sdk cutover SLICE-1 + SLICE-2 COMPLETE + PUSHED (origin `aba1730`, v0.21.10, 497 green).** The biggest, riskiest cutover slice done end-to-end through the full House Code Discipline (adapter→cli→web→delete→live-smoke→both heid gates); the bug-hunt caught 4 real confirmed bugs the conformance lens couldn't, and a convergent code-review finding was correctly REJECTED as category-5 (SDK envelope-parser behavior). Slice-3 next. → `persistent-memory.d/2026-07-19-worldtree-sdk-cutover-slice-1-2-complete.md`
- `[2026-07-19]` **worldtree-sdk cutover SLICE-3 COMPLETE + pushed (`ca9a339`+`fc256bb`, v0.21.11.12, 469 green).** Persona/authored-history/first-message onto the wt adapter; last hand-rolled `sessions.py` paths deleted; both heid gates cleared — code-review ZERO drift, bug-hunt caught + fixed a real regression I shipped (ConnectFailed escaping both rewired probes → uncaught crash; the SDK normalizes ALL transport failures to `ConnectFailed`, not raw httpx) plus a finite-PAD chokepoint gap. Slice-4 (agents/tier3 + model→role) next. → `persistent-memory.d/2026-07-19-worldtree-sdk-cutover-slice-3-complete.md`
_65 older entries (2026-05-* debug-TUI/web era + the 2026-06-14 → 06-18 Bifrost-provider build / #17+#18 / #295-296 era) archived to archival-memory.md._
_67 older entries (2026-05-* debug-TUI/web era + the 2026-06-14 → 06-18 Bifrost-provider build / #17+#18 / #295-296 era) archived to archival-memory.md._
_For per-issue TDD implementation notes, Volva findings, and contract amendments, see the git log — every per-issue commit carries a structured message capturing the trail._
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "ratatoskr"
version = "0.21.10"
version = "0.21.13"
description = "Worldtree Conversation API debug console (web + headless CLI) — multi-pane observability"
readme = "README.md"
requires-python = ">=3.12"
+50 -23
View File
@@ -8,6 +8,7 @@ from __future__ import annotations
import argparse
import asyncio
import hashlib
import math
import os
import signal
import sys
@@ -44,16 +45,12 @@ from ratatoskr.sessions import (
BifrostHandshakeFailed,
SessionApiFailed,
create_character,
create_session,
delete_character,
endpoint_for_plane,
get_capabilities,
get_character_state,
get_me,
get_session_messages,
list_character_models,
set_persona_state,
write_authored_history,
)
# The turn path (create / stream / cancel) is served by the worldtree-sdk adapter
@@ -719,8 +716,8 @@ async def _amain(args: ParsedArgs) -> int:
f"agent_id={info['agent_id']}{kind_suffix}\n"
)
# #347 authored first-message: seed the agent's preset opening (best-effort).
# Uses the transport directly — first_message is a slice-3 hand-rolled path.
if await seed_preset_first_message(transport, session_id, args.agent_id):
# Routed through the wt adapter (slice-3); the seed never blocks create.
if await seed_preset_first_message(client, session_id, args.agent_id):
sys.stderr.write(
f". first_message: seeded preset opening for {args.agent_id}\n"
)
@@ -882,16 +879,34 @@ async def _set_persona_probe(args: ParsedArgs) -> int:
"(pleasure,arousal,dominance), e.g. '0.4,0.1,-0.2'\n"
)
return 10
# Canonical POST /sessions/{id}/persona_state body (#317): a named-key dict,
# NOT a bare list — {"pad": {"pleasure", "arousal", "dominance"}}.
snapshot = {"pad": {"pleasure": pad[0], "arousal": pad[1], "dominance": pad[2]}}
async with _probe_client(args) as client:
# The SDK rejects a non-finite axis pre-HTTP (a NaN/Infinity would serialize to
# null and corrupt the injection). Reject it here as a usage error so the probe
# surfaces a clean message instead of crashing on the SDK's ConfigurationError.
if not all(math.isfinite(x) for x in pad):
sys.stderr.write(
"[usage_error] --set-persona-pad values must be finite floats (no nan/inf)\n"
)
return 10
async with _probe_client(args) as transport:
client = wt.build_client(args.server_url, api_key=args.api_key, transport=transport)
try:
await set_persona_state(client, args.session_id, snapshot)
except SessionApiFailed as exc:
sys.stderr.write(f"[session_api_failed] status={exc.status} body={exc.body!r}\n")
# The SDK owns the canonical {"pad": {...}} wire body (#317); ratatoskr
# passes the three PAD axes and no longer hand-builds the snapshot.
await wt.set_persona_state(
client, args.session_id, pleasure=pad[0], arousal=pad[1], dominance=pad[2]
)
except wt.SessionApiFailed as exc:
sys.stderr.write(
f"[session_api_failed] status={exc.status} "
f"error_code={exc.error_code!r} body={exc.body!r}\n"
)
return 20
except (httpx.ConnectError, httpx.ReadTimeout, httpx.TransportError) as exc:
except (
httpx.ConnectError,
httpx.ReadTimeout,
httpx.TransportError,
ConnectFailed, # SDK normalizes a pre-response transport failure here
) as exc:
sys.stderr.write(f"[network_error] {type(exc).__name__}: {exc}\n")
return 21
sys.stdout.write(
@@ -914,19 +929,23 @@ async def _seed_first_message_probe(args: ParsedArgs) -> int:
"""
assert isinstance(args, ParsedArgs)
assert args.agent_id is not None and args.seed_first_message is not None
async with _probe_client(args) as client:
async with _probe_client(args) as transport:
client = wt.build_client(args.server_url, api_key=args.api_key, transport=transport)
try:
session = await create_session(
# wt.create_session returns the SDK's open-world create dict; read as a
# mapping (no SessionInfo dataclass — the hand-rolled path is retired).
session = await wt.create_session(
client, args.agent_id, end_user_id=args.end_user_id
)
sys.stdout.write(f"session: {session.session_id} (agent {session.agent_id})\n")
session_id = session["session_id"]
sys.stdout.write(f"session: {session_id} (agent {session.get('agent_id')})\n")
key = "ratatoskr-first-message-" + hashlib.sha256(
args.seed_first_message.encode("utf-8")
).hexdigest()[:12]
try:
ack = await write_authored_history(
ack = await wt.write_authored_history(
client,
session.session_id,
session_id,
content=args.seed_first_message,
idempotency_key=key,
)
@@ -941,17 +960,25 @@ async def _seed_first_message_probe(args: ParsedArgs) -> int:
f"seeded: seq={ack.get('seq')} phase={ack.get('phase')} "
f"turn_id={ack.get('turn_id')} content_chars={ack.get('content_chars')}\n"
)
history = await get_session_messages(client, session.session_id)
history = await wt.get_session_messages(client, session_id)
items = history.get("items", [])
sys.stdout.write(f"read-back: {len(items)} message(s)\n")
for m in items:
sys.stdout.write(
f" seq={m.get('seq')} role={m.get('role')} content={m.get('content')!r}\n"
)
except SessionApiFailed as exc:
sys.stderr.write(f"[session_api_failed] status={exc.status} body={exc.body!r}\n")
except wt.SessionApiFailed as exc:
sys.stderr.write(
f"[session_api_failed] status={exc.status} "
f"error_code={exc.error_code!r} body={exc.body!r}\n"
)
return 20
except (httpx.ConnectError, httpx.ReadTimeout, httpx.TransportError) as exc:
except (
httpx.ConnectError,
httpx.ReadTimeout,
httpx.TransportError,
ConnectFailed, # SDK normalizes a pre-response transport failure here
) as exc:
sys.stderr.write(f"[network_error] {type(exc).__name__}: {exc}\n")
return 21
return 0
+6 -6
View File
@@ -14,12 +14,12 @@ blocked (the session simply opens with no seeded greeting). See
import asyncio
import hashlib
import httpx
from worldtree_sdk import WorldtreeClient
from ratatoskr.sessions import write_authored_history
from ratatoskr import wt
# Cap the best-effort seed write. The CLI/TUI create paths reuse an httpx client
# with NO read timeout (it streams SSE turns), so an accepted-but-never-answered
# Cap the best-effort seed write. The CLI create path reuses a transport with NO
# read timeout (it streams SSE turns), so an accepted-but-never-answered
# POST /history would otherwise block session creation forever — violating INV-001's
# "never block". asyncio.wait_for bounds the seed regardless of the client's timeout.
_SEED_TIMEOUT_S = 10.0
@@ -39,7 +39,7 @@ def preset_for(agent_id: str) -> str | None:
async def seed_preset_first_message(
client: httpx.AsyncClient, session_id: str, agent_id: str
client: WorldtreeClient, session_id: str, agent_id: str
) -> str | None:
"""Best-effort: seed ``agent_id``'s preset opening as a #347 authored
first-message on ``session_id``; return the seeded text, or None.
@@ -64,7 +64,7 @@ async def seed_preset_first_message(
key = "ratatoskr-preset-" + hashlib.sha256(content.encode("utf-8")).hexdigest()[:12]
try:
await asyncio.wait_for(
write_authored_history(
wt.write_authored_history(
client, session_id, content=content, idempotency_key=key
),
timeout=_SEED_TIMEOUT_S,
+9 -4
View File
@@ -27,7 +27,11 @@ import os
from dataclasses import asdict, dataclass
from pathlib import Path
_SCHEMA_VERSION = 1
# v2 (worldtree-sdk cutover slice-4): `model` → `role`. The field holds what the
# Worldtree wire now calls a role (spec 1.2 / b128, the define response echoes
# `role`); the version bump discards any pre-cutover on-disk index cleanly
# (no-backwards-compat — old `{"model": …}` rows are dropped, re-defined fresh).
_SCHEMA_VERSION = 2
@dataclass(frozen=True)
@@ -37,16 +41,17 @@ class LocalAgentEntry:
Schema:
- ``agent_id``: full "user_id:agent_name" string (Worldtree-owned).
- ``agent_name``: slug from define (display name).
- ``model``: provider model ID at last define/patch.
- ``role``: model-role at last define/patch (e.g. "thoughtful-character";
the define/patch response's ``role`` field, W-4 resolved / b128).
- ``description``: synthetic display string (typically derived from
the system_prompt's first line + a "(tier 3)" prefix; the picker
uses this in its ``{id} · {name}{description}`` rendering).
- ``defined_at``: ISO-8601 timestamp from the Tier3AgentInfo response.
- ``defined_at``: ISO-8601 timestamp from the define/patch response.
"""
agent_id: str
agent_name: str
model: str
role: str
description: str
defined_at: str
+63 -326
View File
@@ -5,61 +5,12 @@ Implements docs/contracts/issues/2.contract.md.
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any
import httpx
@dataclass(frozen=True)
class SessionInfo:
"""Worldtree session envelope; shared shape for create + list responses.
INV-001 / INV-002: origin-conditional defaults — `create_session` sets fixed
`name=None`, `archived=False`, `tags=[]`; `list_sessions` populates from the
response item with the same absent/null defaults but `message_count=None`.
Amendment 2026-07-18 (issue #161): `kind` ("ephemeral" | "foundational") and
`config` (the frozen ephemeral config, create-origin only) captured defensively
via `.get()` — both `None` on a pre-cutover server that omits them.
"""
session_id: str
agent_id: str
created_at: str
last_active: str
metadata: dict[str, Any]
message_count: int | None
name: str | None
archived: bool
tags: list[str]
kind: str | None = None
config: dict[str, Any] | None = None
@dataclass(frozen=True)
class AgentInfo:
"""Worldtree agent envelope from GET /agents (issue #8).
INV-005: required fields (`agent_id`, `name`, `description`) take the
response value verbatim. Optional fields default to None / [] / {} when
omitted by the server, mirroring SessionInfo's INV-001/INV-002
origin-conditional defaulting.
"""
agent_id: str
name: str
description: str
version: str | None
capabilities: list[str]
supported_models: list[str]
persona_traits: dict[str, Any]
ui_hints: dict[str, Any]
@dataclass(frozen=True)
class BifrostBinding:
"""Session-create Bifrost binding (Worldtree BifrostBindingRequest, #160).
@@ -198,6 +149,68 @@ class AuthoredHistoryUnavailable(Exception):
self.session_id = session_id
# ── Tier-3 (consumer-defined) agent lifecycle exceptions ─────────────────────
# The worldtree-sdk adapter (`ratatoskr.wt`) re-raises these from the agents.define/
# patch/delete routes. They live HERE (not in `tier3`) so both `wt` and the
# `python -m ratatoskr.tier3` CLI reference the SAME class objects: `tier3` is run as
# `__main__`, and if these were defined there, `wt`'s `from .tier3 import …` would bind
# a SECOND copy under `ratatoskr.tier3` — so a raised exception would not match the
# CLI's `except` (the exception would escape as an uncaught traceback). Homing them in
# `sessions` (never run as `__main__`) makes the class identity single.
class Tier3QuotaExceeded(Exception):
"""Raised on HTTP 429 ``agent_quota_exceeded`` — 50-agent cap reached
on the Heimdall key. ``retry_after`` captures the Retry-After header
verbatim (defaults to 0 per spec §2675; forward-compat for non-zero).
Post-cutover the adapter constructs this with ``retry_after=0`` — the SDK's
``ApiError`` floor carries no response headers, and §2675 pins Phase-2.0 quota
to ``Retry-After: 0``, so the value is spec-canonical."""
def __init__(self, *, retry_after: int) -> None:
super().__init__(f"Tier 3 agent quota exceeded (retry_after={retry_after})")
self.retry_after = retry_after
class Tier3UserIdUnsupported(Exception):
"""Raised on HTTP 403 ``tier3_user_id_unsupported`` — auth's user_id
is not slug-safe per Phase 2.0 gate (spec §2626)."""
def __init__(self) -> None:
super().__init__("tier3 caller user_id is not slug-safe")
class Tier3FieldNotMutable(Exception):
"""Raised on HTTP 422 ``field_not_mutable`` — PATCH request body
carried a key that's immutable post-define (``agent_name``, ``user_id``,
or any layer field). Server rejects BEFORE the DB lookup (spec §2644)."""
def __init__(self, *, field: str | None) -> None:
super().__init__(f"field not mutable on Tier 3 patch: {field!r}")
self.field = field
class Tier3LayerDeferred(Exception):
"""Raised on HTTP 422 ``layer_deferred`` — define request carried a
non-null layer field (``persona`` / ``motivational`` / ``valence`` /
``memory``). Phase 2.0 ships baseline only; layers are schema-reserved.
Note: ``define_agent`` never sends layer fields, so this exception is
defense-against-server-side-changes / forward-compat."""
def __init__(self, *, field: str | None) -> None:
super().__init__(f"tier3 layer field deferred: {field!r}")
self.field = field
class Tier3AgentNotFound(Exception):
"""Raised on HTTP 404 — PATCH or DELETE on a non-existent agent_id
(spec §2634 + §2641)."""
def __init__(self, *, agent_id: str) -> None:
super().__init__(f"tier3 agent not found: {agent_id!r}")
self.agent_id = agent_id
def endpoint_for_plane(plane: str, base_host: str) -> str:
@@ -213,191 +226,10 @@ def endpoint_for_plane(plane: str, base_host: str) -> str:
"""
ports = {"memory": 8391, "affect": 8390, "combined": 8392}
if plane not in ports:
raise ValueError(
f"unknown plane: {plane!r} "
"(expected 'memory', 'affect', or 'combined')"
)
raise ValueError(f"unknown plane: {plane!r} (expected 'memory', 'affect', or 'combined')")
return f"http://{base_host}:{ports[plane]}"
def _bifrost_error_from(resp: httpx.Response) -> str | None:
"""Pull the spec-level `bifrost_error` from a 502 body.
Tolerates both the FastAPI-nested `{"detail": {"bifrost_error": …}}` shape
(the spec's documented form, §"Optional Bifrost binding") and a flat
top-level `bifrost_error`, per the both-shape unwrap precedent established for
persona_state errors (the real wire returns the detail-nested form).
"""
try:
err = resp.json()
except ValueError:
return None
if not isinstance(err, dict):
return None
bifrost_error = err.get("bifrost_error")
if bifrost_error is None and isinstance(err.get("detail"), dict):
bifrost_error = err["detail"].get("bifrost_error")
return bifrost_error
async def create_session(
client: httpx.AsyncClient,
agent_id: str,
*,
end_user_id: str | None = None,
bifrost: BifrostBinding | None = None,
consumer_key: str | None = None,
config: Mapping[str, Any] | None = None,
) -> SessionInfo:
"""POST /sessions to create a new session. See contract FN create_session.
Per issue #5: pass `end_user_id` for per-end-user agents (lofn etc.).
When None (default), the body shape matches the pre-#5 baseline
`{"agent_id": agent_id}` so existing callers (mimir smoke) are unaffected.
Empty-string `end_user_id` is rejected before HTTP (PRE-003).
Per issue #17: when `bifrost` is set the request carries the binding and
authenticates with `consumer_key` (NOT the client's default canary bearer);
Worldtree handshakes synchronously to our provider before 201.
"""
assert client is not None
assert agent_id and isinstance(agent_id, str)
assert end_user_id is None or (isinstance(end_user_id, str) and end_user_id)
# PRE-004 (issue #161): config is None or a Mapping.
assert config is None or isinstance(config, Mapping)
# PRE-005 (issue #161): ephemeral config + Bifrost binding are mutually
# exclusive (server would 422 ephemeral_does_not_accept_bifrost). The CLI
# guards this at arg-parse; this assert is defense-in-depth.
assert not (config is not None and bifrost is not None)
# PRE-001 (INV-001): a bifrost binding REQUIRES a non-empty consumer key,
# enforced before any HTTP so a bound create never falls back to the canary.
if bifrost is not None and not (isinstance(consumer_key, str) and consumer_key):
raise BifrostConsumerKeyMissing()
body: dict[str, Any] = {"agent_id": agent_id}
if end_user_id is not None:
body["end_user_id"] = end_user_id
# Issue #161: ephemeral-template config passthrough — verbatim, role/model-
# agnostic. The caller (CLI) builds {"system_prompt": ...}; the wrapper never
# injects a selector. Absent when None (foundational baseline unchanged).
if config is not None:
body["config"] = dict(config)
headers: dict[str, str] = {}
if bifrost is not None:
body["bifrost"] = {
"endpoint_url": bifrost.endpoint_url,
"scope": bifrost.scope,
}
# INV-001: the bound create authenticates with the consumer key,
# overriding the httpx client's default canary bearer per-request.
headers["Authorization"] = f"Bearer {consumer_key}"
resp = await client.post("/sessions", json=body, headers=headers)
if resp.status_code == 404:
raise AgentNotFound(agent_id=agent_id)
# POST-002 (INV-002): a 502 on a BOUND create is the synchronous Bifrost
# handshake failing. Gated on `bifrost is not None` — an unbound create's
# 502 is a generic upstream fault and stays SessionApiFailed.
if bifrost is not None and resp.status_code == 502:
raise BifrostHandshakeFailed(
bifrost_error=_bifrost_error_from(resp), body=resp.content
)
if resp.status_code != 201:
raise SessionApiFailed(status=resp.status_code, body=resp.content)
body = resp.json()
return SessionInfo(
session_id=body["session_id"],
agent_id=body["agent_id"],
created_at=body["created_at"],
last_active=body["last_active"],
metadata=body.get("metadata", {}),
message_count=body["message_count"],
name=None,
archived=False,
tags=[],
kind=body.get("kind"), # INV-001 amendment (#161): "ephemeral"|"foundational"|None
config=body.get("config"), # frozen ephemeral config; None for foundational
)
async def list_agents(client: httpx.AsyncClient) -> list[AgentInfo]:
"""GET /agents — list available agents. See contract FN list_agents (issue #8).
No request params, no pagination. Returns server-ordered list. Optional
fields are defaulted to None / [] / {} per INV-005.
"""
assert client is not None
resp = await client.get("/agents")
if resp.status_code != 200:
raise SessionApiFailed(status=resp.status_code, body=resp.content)
body = resp.json()
return [
AgentInfo(
agent_id=item["agent_id"],
name=item["name"],
description=item["description"],
version=item.get("version"),
capabilities=item.get("capabilities") or [],
supported_models=item.get("supported_models") or [],
persona_traits=item.get("persona_traits") or {},
ui_hints=item.get("ui_hints") or {},
)
for item in body
]
async def get_persona_state(
client: httpx.AsyncClient, agent_id: str
) -> dict[str, Any]:
"""GET /agents/{agent_id}/persona_state — fetch current persona snapshot.
Worldtree #204 / v0.28.0. Returns the same `snapshot` dict shape as the
`affect_update` SSE event's `status="current"` emission: pad,
dominant_emotion, emotions_active, baseline_pad, mood_drift,
last_updated_at. Bootstrap read for clients that want to populate a
persona pane on session-open without waiting for turn-1's `affect_update`.
Auth: requires Heimdall `persona.read` scope (user-tier default).
Failure modes (mapped to typed exceptions per the spec error_codes):
- 404 `persona_not_configured` → PersonaNotConfigured (persona-disabled
agents: domari / muninn, and all Tier 3 in Phase 2.0)
- 404 `agent_not_available` → AgentNotAvailable (unknown agent_id)
- 403 `auth_scope_denied` → AuthScopeDenied (key lacks persona.read)
- any other non-2xx → SessionApiFailed (preserves the broader-error
precedent from list_agents / list_sessions / create_session)
"""
assert client is not None
assert agent_id and isinstance(agent_id, str)
resp = await client.get(f"/agents/{agent_id}/persona_state")
if resp.status_code == 200:
return resp.json()
# Discriminate the 4xx error_code sub-codes; everything else falls
# through. Worldtree returns errors as either flat `{"error_code": …}`
# OR FastAPI-default `{"detail": {"error_code": …}}` depending on
# which handler raised — unwrap both shapes (real wire observed
# 2026-05-28 returning the detail-nested form for auth_scope_denied
# from /agents/{id}/persona_state).
try:
err = resp.json()
except ValueError:
err = None
error_code: str | None = None
if isinstance(err, dict):
error_code = err.get("error_code")
if error_code is None and isinstance(err.get("detail"), dict):
error_code = err["detail"].get("error_code")
if resp.status_code == 404 and error_code == "persona_not_configured":
raise PersonaNotConfigured(agent_id=agent_id)
if resp.status_code == 404 and error_code == "agent_not_available":
raise AgentNotAvailable(agent_id=agent_id)
if resp.status_code == 403 and error_code == "auth_scope_denied":
raise AuthScopeDenied(scope="persona.read")
raise SessionApiFailed(status=resp.status_code, body=resp.content)
async def get_me(client: httpx.AsyncClient) -> dict[str, Any]:
"""GET /me — the authenticated principal's identity + key metadata (spec §GET /me).
@@ -473,27 +305,6 @@ async def delete_character(client: httpx.AsyncClient, character_id: str) -> None
raise SessionApiFailed(status=resp.status_code, body=resp.content)
async def set_persona_state(
client: httpx.AsyncClient, session_id: str, snapshot: dict[str, Any]
) -> None:
"""POST /sessions/{session_id}/persona_state — set a session's persona state (affect injection).
The request body is FREEFORM on the wire (the OpenAPI declares no request
schema), but worldtree-dev's prose now pins the canonical shape (#317):
`{"pad": {"pleasure": p, "arousal": a, "dominance": d}}` — a named-key dict
(each in [-1, 1]), NOT a bare list; PAD-only, session-scoped, pull-over-push
(#289). The caller supplies the snapshot. 204 No Content → None; any other
status → SessionApiFailed.
"""
assert client is not None
assert session_id and isinstance(session_id, str)
assert isinstance(snapshot, dict)
resp = await client.post(f"/sessions/{session_id}/persona_state", json=snapshot)
if resp.status_code == 204:
return None
raise SessionApiFailed(status=resp.status_code, body=resp.content)
async def get_session_bifrost(
client: httpx.AsyncClient, session_id: str, *, admin_key: str
) -> dict[str, Any]:
@@ -519,8 +330,6 @@ async def get_session_bifrost(
raise SessionApiFailed(status=resp.status_code, body=resp.content)
async def get_capabilities(client: httpx.AsyncClient) -> dict[str, Any]:
"""GET /capabilities — server capability discovery (spec §Ephemeral Templates).
@@ -534,75 +343,3 @@ async def get_capabilities(client: httpx.AsyncClient) -> dict[str, Any]:
if resp.status_code == 200:
return resp.json()
raise SessionApiFailed(status=resp.status_code, body=resp.content)
async def write_authored_history(
client: httpx.AsyncClient,
session_id: str,
*,
content: str,
idempotency_key: str,
author: str = "assistant",
effects: str | None = None,
claimed_original_at: str | None = None,
) -> dict[str, Any]:
"""POST /sessions/{session_id}/history — the #347 authored-history-write primitive.
Write one model-visible turn into the session's ledger AS the bound agent,
WITHOUT a generation and WITHOUT lived-turn side effects (the SillyTavern
"first message"). v1: `author="assistant"`, `effects` omitted (== "none"),
`idempotency_key` REQUIRED (per-session dedup). The server pins the body
(`AuthoredWriteRequest`, `extra="forbid"`), so `effects` /
`claimed_original_at` are sent only when non-None — never as null keys.
Success is 201 (fresh) or 200 (idempotent replay, byte-identical body); both
return the `AuthoredTurnResponse` dict verbatim (`{author, content_chars,
injected_at, phase, seq, session_id, turn_id}` — provenance is audit-only,
never on this body).
404 → `AuthoredHistoryUnavailable` (hide-existence: feature-absent /
ungranted / session-absent are indistinguishable by design; the caller falls
back and NEVER capability-probes — server INV-347-1). Any other non-2xx →
`SessionApiFailed` (notably 409 `generation_active`, 422 `content_too_long` /
`validation_failed`).
"""
assert client is not None
assert session_id and isinstance(session_id, str)
assert content and isinstance(content, str)
assert idempotency_key and isinstance(idempotency_key, str)
assert author and isinstance(author, str)
body: dict[str, Any] = {
"author": author,
"content": content,
"idempotency_key": idempotency_key,
}
if effects is not None:
body["effects"] = effects
if claimed_original_at is not None:
body["claimed_original_at"] = claimed_original_at
resp = await client.post(f"/sessions/{session_id}/history", json=body)
if resp.status_code in (200, 201):
return resp.json()
if resp.status_code == 404:
raise AuthoredHistoryUnavailable(session_id=session_id)
raise SessionApiFailed(status=resp.status_code, body=resp.content)
async def get_session_messages(
client: httpx.AsyncClient, session_id: str
) -> dict[str, Any]:
"""GET /sessions/{session_id}/messages — the session's message history.
Un-deferred as the #347 seed read-back: a seeded turn renders as a normal
`role=assistant` message (model-invisible provenance — indistinguishable
from a lived turn on read). Returns `{session_id, items: [{seq, role,
content, ...}], next_cursor}` verbatim; owner-scoped; any non-200 →
`SessionApiFailed`. v1 reads the server default page (no pagination params —
add limit/cursor when a caller needs scrollback).
"""
assert client is not None
assert session_id and isinstance(session_id, str)
resp = await client.get(f"/sessions/{session_id}/messages")
if resp.status_code == 200:
return resp.json()
raise SessionApiFailed(status=resp.status_code, body=resp.content)
+77 -287
View File
@@ -1,259 +1,43 @@
"""Worldtree Tier 3 (consumer-defined) agent lifecycle client.
"""Worldtree Tier 3 (consumer-defined) agent CLI + caller-semantic exceptions.
Implements docs/contracts/issues/15.contract.md. Caller-owned httpx.AsyncClient
posture (same as ratatoskr.sessions). Exposes three lifecycle operations:
The define / patch / delete wire calls route through the worldtree-sdk adapter
(``ratatoskr.wt.define_agent`` / ``patch_agent`` / ``delete_agent``); this module owns
the ``python -m ratatoskr.tier3`` CLI and the Tier-3 caller-semantic exception
taxonomy the adapter re-raises (quota / user-id / field-not-mutable / layer-deferred /
not-found). The picker already handles colon-containing agent_ids generically
(issue #8).
- ``define_agent`` — POST /agents/define
- ``patch_agent`` — PATCH /agents/<id>
- ``delete_agent`` — DELETE /agents/<id>
Plus a frozen ``Tier3AgentInfo`` dataclass for the response shape. The picker
already handles colon-containing agent_ids generically (issue #8); session
creation works unchanged via ``ratatoskr.sessions.create_session``.
Spec reference: ``docs/conversation-api-spec.md`` §2576-2750 (Phase 2.0).
The old hand-rolled httpx wrappers + the ``Tier3AgentInfo`` dataclass were deleted in
the worldtree-sdk cutover (issue #20, slice-4); the adapter returns the SDK's
open-world define/patch dicts (echoing ``role`` post-b128, spec 1.2), read here as
mappings. ``wt`` imports this module's exceptions at module level; this module imports
``wt`` only lazily inside the CLI handlers, so there is no import cycle.
"""
from __future__ import annotations
import argparse
import re
from dataclasses import dataclass
import httpx
from ratatoskr.sessions import SessionApiFailed
# Per spec §2627: agent_name + user_id slugs are `[a-z][a-z0-9-]{2,63}`.
_SLUG_RE = re.compile(r"^[a-z][a-z0-9-]{2,63}$")
@dataclass(frozen=True)
class Tier3AgentInfo:
"""Worldtree Tier 3 agent envelope returned by define / patch.
INV-001: ``agent_id`` is always shape ``"<user_id>:<agent_name>"`` —
constructed server-side from the auth's user_id + the supplied agent_name.
"""
agent_id: str
user_id: str
agent_name: str
system_prompt: str
model: str
created_at: str
updated_at: str
class Tier3QuotaExceeded(Exception):
"""Raised on HTTP 429 ``agent_quota_exceeded`` — 50-agent cap reached
on the Heimdall key. ``retry_after`` captures the Retry-After header
verbatim (defaults to 0 per spec §2675; forward-compat for non-zero)."""
def __init__(self, *, retry_after: int) -> None:
super().__init__(f"Tier 3 agent quota exceeded (retry_after={retry_after})")
self.retry_after = retry_after
class Tier3UserIdUnsupported(Exception):
"""Raised on HTTP 403 ``tier3_user_id_unsupported`` — auth's user_id
is not slug-safe per Phase 2.0 gate (spec §2626)."""
def __init__(self) -> None:
super().__init__("tier3 caller user_id is not slug-safe")
class Tier3FieldNotMutable(Exception):
"""Raised on HTTP 422 ``field_not_mutable`` — PATCH request body
carried a key that's immutable post-define (``agent_name``, ``user_id``,
or any layer field). Server rejects BEFORE the DB lookup (spec §2644)."""
def __init__(self, *, field: str | None) -> None:
super().__init__(f"field not mutable on Tier 3 patch: {field!r}")
self.field = field
class Tier3LayerDeferred(Exception):
"""Raised on HTTP 422 ``layer_deferred`` — define request carried a
non-null layer field (``persona`` / ``motivational`` / ``valence`` /
``memory``). Phase 2.0 ships baseline only; layers are schema-reserved.
Note: ``define_agent`` never sends layer fields, so this exception is
defense-against-server-side-changes / forward-compat. INV-001 in the
request body construction is the first line of defense.
"""
def __init__(self, *, field: str | None) -> None:
super().__init__(f"tier3 layer field deferred: {field!r}")
self.field = field
class Tier3AgentNotFound(Exception):
"""Raised on HTTP 404 — PATCH or DELETE on a non-existent agent_id
(spec §2634 + §2641)."""
def __init__(self, *, agent_id: str) -> None:
super().__init__(f"tier3 agent not found: {agent_id!r}")
self.agent_id = agent_id
def _extract_error_code(resp: httpx.Response) -> str | None:
"""Pluck the ``detail.error_code`` from a Worldtree error envelope.
Worldtree wraps API errors in ``{"detail": {"error_code": "...", ...}}``
per the spec. Returns None on shape mismatch (so callers fall through
to the generic ``SessionApiFailed`` branch).
"""
try:
body = resp.json()
except ValueError:
return None
detail = body.get("detail") if isinstance(body, dict) else None
if isinstance(detail, dict):
code = detail.get("error_code")
if isinstance(code, str):
return code
return None
def _extract_error_field(resp: httpx.Response) -> str | None:
"""Pluck ``detail.field`` from a Worldtree error envelope (used for
``field_not_mutable`` and ``layer_deferred`` to surface which field
triggered the rejection). Returns None on shape mismatch.
"""
try:
body = resp.json()
except ValueError:
return None
detail = body.get("detail") if isinstance(body, dict) else None
if isinstance(detail, dict):
field = detail.get("field")
if isinstance(field, str):
return field
return None
def _parse_tier3_agent_info(body: dict) -> Tier3AgentInfo:
"""Parse a Worldtree Tier 3 agent JSON body into the frozen dataclass."""
return Tier3AgentInfo(
agent_id=body["agent_id"],
user_id=body["user_id"],
agent_name=body["agent_name"],
system_prompt=body["system_prompt"],
model=body["model"],
created_at=body["created_at"],
updated_at=body["updated_at"],
)
async def define_agent(
client: httpx.AsyncClient,
*,
agent_name: str,
system_prompt: str,
role: str,
) -> Tier3AgentInfo:
"""POST /agents/define — create a Tier 3 agent.
See contract FN define_agent. Validates the agent_name slug client-side
before the network round-trip; server-side validation is the safety net.
Returns a fully populated Tier3AgentInfo on 201. Routes documented error
codes to typed exceptions; unknown non-2xx → SessionApiFailed.
"""
assert client is not None
assert _SLUG_RE.match(agent_name), (
f"agent_name must match [a-z][a-z0-9-]{{2,63}}: {agent_name!r}"
)
assert system_prompt, "system_prompt must be non-empty"
assert role, "role must be non-empty"
# b125 drift: /agents/define takes `role` (a model-role, e.g. "thoughtful-character")
# in the request; the response echoes it back as `model`. See #15 follow-up.
body = {
"agent_name": agent_name,
"system_prompt": system_prompt,
"role": role,
}
resp = await client.post("/agents/define", json=body)
if resp.status_code == 201:
return _parse_tier3_agent_info(resp.json())
if resp.status_code == 429:
# Spec §2675: 51st define → 429 with Retry-After: 0.
try:
retry_after = int(resp.headers.get("Retry-After", "0"))
except (TypeError, ValueError):
retry_after = 0
raise Tier3QuotaExceeded(retry_after=retry_after)
if resp.status_code == 403:
if _extract_error_code(resp) == "tier3_user_id_unsupported":
raise Tier3UserIdUnsupported()
if resp.status_code == 422:
code = _extract_error_code(resp)
if code == "layer_deferred":
raise Tier3LayerDeferred(field=_extract_error_field(resp))
raise SessionApiFailed(status=resp.status_code, body=resp.content)
async def patch_agent(
client: httpx.AsyncClient,
agent_id: str,
*,
system_prompt: str | None = None,
role: str | None = None,
) -> Tier3AgentInfo:
"""PATCH /agents/<id> — mutate system_prompt and/or model.
See contract FN patch_agent. Per spec §2641: only system_prompt + model
are mutable in Phase 2.0; any other key returns 422 field_not_mutable.
"""
assert client is not None
assert ":" in agent_id, f"tier 3 agent_id must contain ':': {agent_id!r}"
assert system_prompt is not None or role is not None, (
"patch requires at least one of system_prompt or role"
)
body: dict[str, str] = {}
if system_prompt is not None:
body["system_prompt"] = system_prompt
if role is not None:
body["role"] = role
resp = await client.patch(f"/agents/{agent_id}", json=body)
if resp.status_code == 200:
return _parse_tier3_agent_info(resp.json())
if resp.status_code == 404:
raise Tier3AgentNotFound(agent_id=agent_id)
if resp.status_code == 422:
code = _extract_error_code(resp)
if code == "field_not_mutable":
raise Tier3FieldNotMutable(field=_extract_error_field(resp))
raise SessionApiFailed(status=resp.status_code, body=resp.content)
async def delete_agent(client: httpx.AsyncClient, agent_id: str) -> None:
"""DELETE /agents/<id> — owner hard-delete (cancels active sessions
server-side per spec §2636).
See contract FN delete_agent. 204 on success; 404 if the agent_id
doesn't exist; other non-2xx → SessionApiFailed.
"""
assert client is not None
assert ":" in agent_id, f"tier 3 agent_id must contain ':': {agent_id!r}"
resp = await client.delete(f"/agents/{agent_id}")
if resp.status_code == 204:
return
if resp.status_code == 404:
raise Tier3AgentNotFound(agent_id=agent_id)
raise SessionApiFailed(status=resp.status_code, body=resp.content)
# The Tier-3 caller-semantic exceptions live in `sessions` (never run as `__main__`)
# so the adapter's raise and this CLI's `except` reference the SAME class objects —
# see the header note in `sessions.py`. `main()` catches these; `wt` raises them.
from ratatoskr.sessions import (
Tier3AgentNotFound,
Tier3FieldNotMutable,
Tier3LayerDeferred,
Tier3QuotaExceeded,
Tier3UserIdUnsupported,
)
# ---- CLI (`python -m ratatoskr.tier3 <subcommand>`) ------------------------
#
# Auth + server URL resolution mirrors ratatoskr.cli verbatim. Exit codes
# mirror ratatoskr.cli: 0 happy / 10 usage / 11 auth / 20 api-failure /
# 21 network. Outbound requests carry the same User-Agent string.
# 21 network. Outbound requests carry the same User-Agent string. The wire calls
# route through the worldtree-sdk adapter (ratatoskr.wt) over a ratatoskr-owned
# injected transport (INV-CUT-1: the SDK never closes it).
class _Tier3UsageError(Exception):
@@ -284,7 +68,7 @@ def _build_parser() -> argparse.ArgumentParser:
help="Model role, e.g. thoughtful-character (see GET /models/available-for-characters).",
)
p_patch = sub.add_parser("patch", help="Mutate system_prompt and/or model.")
p_patch = sub.add_parser("patch", help="Mutate system_prompt and/or role.")
p_patch.add_argument("agent_id", help='Full "<user_id>:<agent_name>" form.')
p_patch.add_argument("--system-prompt", dest="system_prompt", default=None)
p_patch.add_argument("--role", default=None)
@@ -308,46 +92,54 @@ def _resolve_auth(ns: argparse.Namespace) -> tuple[str, str]:
return api_key, server_url
def _transport(server_url: str, api_key: str) -> httpx.AsyncClient:
"""The ratatoskr-owned httpx transport the adapter's WorldtreeClient is built
over. Carries the User-Agent + a generous read timeout for agent CRUD; the SDK
re-applies auth per request (the default bearer here just mirrors it)."""
from ratatoskr.cli import USER_AGENT
return httpx.AsyncClient(
base_url=server_url,
headers={"Authorization": f"Bearer {api_key}", "User-Agent": USER_AGENT},
timeout=httpx.Timeout(connect=10.0, read=30.0, write=10.0, pool=10.0),
)
async def _run_define(ns: argparse.Namespace) -> int:
api_key, server_url = _resolve_auth(ns)
from ratatoskr.cli import USER_AGENT
from ratatoskr import wt
from ratatoskr.local_agents import (
LocalAgentEntry,
add_local_agent,
make_description,
)
async with httpx.AsyncClient(
base_url=server_url,
headers={
"Authorization": f"Bearer {api_key}",
"User-Agent": USER_AGENT,
},
timeout=httpx.Timeout(connect=10.0, read=30.0, write=10.0, pool=10.0),
) as client:
info = await define_agent(
async with _transport(server_url, api_key) as transport:
client = wt.build_client(server_url, api_key=api_key, transport=transport)
info = await wt.define_agent(
client,
agent_name=ns.name,
system_prompt=ns.system_prompt,
role=ns.role,
)
# v0.8.0: persist to local index so the picker can show it.
# v0.8.0: persist to local index so the picker can show it. The SDK returns
# the open-world define dict — read `role` (echoed post-b128), not `model`.
add_local_agent(
LocalAgentEntry(
agent_id=info.agent_id,
agent_name=info.agent_name,
model=info.model,
description=make_description(info.system_prompt),
defined_at=info.created_at,
agent_id=info["agent_id"],
agent_name=info["agent_name"],
role=info["role"],
description=make_description(info.get("system_prompt", "")),
defined_at=info.get("created_at", ""),
)
)
print(f"defined {info.agent_id} ({info.model})")
print(f"defined {info['agent_id']} ({info['role']})")
return 0
async def _run_patch(ns: argparse.Namespace) -> int:
api_key, server_url = _resolve_auth(ns)
from ratatoskr.cli import USER_AGENT
from ratatoskr import wt
from ratatoskr.local_agents import (
LocalAgentEntry,
make_description,
@@ -358,15 +150,9 @@ async def _run_patch(ns: argparse.Namespace) -> int:
raise _Tier3UsageError(
"patch requires at least one of --system-prompt or --role"
)
async with httpx.AsyncClient(
base_url=server_url,
headers={
"Authorization": f"Bearer {api_key}",
"User-Agent": USER_AGENT,
},
timeout=httpx.Timeout(connect=10.0, read=30.0, write=10.0, pool=10.0),
) as client:
info = await patch_agent(
async with _transport(server_url, api_key) as transport:
client = wt.build_client(server_url, api_key=api_key, transport=transport)
info = await wt.patch_agent(
client,
ns.agent_id,
system_prompt=ns.system_prompt,
@@ -375,31 +161,25 @@ async def _run_patch(ns: argparse.Namespace) -> int:
# v0.8.0: refresh local index with the post-patch state.
update_local_agent(
LocalAgentEntry(
agent_id=info.agent_id,
agent_name=info.agent_name,
model=info.model,
description=make_description(info.system_prompt),
defined_at=info.updated_at,
agent_id=info["agent_id"],
agent_name=info["agent_name"],
role=info["role"],
description=make_description(info.get("system_prompt", "")),
defined_at=info.get("updated_at", ""),
)
)
print(f"patched {info.agent_id}")
print(f"patched {info['agent_id']}")
return 0
async def _run_delete(ns: argparse.Namespace) -> int:
api_key, server_url = _resolve_auth(ns)
from ratatoskr.cli import USER_AGENT
from ratatoskr import wt
from ratatoskr.local_agents import remove_local_agent
async with httpx.AsyncClient(
base_url=server_url,
headers={
"Authorization": f"Bearer {api_key}",
"User-Agent": USER_AGENT,
},
timeout=httpx.Timeout(connect=10.0, read=30.0, write=10.0, pool=10.0),
) as client:
await delete_agent(client, ns.agent_id)
async with _transport(server_url, api_key) as transport:
client = wt.build_client(server_url, api_key=api_key, transport=transport)
await wt.delete_agent(client, ns.agent_id)
# v0.8.0: drop from local index so the picker stops listing it.
remove_local_agent(ns.agent_id)
print(f"deleted {ns.agent_id}")
@@ -419,6 +199,10 @@ def main(argv: list[str] | None = None) -> int:
import asyncio
import sys
import worldtree_sdk as wtsdk
from ratatoskr.wt import SessionApiFailed
parser = _build_parser()
try:
ns = parser.parse_args(argv)
@@ -459,10 +243,16 @@ def main(argv: list[str] | None = None) -> int:
return 20
except SessionApiFailed as exc:
sys.stderr.write(
f"[api_failed] status={exc.status} body={exc.body!r}\n"
f"[api_failed] status={exc.status} "
f"error_code={exc.error_code!r} body={exc.body!r}\n"
)
return 20
except (httpx.ConnectError, httpx.ReadTimeout, httpx.TransportError) as exc:
except (
httpx.ConnectError,
httpx.ReadTimeout,
httpx.TransportError,
wtsdk.ConnectFailed, # SDK normalizes any pre-response transport failure here
) as exc:
sys.stderr.write(f"[network_error] {type(exc).__name__}: {exc}\n")
return 21
+30 -16
View File
@@ -26,7 +26,13 @@ from starlette.responses import (
)
from starlette.routing import Mount, Route
from starlette.staticfiles import StaticFiles
from worldtree_sdk import CancelledEvent, DoneEvent, ErrorEvent, WorldtreeClient
from worldtree_sdk import (
CancelledEvent,
ConnectFailed,
DoneEvent,
ErrorEvent,
WorldtreeClient,
)
from ratatoskr import local_agents as _local_agents
from ratatoskr import wt
@@ -41,15 +47,13 @@ from ratatoskr.sessions import (
PersonaNotConfigured,
SessionApiFailed,
endpoint_for_plane,
get_persona_state,
get_session_bifrost,
list_agents,
)
# The turn path (create / stream / cancel / tools / messages) is served by the
# worldtree-sdk adapter (`wt.*`), which raises ratatoskr's caller-semantic
# exceptions (DEC-2). The hand-rolled endpoints (persona / agents / admin /
# bifrost) stay on the `sessions` / `sse_client` wrappers until their own slices.
# The turn path (create / stream / cancel / tools / messages) AND the agents /
# persona-state reads are served by the worldtree-sdk adapter (`wt.*`), which raises
# ratatoskr's caller-semantic exceptions (DEC-2). The remaining hand-rolled endpoint
# (admin bifrost) stays on the `sessions` / `sse_client` wrappers until slice 6.
from ratatoskr.sse_client import (
AdminEvent,
CancelAlreadyCompleted,
@@ -124,18 +128,22 @@ async def _agents_endpoint(request: Request) -> JSONResponse:
client_factory = request.app.state.client_factory
try:
async with client_factory() as client:
upstream = await list_agents(client)
except SessionApiFailed as exc:
upstream = await wt.list_agents(_wt_client(client))
except wt.SessionApiFailed as exc:
return JSONResponse(
{"error_code": "session_api_failed", "status": exc.status},
status_code=exc.status,
)
except httpx.RequestError as exc:
except (httpx.RequestError, ConnectFailed) as exc:
# The SDK normalizes a transport failure to ConnectFailed(status=0), not a
# raw httpx error; both surface the same network envelope (slice-3 foot-gun).
return JSONResponse(
{"error_code": "network_error", "message": str(exc)},
status_code=502,
)
upstream_ids = {a.agent_id for a in upstream}
# Open-world upstream dicts (parity: no AgentInfo normalization); read `agent_id`
# as a mapping key. Local tier3 entries dedup against the upstream ids (remote-wins).
upstream_ids = {a["agent_id"] for a in upstream}
local = _local_agents.load_local_agents()
merged = [_as_dict(a) for a in upstream] + [
_as_dict(le) for le in local if le.agent_id not in upstream_ids
@@ -179,17 +187,17 @@ async def _create_session_endpoint(request: Request) -> JSONResponse:
try:
async with client_factory() as client:
wt_client = _wt_client(client)
info = await wt.create_session(
_wt_client(client),
wt_client,
agent_id,
end_user_id=end_user_id,
bifrost=bifrost,
consumer_key=consumer_key if bifrost else None,
)
# #347 authored first-message: seed the agent's preset opening (best-effort;
# never blocks create). first_message is a slice-3 hand-rolled path — it
# reuses the raw transport (its default bearer), not the adapter client.
await seed_preset_first_message(client, info["session_id"], agent_id)
# never blocks create). Routed through the wt adapter (slice-3).
await seed_preset_first_message(wt_client, info["session_id"], agent_id)
except AgentNotFound:
return JSONResponse({"error_code": "agent_not_found"}, status_code=404)
except BifrostConsumerKeyMissing:
@@ -433,13 +441,19 @@ async def _persona_state_endpoint(request: Request) -> JSONResponse:
client_factory = request.app.state.client_factory
try:
async with client_factory() as client:
snap = await get_persona_state(client, agent_id)
snap = await wt.get_persona_state(_wt_client(client), agent_id)
except PersonaNotConfigured:
return JSONResponse({"error_code": "persona_not_configured"}, status_code=404)
except AgentNotAvailable:
return JSONResponse({"error_code": "agent_not_available"}, status_code=404)
except AuthScopeDenied:
return JSONResponse({"error_code": "auth_scope_denied"}, status_code=403)
except (httpx.RequestError, ConnectFailed) as exc:
# SDK normalizes a transport failure to ConnectFailed(status=0) (slice-3
# foot-gun); surface the network envelope rather than a 500 crash.
return JSONResponse(
{"error_code": "network_error", "message": str(exc)}, status_code=502
)
return JSONResponse(snap, status_code=200)
+235 -4
View File
@@ -28,23 +28,36 @@ carries the SDK's parsed `error_code`).
from __future__ import annotations
import json
from collections.abc import AsyncGenerator, Mapping
import math
import re
from collections.abc import AsyncGenerator, Mapping, Sequence
from typing import Any
import httpx
import worldtree_sdk as wtsdk
from worldtree_sdk import ApiError, AuthProvider, CancelResult, WorldtreeClient
from worldtree_sdk import ApiError, AuthProvider, CancelResult, PadState, WorldtreeClient
# Transitional (slice-2): the caller-semantic exceptions + the BifrostBinding input
# Transitional (slice-2/3): the caller-semantic exceptions + the BifrostBinding input
# type still live in the retiring `sessions` / `sse_client` modules; they relocate
# into this adapter as their call-sites are rewired in later slice-2 commits. wt →
# into this adapter as their call-sites are rewired in later slices. wt →
# sessions / sse_client is one-way (neither imports wt), so there is no cycle.
from .sessions import (
AgentNotAvailable as PersonaAgentNotAvailable,
)
from .sessions import (
AgentNotFound,
AuthoredHistoryUnavailable,
AuthScopeDenied,
BifrostBinding,
BifrostConsumerKeyMissing,
BifrostHandshakeFailed,
InvalidCursor,
PersonaNotConfigured,
Tier3AgentNotFound,
Tier3FieldNotMutable,
Tier3LayerDeferred,
Tier3QuotaExceeded,
Tier3UserIdUnsupported,
)
from .sse_client import (
AgentNotAvailable,
@@ -342,3 +355,221 @@ async def cancel_turn(
except ApiError as exc:
# INV-CUT-2 default: an undiscriminated ApiError on this route → SessionApiFailed.
raise translate_error(exc) from exc
# ── slice-3: persona + authored-history adapter routes ───────────────────────
# The session-scoped affect write (set_persona_state) and the #347 authored-history
# write (write_authored_history). The SDK owns the wire shapes — the canonical
# `{"pad": {...}}` persona body via `PadState`, and the authored-write entry — so
# ratatoskr no longer hand-builds either. Error map (INV-CUT-2): persona has no row
# beyond the default; authored-history's 404 is the sole hide-existence route
# (AuthoredHistoryUnavailable), everything else the SessionApiFailed default.
async def set_persona_state(
client: WorldtreeClient,
session_id: str,
*,
pleasure: float,
arousal: float,
dominance: float,
) -> None:
"""Set a session's PAD persona state (POST /sessions/{id}/persona_state, W-7).
The adapter builds the canonical `PadState`; the SDK owns the wire wrapper
(`{"pad": {pleasure, arousal, dominance}}`, prose-pinned #317) — ratatoskr no
longer hand-assembles it. Resolves on 204 (→ None). Error map (INV-CUT-2): no
route-specific row → the `SessionApiFailed` default.
Finiteness is enforced HERE at the chokepoint (not only at the CLI): a
non-finite axis would serialize to `null` and corrupt the injection, and the SDK
raises `ConfigurationError` pre-HTTP — the precondition asserts it so any caller
gets a clean ratatoskr-side rejection, never a leaked SDK error. (The CLI surface
additionally pre-validates for a friendly usage error.)
"""
assert session_id and isinstance(session_id, str)
assert all(math.isfinite(v) for v in (pleasure, arousal, dominance))
try:
await client.sessions.set_persona_state(
session_id, PadState(pleasure=pleasure, arousal=arousal, dominance=dominance)
)
except ApiError as exc:
raise translate_error(exc) from exc
async def write_authored_history(
client: WorldtreeClient,
session_id: str,
*,
content: str,
idempotency_key: str,
) -> Mapping[str, Any]:
"""Write one authored assistant turn into the session ledger (POST
/sessions/{id}/history, #347) — the durable first-message primitive.
v1 accepts only `author="assistant"` (INV-347-4), so the adapter fixes it; the
caller supplies `content` + the per-content `idempotency_key` (REQUIRED, never
SDK-generated — a replay with the same (session, key) is an idempotent 200).
Returns the open-world `AuthoredTurn` ack verbatim. Error map (INV-CUT-2): a 404
→ `AuthoredHistoryUnavailable` (the ROUTE is the discriminator — hide-existence,
never body-sniffed: feature-absent / ungranted / session-absent are one 404 by
design, server INV-347-1); every other `ApiError` (notably 409 generation_active,
422 validation) → the `SessionApiFailed` default.
"""
assert session_id and isinstance(session_id, str)
assert content and isinstance(content, str)
assert idempotency_key and isinstance(idempotency_key, str)
try:
return await client.sessions.write_history(
session_id,
{"author": "assistant", "content": content, "idempotency_key": idempotency_key},
)
except ApiError as exc:
if exc.status == 404:
raise AuthoredHistoryUnavailable(session_id=session_id) from exc
raise translate_error(exc) from exc
# ── slice-4: agents (Tier-3) adapter routes ──────────────────────────────────
# Ratatoskr-semantic surfaces over `WorldtreeClient.agents.*` (list/persona_state/
# define/patch/delete). The SDK returns open-world dicts (parity posture — read as
# mappings, never normalized into a frozen dataclass) and surfaces the tier3/persona
# failure modes on its undiscriminated `ApiError` floor; the adapter maps them by the
# ROUTE + (status, error_code) per the § Error map (INV-CUT-2). The `model`→`role`
# cutover folds in here: the define/patch responses echo `role` (spec 1.2 / b128), so
# callers read `info["role"]` off the open-world dict — no `Tier3AgentInfo` survives.
# Consumer-agent slug (spec §2627): agent_name is `[a-z][a-z0-9-]{2,63}`.
_AGENT_SLUG_RE = re.compile(r"^[a-z][a-z0-9-]{2,63}$")
def _error_field_from_body(body: str | None) -> str | None:
"""Pull the envelope's `field` from an SDK `ApiError` body string.
The SDK's `ApiError` carries the parsed `error_code` but NOT the envelope's
`field`, so the field-bearing tier3 rejections (`layer_deferred`,
`field_not_mutable`) body-parse it here — same both-shape unwrap as
`_bifrost_error_from_body`, tolerant of `{"detail": {"field": …}}` and a flat
top-level `field`. Returns None on any parse failure (the exception still carries
a None field, exactly as the hand-rolled path did on shape mismatch).
"""
if not body:
return None
try:
err = json.loads(body)
except (json.JSONDecodeError, ValueError):
return None
if not isinstance(err, dict):
return None
field = err.get("field")
if field is None and isinstance(err.get("detail"), dict):
field = err["detail"].get("field")
return field
async def list_agents(client: WorldtreeClient) -> Sequence[Mapping[str, Any]]:
"""List the caller's agents (GET /agents) as the SDK's open-world array, verbatim
(parity: each item read as a mapping, tolerant of wire drift — no `AgentInfo`
normalization). Any error → the `SessionApiFailed` default."""
try:
return await client.agents.list()
except ApiError as exc:
raise translate_error(exc) from exc
async def get_persona_state(client: WorldtreeClient, agent_id: str) -> Mapping[str, Any]:
"""Fetch an agent's persona snapshot (GET /agents/{id}/persona_state, WT #204),
open-world dict verbatim. Error map (INV-CUT-2 — dual-key status+error_code): 404
`persona_not_configured` → `PersonaNotConfigured`; 404 `agent_not_available` →
`AgentNotAvailable` (the persona-surface variant); 403 `auth_scope_denied` →
`AuthScopeDenied`; every other error → the `SessionApiFailed` default. A 404 with
an unrecognized code stays generic — the error_code is the discriminator, never a
bare 404→hidden (this route is NOT hide-existence)."""
assert agent_id and isinstance(agent_id, str)
try:
return await client.agents.persona_state(agent_id)
except ApiError as exc:
if exc.status == 404 and exc.error_code == "persona_not_configured":
raise PersonaNotConfigured(agent_id=agent_id) from exc
if exc.status == 404 and exc.error_code == "agent_not_available":
raise PersonaAgentNotAvailable(agent_id=agent_id) from exc
if exc.status == 403 and exc.error_code == "auth_scope_denied":
raise AuthScopeDenied(scope="persona.read") from exc
raise translate_error(exc) from exc
async def define_agent(
client: WorldtreeClient, *, agent_name: str, system_prompt: str, role: str
) -> Mapping[str, Any]:
"""Define a Tier-3 consumer agent (POST /agents/define). Sends the
`AgentDefineInput` body `{agent_name, role, system_prompt}` and returns the SDK's
open-world `DefinedAgent` dict verbatim (echoes `role` post-b128 — read
`info["role"]`, no `Tier3AgentInfo`). The slug is validated client-side pre-HTTP
(server-side is the safety net). Error map (INV-CUT-2): 429 →
`Tier3QuotaExceeded(retry_after=0)` — the SDK's `ApiError` floor drops the
`Retry-After` header, and §2675 pins Phase-2.0 quota to 0; 403
`tier3_user_id_unsupported` → `Tier3UserIdUnsupported`; 422 `layer_deferred` →
`Tier3LayerDeferred(field)`; else the `SessionApiFailed` default."""
assert _AGENT_SLUG_RE.match(agent_name), (
f"agent_name must match [a-z][a-z0-9-]{{2,63}}: {agent_name!r}"
)
assert system_prompt and isinstance(system_prompt, str)
assert role and isinstance(role, str)
try:
# Inline literal so it type-checks structurally against the SDK's
# AgentDefineInput TypedDict (no import of the SDK's private `_types`).
return await client.agents.define(
{"agent_name": agent_name, "role": role, "system_prompt": system_prompt}
)
except ApiError as exc:
if exc.status == 429:
raise Tier3QuotaExceeded(retry_after=0) from exc
if exc.status == 403 and exc.error_code == "tier3_user_id_unsupported":
raise Tier3UserIdUnsupported() from exc
if exc.status == 422 and exc.error_code == "layer_deferred":
raise Tier3LayerDeferred(field=_error_field_from_body(exc.body)) from exc
raise translate_error(exc) from exc
async def patch_agent(
client: WorldtreeClient,
agent_id: str,
*,
system_prompt: str | None = None,
role: str | None = None,
) -> Mapping[str, Any]:
"""Mutate a Tier-3 agent (PATCH /agents/{id}). At least one of `system_prompt` /
`role` is required; the None-valued field is omitted from the body. Returns the
open-world `PatchedAgent` dict verbatim. Error map (INV-CUT-2): 404 →
`Tier3AgentNotFound` (agents CRUD is NOT hide-existence); 422 `field_not_mutable`
→ `Tier3FieldNotMutable(field)`; else the `SessionApiFailed` default."""
assert ":" in agent_id, f"tier 3 agent_id must contain ':': {agent_id!r}"
assert system_prompt is not None or role is not None, (
"patch requires at least one of system_prompt or role"
)
changes: dict[str, Any] = {}
if system_prompt is not None:
changes["system_prompt"] = system_prompt
if role is not None:
changes["role"] = role
try:
return await client.agents.patch(agent_id, changes)
except ApiError as exc:
if exc.status == 404:
raise Tier3AgentNotFound(agent_id=agent_id) from exc
if exc.status == 422 and exc.error_code == "field_not_mutable":
raise Tier3FieldNotMutable(field=_error_field_from_body(exc.body)) from exc
raise translate_error(exc) from exc
async def delete_agent(client: WorldtreeClient, agent_id: str) -> None:
"""Hard-delete a Tier-3 agent (DELETE /agents/{id}); resolves on 204 → None. Error
map (INV-CUT-2): 404 → `Tier3AgentNotFound` (route-discriminated; NOT
hide-existence); else the `SessionApiFailed` default."""
assert ":" in agent_id, f"tier 3 agent_id must contain ':': {agent_id!r}"
try:
await client.agents.delete(agent_id)
except ApiError as exc:
if exc.status == 404:
raise Tier3AgentNotFound(agent_id=agent_id) from exc
raise translate_error(exc) from exc
+28
View File
@@ -1950,6 +1950,20 @@ class TestTier2Probes:
)
assert rc == 10
@respx.mock
def test_set_persona_probe_connect_failed(self, capsys: pytest.CaptureFixture[str]) -> None:
"""connect_failed [error-path]: a transport failure the SDK normalizes to
ConnectFailed → graceful [network_error], exit 21 (not an uncaught crash)."""
respx.post("https://w.example/sessions/s1/persona_state").mock(
side_effect=httpx.ConnectError("refused")
)
rc = main(
["--set-persona-pad", "0.4,0.1,-0.2", "--session", "s1",
"--api-key", "k", "--server", "https://w.example"]
)
assert rc == 21
assert "[network_error]" in capsys.readouterr().err
class TestSeedFirstMessageProbe:
"""--seed-first-message one-shot (#347 authored-history-write reference-consumer probe)."""
@@ -2066,3 +2080,17 @@ class TestSeedFirstMessageProbe:
assert rc == 0
assert "feature-absent" in capsys.readouterr().out
assert msgs_route.call_count == 0 # never capability-probes past the 404
@respx.mock
def test_seed_probe_connect_failed(self, capsys: pytest.CaptureFixture[str]) -> None:
"""connect_failed [error-path]: a transport failure on create that the SDK
normalizes to ConnectFailed → graceful [network_error], exit 21."""
respx.post("https://w.example/sessions").mock(
side_effect=httpx.ConnectError("refused")
)
rc = main(
["--seed-first-message", "hello", "--agent", "mimir",
"--api-key", "k", "--server", "https://w.example"]
)
assert rc == 21
assert "[network_error]" in capsys.readouterr().err
+77 -91
View File
@@ -1,12 +1,21 @@
"""Tests for ratatoskr.first_message per docs/contracts/first_message.contract.md."""
"""Tests for ratatoskr.first_message per docs/contracts/first_message.contract.md.
Slice-3 (worldtree-sdk cutover): `seed_preset_first_message` routes through the
`ratatoskr.wt` adapter over a `WorldtreeClient`, no longer the hand-rolled httpx
wrapper. These tests drive it through a fake client whose `sessions.write_history`
returns or raises the SDK's real types — exercising the adapter's error mapping AND
first_message's best-effort swallow in one pass. The wire format itself is the SDK's
to prove (the parity corpus); first_message's contract is behavioral: never block,
never raise (except CancelledError), and exactly one write on a preset hit.
"""
import asyncio
import hashlib
import json
from typing import Any, cast
import httpx
import pytest
import respx
import worldtree_sdk as wtsdk
from worldtree_sdk import ApiError, WorldtreeClient
from ratatoskr.first_message import (
FIRST_MESSAGE_PRESETS,
@@ -15,6 +24,33 @@ from ratatoskr.first_message import (
)
class _FakeSessions:
"""Stand-in for `WorldtreeClient.sessions` — records each `write_history` call
and returns a canned ack or raises a canned error (the SDK's real exceptions)."""
def __init__(self, *, result: Any = None, error: BaseException | None = None) -> None:
self._result = result if result is not None else {}
self._error = error
self.calls: list[tuple[str, Any]] = []
async def write_history(self, session_id: str, entry: Any) -> Any:
self.calls.append((session_id, entry))
if self._error is not None:
raise self._error
return self._result
class _FakeClient:
def __init__(self, sessions: _FakeSessions) -> None:
self.sessions = sessions
def _wt(sessions: _FakeSessions) -> WorldtreeClient:
"""Cast the structural fake to the nominal client type (no network; the seed
path only touches `client.sessions.write_history`, which the fake provides)."""
return cast(WorldtreeClient, _FakeClient(sessions))
class TestPresetFor:
"""first_message contract — preset_for (dict lookup)."""
@@ -36,120 +72,70 @@ class TestPresetFor:
class TestSeedPresetFirstMessage:
"""first_message contract — seed_preset_first_message (best-effort #347 seed)."""
@respx.mock
async def test_seeds_preset(self) -> None:
"""seeds_preset [happy,tracer]: preset agent → one history POST, correct body."""
"""seeds_preset [happy,tracer]: preset agent → one write_history, correct entry."""
content = FIRST_MESSAGE_PRESETS["ratatoskr:sindra"]
key = "ratatoskr-preset-" + hashlib.sha256(content.encode("utf-8")).hexdigest()[:12]
route = respx.post("https://w.example/sessions/s1/history").mock(
return_value=httpx.Response(
201,
json={
"author": "assistant",
"seq": 0,
"phase": "seeded",
"turn_id": "t1",
"session_id": "s1",
"content_chars": len(content),
"injected_at": "2026-07-06T00:00:00+00:00",
},
)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
result = await seed_preset_first_message(client, "s1", "ratatoskr:sindra")
fake = _FakeSessions(result={"seq": 0, "phase": "seeded"})
result = await seed_preset_first_message(_wt(fake), "s1", "ratatoskr:sindra")
assert result == content
assert route.call_count == 1 # POST-002: exactly one history POST
assert json.loads(route.calls[0].request.content) == {
assert len(fake.calls) == 1 # POST-002: exactly one history write
session_id, entry = fake.calls[0]
assert session_id == "s1"
assert entry == {
"author": "assistant",
"content": content,
"idempotency_key": key,
}
@respx.mock
async def test_no_preset_zero_http(self) -> None:
"""no_preset_zero_http [happy]: no-preset agent → None, ZERO HTTP (INV-002)."""
route = respx.post("https://w.example/sessions/s1/history").mock(
return_value=httpx.Response(201, json={})
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
result = await seed_preset_first_message(client, "s1", "mimir")
async def test_no_preset_zero_write(self) -> None:
"""no_preset_zero_write [happy]: no-preset agent → None, ZERO write (INV-002)."""
fake = _FakeSessions()
result = await seed_preset_first_message(_wt(fake), "s1", "mimir")
assert result is None
assert not route.called
assert fake.calls == []
@respx.mock
async def test_feature_absent_swallowed(self) -> None:
"""feature_absent_swallowed [error]: 404 hide-existence → None, no raise (INV-001)."""
respx.post("https://w.example/sessions/s1/history").mock(
return_value=httpx.Response(404, json={"error_code": "session_not_found"})
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
result = await seed_preset_first_message(client, "s1", "ratatoskr:sindra")
"""feature_absent_swallowed [error]: 404 → AuthoredHistoryUnavailable → None (INV-001)."""
fake = _FakeSessions(error=ApiError("session_not_found", "no", status=404))
result = await seed_preset_first_message(_wt(fake), "s1", "ratatoskr:sindra")
assert result is None
assert len(fake.calls) == 1 # the write was attempted, then swallowed
@respx.mock
async def test_session_api_failed_swallowed(self) -> None:
"""session_api_failed_swallowed [error]: 409 → None, no raise (INV-001)."""
respx.post("https://w.example/sessions/s1/history").mock(
return_value=httpx.Response(409, json={"error_code": "generation_active"})
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
result = await seed_preset_first_message(client, "s1", "ratatoskr:sindra")
"""session_api_failed_swallowed [error]: 409 → SessionApiFailed → None (INV-001)."""
fake = _FakeSessions(error=ApiError("generation_active", "busy", status=409))
result = await seed_preset_first_message(_wt(fake), "s1", "ratatoskr:sindra")
assert result is None
@respx.mock
async def test_transport_error_swallowed(self) -> None:
"""transport_error_swallowed [error]: httpx.ConnectError → None, no raise (INV-001)."""
respx.post("https://w.example/sessions/s1/history").mock(
side_effect=httpx.ConnectError("boom")
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
result = await seed_preset_first_message(client, "s1", "ratatoskr:sindra")
"""transport_error_swallowed [error]: SDK ConnectFailed → None, no raise (INV-001)."""
fake = _FakeSessions(error=wtsdk.ConnectFailed("connect_failed", "boom", status=0))
result = await seed_preset_first_message(_wt(fake), "s1", "ratatoskr:sindra")
assert result is None
@respx.mock
async def test_unexpected_exception_swallowed(self) -> None:
"""unexpected_exception [error]: write raises ValueError → None (broad never-raise)."""
respx.post("https://w.example/sessions/s1/history").mock(
side_effect=ValueError("unexpected")
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
result = await seed_preset_first_message(client, "s1", "ratatoskr:sindra")
fake = _FakeSessions(error=ValueError("unexpected"))
result = await seed_preset_first_message(_wt(fake), "s1", "ratatoskr:sindra")
assert result is None
async def test_cancellation_propagates(self) -> None:
"""cancellation_propagates [error]: CancelledError from the write is RE-RAISED."""
import ratatoskr.first_message as fm
fake = _FakeSessions(error=asyncio.CancelledError())
with pytest.raises(asyncio.CancelledError):
await seed_preset_first_message(_wt(fake), "s1", "ratatoskr:sindra")
async def _cancel(*_a: object, **_k: object) -> None:
raise asyncio.CancelledError
async def test_malformed_agent_id_no_write(self) -> None:
"""malformed_agent_id [adversarial]: non-str or empty agent_id → None; no write; no raise."""
fake = _FakeSessions()
assert await seed_preset_first_message(_wt(fake), "s1", 123) is None # type: ignore[arg-type]
assert await seed_preset_first_message(_wt(fake), "s1", "") is None
assert fake.calls == []
orig = fm.write_authored_history
fm.write_authored_history = _cancel # type: ignore[assignment]
try:
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(asyncio.CancelledError):
await seed_preset_first_message(client, "s1", "ratatoskr:sindra")
finally:
fm.write_authored_history = orig # type: ignore[assignment]
@respx.mock
async def test_malformed_agent_id_no_http(self) -> None:
"""malformed_agent_id [adversarial]: non-str or empty agent_id → None; no HTTP; no raise."""
route = respx.post(url__regex=r".*/history$").mock(
return_value=httpx.Response(201, json={})
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
assert await seed_preset_first_message(client, "s1", 123) is None # type: ignore[arg-type]
assert await seed_preset_first_message(client, "s1", "") is None
assert not route.called
@respx.mock
async def test_empty_session_id(self) -> None:
"""empty_session_id [adversarial]: "" → None (soft guard); no HTTP; no raise."""
route = respx.post("https://w.example/sessions/s1/history").mock(
return_value=httpx.Response(201, json={})
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
result = await seed_preset_first_message(client, "", "ratatoskr:sindra")
"""empty_session_id [adversarial]: "" → None (soft guard); no write; no raise."""
fake = _FakeSessions()
result = await seed_preset_first_message(_wt(fake), "", "ratatoskr:sindra")
assert result is None
assert not route.called
assert fake.calls == []
+10 -10
View File
@@ -33,14 +33,14 @@ def local_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
def _entry(
agent_id: str = "ratatoskr:wizard",
agent_name: str = "wizard",
model: str = "qwen3.6-35-a3b",
role: str = "qwen3.6-35-a3b",
description: str = "(tier 3) test agent",
defined_at: str = "2026-05-25T00:00:00+00:00",
) -> LocalAgentEntry:
return LocalAgentEntry(
agent_id=agent_id,
agent_name=agent_name,
model=model,
role=role,
description=description,
defined_at=defined_at,
)
@@ -91,13 +91,13 @@ class TestLoadEmpty:
local_path.write_text(
json.dumps(
{
"version": 1,
"version": 2,
"agents": [
{"agent_id": "incomplete"}, # missing required fields
{
"agent_id": "ratatoskr:good",
"agent_name": "good",
"model": "m",
"role": "m",
"description": "d",
"defined_at": "t",
},
@@ -124,11 +124,11 @@ class TestAdd:
assert ids == {"ratatoskr:a", "ratatoskr:b"}
def test_add_replaces_same_id(self, local_path: Path) -> None:
add_local_agent(_entry(model="old-model"))
add_local_agent(_entry(model="new-model"))
add_local_agent(_entry(role="old-role"))
add_local_agent(_entry(role="new-role"))
entries = load_local_agents()
assert len(entries) == 1
assert entries[0].model == "new-model"
assert entries[0].role == "new-role"
def test_creates_parent_dirs(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
@@ -141,11 +141,11 @@ class TestAdd:
class TestUpdate:
def test_update_changes_existing(self, local_path: Path) -> None:
add_local_agent(_entry(model="v1"))
update_local_agent(_entry(model="v2"))
add_local_agent(_entry(role="v1"))
update_local_agent(_entry(role="v2"))
entries = load_local_agents()
assert len(entries) == 1
assert entries[0].model == "v2"
assert entries[0].role == "v2"
class TestRemove:
+4 -1009
View File
File diff suppressed because it is too large Load Diff
+65 -319
View File
@@ -1,4 +1,14 @@
"""Tests for ratatoskr.tier3 per docs/contracts/issues/15.contract.md."""
"""CLI integration tests for `python -m ratatoskr.tier3`.
The define/patch/delete wire calls route through the worldtree-sdk adapter
(`ratatoskr.wt`); the adapter's body-building + error-mapping are unit-tested in
`test_wt.py` (against a fake `client.agents`). These tests exercise the CLI
end-to-end — argv → the real SDK over a respx-mocked HTTP layer → exit code +
stdout + the local tier3 index side effects.
The define/patch response echoes `role` (Worldtree spec 1.2 / b128), read off the
SDK's open-world dict; `LocalAgentEntry.role` is the v2-schema field.
"""
from pathlib import Path
@@ -6,317 +16,20 @@ import httpx
import pytest
import respx
from ratatoskr.sessions import SessionApiFailed
from ratatoskr.tier3 import (
Tier3AgentInfo,
Tier3AgentNotFound,
Tier3FieldNotMutable,
Tier3LayerDeferred,
Tier3QuotaExceeded,
Tier3UserIdUnsupported,
define_agent,
delete_agent,
main,
patch_agent,
)
from ratatoskr.tier3 import main
# The consumer-agent response echoes `role` (b128), not the former `model`.
_FULL_AGENT_RESP = {
"agent_id": "ratatoskr:wizard",
"user_id": "ratatoskr",
"agent_name": "wizard",
"system_prompt": "You are a wizard.",
"model": "qwen3.6-35-a3b",
"role": "qwen3.6-35-a3b",
"created_at": "2026-05-25T03:20:09.703601+00:00",
"updated_at": "2026-05-25T03:20:09.703601+00:00",
}
class TestDefineAgent:
@respx.mock
async def test_happy_define(self) -> None:
"""happy_define [happy,tracer]: 201 → fully populated Tier3AgentInfo."""
respx.post("https://w.example/agents/define").mock(
return_value=httpx.Response(201, json=_FULL_AGENT_RESP)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
info = await define_agent(
client,
agent_name="wizard",
system_prompt="You are a wizard.",
role="qwen3.6-35-a3b",
)
assert isinstance(info, Tier3AgentInfo)
assert info.agent_id == "ratatoskr:wizard"
assert info.user_id == "ratatoskr"
assert info.agent_name == "wizard"
assert info.model == "qwen3.6-35-a3b"
@respx.mock
async def test_request_body_shape(self) -> None:
"""request_body_shape [trace]: outbound JSON is exactly the three keys."""
import json as _json
route = respx.post("https://w.example/agents/define").mock(
return_value=httpx.Response(201, json=_FULL_AGENT_RESP)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
await define_agent(
client,
agent_name="wizard",
system_prompt="You are a wizard.",
role="qwen3.6-35-a3b",
)
body = _json.loads(route.calls[0].request.content)
# INV-001: exactly these three keys — no layer fields, no metadata.
assert body == {
"agent_name": "wizard",
"system_prompt": "You are a wizard.",
"role": "qwen3.6-35-a3b",
}
@respx.mock
async def test_quota_exceeded(self) -> None:
"""quota_exceeded [error]: 429 + Retry-After → Tier3QuotaExceeded."""
respx.post("https://w.example/agents/define").mock(
return_value=httpx.Response(
429,
headers={"Retry-After": "0"},
json={"detail": {"error_code": "agent_quota_exceeded"}},
)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(Tier3QuotaExceeded) as exc:
await define_agent(
client,
agent_name="overflow",
system_prompt="x",
role="m",
)
assert exc.value.retry_after == 0
@respx.mock
async def test_user_id_unsupported(self) -> None:
"""user_id_unsupported [error]: 403 + error_code → Tier3UserIdUnsupported."""
respx.post("https://w.example/agents/define").mock(
return_value=httpx.Response(
403, json={"detail": {"error_code": "tier3_user_id_unsupported"}}
)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(Tier3UserIdUnsupported):
await define_agent(
client, agent_name="wizard", system_prompt="x", role="m"
)
@respx.mock
async def test_layer_deferred(self) -> None:
"""layer_deferred [error]: 422 + layer_deferred → Tier3LayerDeferred(field)."""
respx.post("https://w.example/agents/define").mock(
return_value=httpx.Response(
422,
json={"detail": {"error_code": "layer_deferred", "field": "persona"}},
)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(Tier3LayerDeferred) as exc:
await define_agent(
client, agent_name="wizard", system_prompt="x", role="m"
)
assert exc.value.field == "persona"
@respx.mock
async def test_bad_slug_assert(self) -> None:
"""bad_slug_assert [adversarial]: agent_name with uppercase → AssertionError, no HTTP."""
route = respx.post("https://w.example/agents/define").mock(
return_value=httpx.Response(201, json=_FULL_AGENT_RESP)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(AssertionError):
await define_agent(
client, agent_name="Wizard", system_prompt="x", role="m"
)
assert route.call_count == 0
@respx.mock
async def test_short_slug_assert(self) -> None:
"""short_slug_assert [adversarial]: agent_name len < 3 → AssertionError."""
route = respx.post("https://w.example/agents/define").mock(
return_value=httpx.Response(201, json=_FULL_AGENT_RESP)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(AssertionError):
await define_agent(
client, agent_name="ab", system_prompt="x", role="m"
)
assert route.call_count == 0
@respx.mock
async def test_empty_prompt_assert(self) -> None:
"""empty_prompt_assert [adversarial]: empty system_prompt → AssertionError."""
route = respx.post("https://w.example/agents/define").mock(
return_value=httpx.Response(201, json=_FULL_AGENT_RESP)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(AssertionError):
await define_agent(
client, agent_name="wizard", system_prompt="", role="m"
)
assert route.call_count == 0
@respx.mock
async def test_other_5xx(self) -> None:
"""other_5xx [error]: 503 → SessionApiFailed(status=503)."""
respx.post("https://w.example/agents/define").mock(
return_value=httpx.Response(503, content=b"upstream out")
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(SessionApiFailed) as exc:
await define_agent(
client, agent_name="wizard", system_prompt="x", role="m"
)
assert exc.value.status == 503
class TestPatchAgent:
@respx.mock
async def test_happy_patch_both_fields(self) -> None:
"""happy_patch_both_fields: both fields set → request body has both."""
import json as _json
updated = {
**_FULL_AGENT_RESP,
"system_prompt": "new prompt",
"model": "different-model",
}
route = respx.patch("https://w.example/agents/ratatoskr:wizard").mock(
return_value=httpx.Response(200, json=updated)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
info = await patch_agent(
client,
"ratatoskr:wizard",
system_prompt="new prompt",
role="different-model",
)
body = _json.loads(route.calls[0].request.content)
assert body == {"system_prompt": "new prompt", "role": "different-model"}
assert info.system_prompt == "new prompt"
assert info.model == "different-model"
@respx.mock
async def test_happy_patch_single_field(self) -> None:
"""happy_patch_single_field: omit role → body has system_prompt only."""
import json as _json
updated = {**_FULL_AGENT_RESP, "system_prompt": "only this"}
route = respx.patch("https://w.example/agents/ratatoskr:wizard").mock(
return_value=httpx.Response(200, json=updated)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
await patch_agent(client, "ratatoskr:wizard", system_prompt="only this")
body = _json.loads(route.calls[0].request.content)
# INV-002: body omits the None-valued field entirely
assert body == {"system_prompt": "only this"}
@respx.mock
async def test_field_not_mutable(self) -> None:
"""field_not_mutable [error]: 422 + error_code → Tier3FieldNotMutable(field)."""
respx.patch("https://w.example/agents/ratatoskr:wizard").mock(
return_value=httpx.Response(
422,
json={
"detail": {"error_code": "field_not_mutable", "field": "agent_name"}
},
)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(Tier3FieldNotMutable) as exc:
await patch_agent(
client, "ratatoskr:wizard", system_prompt="x"
)
assert exc.value.field == "agent_name"
@respx.mock
async def test_404(self) -> None:
"""404 [error]: PATCH on non-existent agent → Tier3AgentNotFound."""
respx.patch("https://w.example/agents/ratatoskr:ghost").mock(
return_value=httpx.Response(404, content=b"")
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(Tier3AgentNotFound) as exc:
await patch_agent(
client, "ratatoskr:ghost", system_prompt="x"
)
assert exc.value.agent_id == "ratatoskr:ghost"
@respx.mock
async def test_no_fields_assert(self) -> None:
"""no_fields_assert [adversarial]: both None → AssertionError, no HTTP."""
route = respx.patch("https://w.example/agents/ratatoskr:wizard").mock(
return_value=httpx.Response(200, json=_FULL_AGENT_RESP)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(AssertionError):
await patch_agent(client, "ratatoskr:wizard")
assert route.call_count == 0
@respx.mock
async def test_non_tier3_id_assert(self) -> None:
"""non_tier3_id_assert [adversarial]: agent_id without `:` → AssertionError."""
route = respx.patch("https://w.example/agents/mimir").mock(
return_value=httpx.Response(200, json=_FULL_AGENT_RESP)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(AssertionError):
await patch_agent(client, "mimir", system_prompt="x")
assert route.call_count == 0
class TestDeleteAgent:
@respx.mock
async def test_happy_delete(self) -> None:
"""happy_delete [happy,tracer]: 204 → returns None."""
respx.delete("https://w.example/agents/ratatoskr:wizard").mock(
return_value=httpx.Response(204)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
result = await delete_agent(client, "ratatoskr:wizard")
assert result is None
@respx.mock
async def test_404(self) -> None:
"""404 [error]: DELETE on non-existent agent → Tier3AgentNotFound."""
respx.delete("https://w.example/agents/ratatoskr:ghost").mock(
return_value=httpx.Response(404)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(Tier3AgentNotFound) as exc:
await delete_agent(client, "ratatoskr:ghost")
assert exc.value.agent_id == "ratatoskr:ghost"
@respx.mock
async def test_non_tier3_id_assert(self) -> None:
"""non_tier3_id_assert [adversarial]: agent_id without `:` → AssertionError."""
route = respx.delete("https://w.example/agents/mimir").mock(
return_value=httpx.Response(204)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(AssertionError):
await delete_agent(client, "mimir")
assert route.call_count == 0
@respx.mock
async def test_other_5xx(self) -> None:
"""other_5xx [error]: 500 → SessionApiFailed."""
respx.delete("https://w.example/agents/ratatoskr:wizard").mock(
return_value=httpx.Response(500, content=b"oops")
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(SessionApiFailed) as exc:
await delete_agent(client, "ratatoskr:wizard")
assert exc.value.status == 500
@pytest.fixture
def _isolated_local_agents(
tmp_path: "Path", monkeypatch: pytest.MonkeyPatch
@@ -335,8 +48,8 @@ class TestCli:
monkeypatch: pytest.MonkeyPatch,
_isolated_local_agents: "Path",
) -> None:
"""cli_define_happy [happy]: argv → 201 mock → stdout confirmation;
local index updated with the new entry (v0.8.0 hook).
"""cli_define_happy [happy,tracer]: argv → 201 mock → stdout confirmation;
local index updated with the new entry (role echoed).
"""
from ratatoskr.local_agents import load_local_agents
@@ -354,11 +67,34 @@ class TestCli:
out = capsys.readouterr()
assert rc == 0
assert out.out.strip() == "defined ratatoskr:wizard (qwen3.6-35-a3b)"
# v0.8.0: local index now has the new entry.
entries = load_local_agents()
assert len(entries) == 1
assert entries[0].agent_id == "ratatoskr:wizard"
assert entries[0].model == "qwen3.6-35-a3b"
assert entries[0].role == "qwen3.6-35-a3b"
@respx.mock
def test_cli_define_body_shape(
self, monkeypatch: pytest.MonkeyPatch, _isolated_local_agents: "Path"
) -> None:
"""cli_define_body_shape [trace]: outbound JSON is exactly the three keys
(the adapter sends AgentDefineInput, no layer fields)."""
import json as _json
monkeypatch.setenv("WORLDTREE_API_URL", "https://w.example")
monkeypatch.setenv("WORLDTREE_API_KEY", "k")
route = respx.post("https://w.example/agents/define").mock(
return_value=httpx.Response(201, json=_FULL_AGENT_RESP)
)
main([
"define", "--name", "wizard",
"--system-prompt", "You are a wizard.", "--role", "qwen3.6-35-a3b",
])
body = _json.loads(route.calls[0].request.content)
assert body == {
"agent_name": "wizard",
"role": "qwen3.6-35-a3b",
"system_prompt": "You are a wizard.",
}
@respx.mock
def test_cli_patch_happy(
@@ -384,6 +120,7 @@ class TestCli:
entries = load_local_agents()
assert len(entries) == 1
assert entries[0].agent_id == "ratatoskr:wizard"
assert entries[0].role == "qwen3.6-35-a3b"
@respx.mock
def test_cli_delete_happy(
@@ -401,11 +138,11 @@ class TestCli:
load_local_agents,
)
# Pre-populate so we can verify removal.
# Pre-populate so we can verify removal (v2 schema: role, not model).
add_local_agent(LocalAgentEntry(
agent_id="ratatoskr:wizard",
agent_name="wizard",
model="m",
role="m",
description="d",
defined_at="t",
))
@@ -426,10 +163,7 @@ class TestCli:
"""cli_missing_auth [error]: no api-key → stderr [auth_error] + exit 11."""
monkeypatch.delenv("WORLDTREE_API_KEY", raising=False)
rc = main([
"define",
"--name", "wizard",
"--system-prompt", "x",
"--role", "m",
"define", "--name", "wizard", "--system-prompt", "x", "--role", "m",
])
err = capsys.readouterr().err
assert rc == 11
@@ -446,10 +180,7 @@ class TestCli:
return_value=httpx.Response(500, content=b"upstream out")
)
rc = main([
"define",
"--name", "wizard",
"--system-prompt", "x",
"--role", "m",
"define", "--name", "wizard", "--system-prompt", "x", "--role", "m",
])
err = capsys.readouterr().err
assert rc == 20
@@ -470,15 +201,30 @@ class TestCli:
)
)
rc = main([
"define",
"--name", "wizard",
"--system-prompt", "x",
"--role", "m",
"define", "--name", "wizard", "--system-prompt", "x", "--role", "m",
])
err = capsys.readouterr().err
assert rc == 20
assert "[quota_exceeded]" in err
@respx.mock
def test_cli_network_error(
self, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
) -> None:
"""cli_network_error [error]: a transport failure surfaces as the SDK's
ConnectFailed (not a raw httpx error) → stderr [network_error] + exit 21."""
monkeypatch.setenv("WORLDTREE_API_URL", "https://w.example")
monkeypatch.setenv("WORLDTREE_API_KEY", "k")
respx.post("https://w.example/agents/define").mock(
side_effect=httpx.ConnectError("refused")
)
rc = main([
"define", "--name", "wizard", "--system-prompt", "x", "--role", "m",
])
err = capsys.readouterr().err
assert rc == 21
assert "[network_error]" in err
def test_cli_patch_no_fields(
self, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
) -> None:
+2 -2
View File
@@ -66,7 +66,7 @@ class TestAgentsEndpoint:
LocalAgentEntry(
agent_id="ratatoskr:sindra",
agent_name="sindra",
model="artemis-31b-v1i",
role="artemis-31b-v1i",
description="(tier 3) IDENTITY",
defined_at="2026-05-28T00:00:00+00:00",
)
@@ -118,7 +118,7 @@ class TestAgentsEndpoint:
from ratatoskr.local_agents import LocalAgentEntry, add_local_agent
add_local_agent(
LocalAgentEntry(
agent_id="ratatoskr:sindra", agent_name="sindra", model="m",
agent_id="ratatoskr:sindra", agent_name="sindra", role="m",
description="local-tier3", defined_at="2026-05-28T00:00:00+00:00",
)
)
+367 -1
View File
@@ -17,14 +17,25 @@ from typing import Any, cast
import httpx
import pytest
import worldtree_sdk as wtsdk
from worldtree_sdk import ApiError, CancelResult, WorldtreeClient
from worldtree_sdk import ApiError, CancelResult, PadState, WorldtreeClient
from ratatoskr.sessions import (
AgentNotAvailable as PersonaAgentNotAvailable,
)
from ratatoskr.sessions import (
AgentNotFound,
AuthoredHistoryUnavailable,
AuthScopeDenied,
BifrostBinding,
BifrostConsumerKeyMissing,
BifrostHandshakeFailed,
InvalidCursor,
PersonaNotConfigured,
Tier3AgentNotFound,
Tier3FieldNotMutable,
Tier3LayerDeferred,
Tier3QuotaExceeded,
Tier3UserIdUnsupported,
)
from ratatoskr.sse_client import (
AgentNotAvailable,
@@ -43,11 +54,18 @@ from ratatoskr.wt import (
build_client,
cancel_turn,
create_session,
define_agent,
delete_agent,
get_persona_state,
get_session_messages,
get_session_tools,
list_agents,
list_sessions,
patch_agent,
set_persona_state,
stream_turn,
translate_error,
write_authored_history,
)
@@ -101,6 +119,12 @@ class _FakeSessions:
async def cancel_turn(self, *args: Any, **kwargs: Any) -> Any:
return await self._dispatch("cancel_turn", *args, **kwargs)
async def set_persona_state(self, *args: Any, **kwargs: Any) -> Any:
return await self._dispatch("set_persona_state", *args, **kwargs)
async def write_history(self, *args: Any, **kwargs: Any) -> Any:
return await self._dispatch("write_history", *args, **kwargs)
class _FakeClient:
def __init__(self, sessions: _FakeSessions) -> None:
@@ -440,3 +464,345 @@ class TestCancelTurn:
with pytest.raises(SessionApiFailed) as ei:
await cancel_turn(_wt(fake), "s", 42)
assert ei.value.status == 500
class TestSetPersonaState:
"""slice-3: set_persona_state → SDK sessions.set_persona_state(PadState). The
adapter builds the canonical PadState (the SDK owns the {"pad": {...}} wire
shape); no error row beyond the § Error map default (SessionApiFailed)."""
async def test_happy_builds_padstate_and_returns_none(self) -> None:
fake = _FakeSessions(result=None) # SDK resolves the 204 to None
out = await set_persona_state(
_wt(fake), "s-1", pleasure=0.4, arousal=0.1, dominance=-0.2
)
assert out is None
name, args, _kwargs = fake.calls[-1]
assert name == "set_persona_state"
assert args[0] == "s-1"
pad = args[1]
assert isinstance(pad, PadState)
assert (pad.pleasure, pad.arousal, pad.dominance) == (0.4, 0.1, -0.2)
async def test_falsy_zero_pad_preserved(self) -> None:
# A 0.0 axis must survive verbatim (not be dropped as falsy).
fake = _FakeSessions(result=None)
await set_persona_state(_wt(fake), "s", pleasure=0.0, arousal=0.0, dominance=0.0)
pad = fake.calls[-1][1][1]
assert (pad.pleasure, pad.arousal, pad.dominance) == (0.0, 0.0, 0.0)
async def test_error_maps_to_session_api_failed(self) -> None:
fake = _FakeSessions(error=ApiError("upstream", "boom", status=500, body="x"))
with pytest.raises(SessionApiFailed) as ei:
await set_persona_state(_wt(fake), "s", pleasure=0.0, arousal=0.0, dominance=0.0)
assert ei.value.status == 500
async def test_non_finite_pad_rejected_at_the_chokepoint(self) -> None:
# The finite-PAD invariant is enforced at the adapter (not only the CLI): a
# non-finite axis would serialize to null and corrupt the injection, so a
# direct caller is rejected pre-SDK — never a leaked SDK ConfigurationError.
fake = _FakeSessions(result=None)
for bad in (float("nan"), float("inf"), float("-inf")):
with pytest.raises(AssertionError):
await set_persona_state(_wt(fake), "s", pleasure=bad, arousal=0.0, dominance=0.0)
assert fake.calls == [] # never reached the SDK
class TestWriteAuthoredHistory:
"""slice-3: write_authored_history → SDK sessions.write_history. Builds the
v1 authored-write entry (author="assistant", the only accepted author);
404 AuthoredHistoryUnavailable (hide-existence); else the default."""
async def test_happy_builds_entry_and_returns_dict(self) -> None:
ack = {"seq": 0, "phase": "seeded", "turn_id": "t1", "content_chars": 3}
fake = _FakeSessions(result=ack)
out = await write_authored_history(
_wt(fake), "s-1", content="hi!", idempotency_key="k1"
)
assert out is ack # open-world passthrough
name, args, _kwargs = fake.calls[-1]
assert name == "write_history"
assert args[0] == "s-1"
assert args[1] == {
"author": "assistant",
"content": "hi!",
"idempotency_key": "k1",
}
async def test_404_maps_to_authored_history_unavailable(self) -> None:
# Hide-existence: the ROUTE is the discriminator (never the body) — any 404
# on write_history → AuthoredHistoryUnavailable, no capability-probe.
fake = _FakeSessions(error=ApiError("session_not_found", "no", status=404))
with pytest.raises(AuthoredHistoryUnavailable) as ei:
await write_authored_history(_wt(fake), "s-1", content="hi", idempotency_key="k")
assert ei.value.session_id == "s-1"
async def test_other_error_maps_to_session_api_failed(self) -> None:
# 409 generation_active (retryable) is NOT a hide-existence 404 → default.
fake = _FakeSessions(error=ApiError("generation_active", "busy", status=409))
with pytest.raises(SessionApiFailed) as ei:
await write_authored_history(_wt(fake), "s", content="hi", idempotency_key="k")
assert ei.value.status == 409
# ── slice-4: agents (Tier-3) adapter routes ──────────────────────────────────
class _FakeAgents:
"""Stand-in for `WorldtreeClient.agents` — records the last call and returns a
canned result or raises a canned error. Same shape as `_FakeSessions`."""
def __init__(self, *, result: Any = None, error: BaseException | None = None) -> None:
self._result = result
self._error = error
self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = []
async def _dispatch(self, name: str, *args: Any, **kwargs: Any) -> Any:
self.calls.append((name, args, kwargs))
if self._error is not None:
raise self._error
return self._result
async def list(self, *args: Any, **kwargs: Any) -> Any:
return await self._dispatch("list", *args, **kwargs)
async def persona_state(self, *args: Any, **kwargs: Any) -> Any:
return await self._dispatch("persona_state", *args, **kwargs)
async def define(self, *args: Any, **kwargs: Any) -> Any:
return await self._dispatch("define", *args, **kwargs)
async def patch(self, *args: Any, **kwargs: Any) -> Any:
return await self._dispatch("patch", *args, **kwargs)
async def delete(self, *args: Any, **kwargs: Any) -> Any:
return await self._dispatch("delete", *args, **kwargs)
class _FakeAgentsClient:
def __init__(self, agents: _FakeAgents) -> None:
self.agents = agents
def _wta(agents: _FakeAgents) -> WorldtreeClient:
"""Cast the structural agents-fake to the nominal client type (the agent route
functions only touch `client.agents.*`)."""
return cast(WorldtreeClient, _FakeAgentsClient(agents))
class TestListAgents:
"""slice-4: list_agents → SDK agents.list(); open-world array verbatim."""
async def test_happy_returns_array_verbatim(self) -> None:
data = [{"agent_id": "mimir", "name": "Mimir", "description": "k"}]
fake = _FakeAgents(result=data)
out = await list_agents(_wta(fake))
assert out is data # open-world passthrough, no AgentInfo normalization
assert fake.calls[-1][0] == "list"
async def test_error_maps_to_session_api_failed(self) -> None:
fake = _FakeAgents(error=ApiError("upstream", "boom", status=500))
with pytest.raises(SessionApiFailed) as ei:
await list_agents(_wta(fake))
assert ei.value.status == 500
class TestGetPersonaState:
"""slice-4: get_persona_state → SDK agents.persona_state(id); dict verbatim.
404 sub-codes + 403 auth_scope_denied map by (status, error_code)."""
async def test_happy_returns_dict_verbatim(self) -> None:
snap = {"pad": {}, "dominant_emotion": "curiosity"}
fake = _FakeAgents(result=snap)
out = await get_persona_state(_wta(fake), "mimir")
assert out is snap
assert fake.calls[-1] == ("persona_state", ("mimir",), {})
async def test_persona_not_configured(self) -> None:
fake = _FakeAgents(error=ApiError("persona_not_configured", "no", status=404))
with pytest.raises(PersonaNotConfigured) as ei:
await get_persona_state(_wta(fake), "domari")
assert ei.value.agent_id == "domari"
async def test_agent_not_available(self) -> None:
fake = _FakeAgents(error=ApiError("agent_not_available", "no", status=404))
with pytest.raises(PersonaAgentNotAvailable) as ei:
await get_persona_state(_wta(fake), "bogus")
assert ei.value.agent_id == "bogus"
async def test_auth_scope_denied(self) -> None:
fake = _FakeAgents(error=ApiError("auth_scope_denied", "no", status=403))
with pytest.raises(AuthScopeDenied) as ei:
await get_persona_state(_wta(fake), "mimir")
assert ei.value.scope == "persona.read"
async def test_other_404_without_code_maps_to_default(self) -> None:
# A 404 whose error_code is neither persona sub-code → generic default,
# NOT a spurious PersonaNotConfigured (the code is the discriminator).
fake = _FakeAgents(error=ApiError("weird", "no", status=404))
with pytest.raises(SessionApiFailed) as ei:
await get_persona_state(_wta(fake), "mimir")
assert ei.value.status == 404
async def test_empty_agent_id_asserts(self) -> None:
fake = _FakeAgents(result={})
with pytest.raises(AssertionError):
await get_persona_state(_wta(fake), "")
assert fake.calls == []
class TestDefineAgent:
"""slice-4: define_agent → SDK agents.define(); open-world DefinedAgent dict
(echoes `role` post-b128). Slug validated client-side; tier3 error rows."""
async def test_happy_builds_body_and_returns_dict(self) -> None:
resp = {"agent_id": "ratatoskr:wizard", "role": "thoughtful-character"}
fake = _FakeAgents(result=resp)
out = await define_agent(
_wta(fake), agent_name="wizard", system_prompt="You are a wizard.",
role="thoughtful-character",
)
assert out is resp # open-world passthrough (no Tier3AgentInfo)
name, args, _kwargs = fake.calls[-1]
assert name == "define"
# AgentDefineInput body: exactly the three keys, no layer fields.
assert args[0] == {
"agent_name": "wizard",
"role": "thoughtful-character",
"system_prompt": "You are a wizard.",
}
async def test_quota_exceeded_defaults_retry_after_zero(self) -> None:
# The SDK's ApiError floor drops the Retry-After header; spec §2675 pins it
# to 0, so the adapter defaults retry_after=0.
fake = _FakeAgents(error=ApiError("agent_quota_exceeded", "full", status=429))
with pytest.raises(Tier3QuotaExceeded) as ei:
await define_agent(_wta(fake), agent_name="overflow", system_prompt="x", role="m")
assert ei.value.retry_after == 0
async def test_user_id_unsupported(self) -> None:
fake = _FakeAgents(error=ApiError("tier3_user_id_unsupported", "no", status=403))
with pytest.raises(Tier3UserIdUnsupported):
await define_agent(_wta(fake), agent_name="wizard", system_prompt="x", role="m")
async def test_layer_deferred_field_parsed_from_body(self) -> None:
# `field` is not on ApiError — the adapter body-parses detail.field.
fake = _FakeAgents(error=ApiError(
"layer_deferred", "no", status=422,
body='{"detail": {"error_code": "layer_deferred", "field": "persona"}}',
))
with pytest.raises(Tier3LayerDeferred) as ei:
await define_agent(_wta(fake), agent_name="wizard", system_prompt="x", role="m")
assert ei.value.field == "persona"
async def test_bad_slug_asserts_no_call(self) -> None:
fake = _FakeAgents(result={})
with pytest.raises(AssertionError):
await define_agent(_wta(fake), agent_name="Wizard", system_prompt="x", role="m")
assert fake.calls == []
async def test_short_slug_asserts_no_call(self) -> None:
fake = _FakeAgents(result={})
with pytest.raises(AssertionError):
await define_agent(_wta(fake), agent_name="ab", system_prompt="x", role="m")
assert fake.calls == []
async def test_empty_prompt_asserts(self) -> None:
fake = _FakeAgents(result={})
with pytest.raises(AssertionError):
await define_agent(_wta(fake), agent_name="wizard", system_prompt="", role="m")
assert fake.calls == []
async def test_empty_role_asserts(self) -> None:
fake = _FakeAgents(result={})
with pytest.raises(AssertionError):
await define_agent(_wta(fake), agent_name="wizard", system_prompt="x", role="")
assert fake.calls == []
async def test_other_5xx_maps_to_default(self) -> None:
fake = _FakeAgents(error=ApiError("upstream", "out", status=503))
with pytest.raises(SessionApiFailed) as ei:
await define_agent(_wta(fake), agent_name="wizard", system_prompt="x", role="m")
assert ei.value.status == 503
class TestPatchAgent:
"""slice-4: patch_agent → SDK agents.patch(id, changes); open PatchedAgent dict."""
async def test_happy_both_fields(self) -> None:
resp = {"agent_id": "ratatoskr:wizard", "role": "different"}
fake = _FakeAgents(result=resp)
out = await patch_agent(
_wta(fake), "ratatoskr:wizard", system_prompt="new", role="different"
)
assert out is resp
name, args, _kwargs = fake.calls[-1]
assert name == "patch"
assert args[0] == "ratatoskr:wizard"
assert args[1] == {"system_prompt": "new", "role": "different"}
async def test_happy_single_field_omits_none(self) -> None:
fake = _FakeAgents(result={})
await patch_agent(_wta(fake), "ratatoskr:wizard", system_prompt="only this")
assert fake.calls[-1][1][1] == {"system_prompt": "only this"}
async def test_404_maps_to_agent_not_found(self) -> None:
fake = _FakeAgents(error=ApiError("not_found", "no", status=404))
with pytest.raises(Tier3AgentNotFound) as ei:
await patch_agent(_wta(fake), "ratatoskr:ghost", system_prompt="x")
assert ei.value.agent_id == "ratatoskr:ghost"
async def test_field_not_mutable_field_parsed(self) -> None:
fake = _FakeAgents(error=ApiError(
"field_not_mutable", "no", status=422,
body='{"detail": {"error_code": "field_not_mutable", "field": "agent_name"}}',
))
with pytest.raises(Tier3FieldNotMutable) as ei:
await patch_agent(_wta(fake), "ratatoskr:wizard", system_prompt="x")
assert ei.value.field == "agent_name"
async def test_no_fields_asserts_no_call(self) -> None:
fake = _FakeAgents(result={})
with pytest.raises(AssertionError):
await patch_agent(_wta(fake), "ratatoskr:wizard")
assert fake.calls == []
async def test_non_tier3_id_asserts(self) -> None:
fake = _FakeAgents(result={})
with pytest.raises(AssertionError):
await patch_agent(_wta(fake), "mimir", system_prompt="x")
assert fake.calls == []
async def test_other_error_maps_to_default(self) -> None:
fake = _FakeAgents(error=ApiError("upstream", "boom", status=500))
with pytest.raises(SessionApiFailed) as ei:
await patch_agent(_wta(fake), "ratatoskr:wizard", system_prompt="x")
assert ei.value.status == 500
class TestDeleteAgent:
"""slice-4: delete_agent → SDK agents.delete(id); None on 204; 404 → not-found."""
async def test_happy_returns_none(self) -> None:
fake = _FakeAgents(result=None)
out = await delete_agent(_wta(fake), "ratatoskr:wizard")
assert out is None
assert fake.calls[-1] == ("delete", ("ratatoskr:wizard",), {})
async def test_404_maps_to_agent_not_found(self) -> None:
fake = _FakeAgents(error=ApiError("not_found", "no", status=404))
with pytest.raises(Tier3AgentNotFound) as ei:
await delete_agent(_wta(fake), "ratatoskr:ghost")
assert ei.value.agent_id == "ratatoskr:ghost"
async def test_non_tier3_id_asserts(self) -> None:
fake = _FakeAgents(result=None)
with pytest.raises(AssertionError):
await delete_agent(_wta(fake), "mimir")
assert fake.calls == []
async def test_other_error_maps_to_default(self) -> None:
fake = _FakeAgents(error=ApiError("upstream", "oops", status=500))
with pytest.raises(SessionApiFailed) as ei:
await delete_agent(_wta(fake), "ratatoskr:wizard")
assert ei.value.status == 500
Generated
+1 -1
View File
@@ -472,7 +472,7 @@ wheels = [
[[package]]
name = "ratatoskr"
version = "0.21.10"
version = "0.21.13"
source = { editable = "." }
dependencies = [
{ name = "httpx" },