返回 CodeWhale
RUNTIME_API.md
根目录 / docs / RUNTIME_API.md
1 # Codewhale Engine Runtime API & Integration Contract
2
3 > 阅读简体中文版:[zh_hans/RUNTIME_API.md](zh_hans/RUNTIME_API.md)。
4
5 `codewhale app-server --http` exposes the [Codewhale Engine](ARCHITECTURE.md) through
6 its canonical local Runtime API and control plane.
7 Local SDKs, mobile/remote-control clients, and editor integrations talk to it
8 instead of screen-scraping terminal output. It serves the full HTTP/SSE runtime
9 API (`/v1/*`), a JSON-RPC control transport over stdio, and the phone-friendly
10 mobile page. `codewhale doctor --json` provides machine-readable health, and
11 `codewhale serve --acp` speaks the Agent Client Protocol over stdio for editors
12 such as Zed.
13
14 `codewhale serve --http` / `serve --mobile` remain as **compatibility aliases**
15 for `codewhale app-server --http` / `--mobile`; both launch the identical
16 server. Desktop, web, SDK and custom integrations should target
17 `app-server --http`. `--stdio` and `--socket` expose compatibility controls.
18 Bare `app-server` selects initialized JSONL control over stdio. Local stdio,
19 socket and ACP owners do not bind a hidden TCP listener. Explicit `--http`
20 retains HTTP/SSE and compatibility routes on the same Runtime owner.
21
22 `codewhale exec` is the separate one-shot headless worker path (stream-json,
23 fleet worker subprocess, CI primitive). It is not part of this API, but it
24 shares the same runtime, provider/model resolution, permission profiles, and
25 event vocabulary.
26
27 This document is the stable integration contract for native workbench
28 applications (and other local supervisors) that embed the Codewhale Engine.
29
30 ## Architecture
31
32 ```
33 local supervisor / SDK / automation harness
34 │
35 ├─ codewhale app-server --http → HTTP/SSE runtime API (/v1/*) [canonical]
36 ├─ codewhale app-server --mobile → runtime API + mobile control page
37 ├─ codewhale app-server --stdio → JSON-RPC control transport over stdio
38 ├─ codewhale app-server --socket → same JSON-RPC over a unix domain socket (desktop daemon)
39 ├─ codewhale doctor --json → machine-readable health & capability
40 ├─ codewhale serve --acp → ACP stdio agent for editors such as Zed
41 ├─ codewhale serve --mcp → MCP stdio server
42 ├─ codewhale serve --http/--mobile → legacy aliases for `app-server --http/--mobile`
43 └─ codewhale exec [args] → one-shot headless worker (stream-json)
44 ```
45
46 The engine runs as a local-only process. All APIs bind to `localhost` by
47 default. No hosted relay, no provider-token custody, no secret leakage.
48
49 For the read-only record of what a thread or turn did, see
50 [`docs/RECEIPTS.md`](RECEIPTS.md): `codewhale receipts` on the CLI and the
51 `/receipt` routes under **Threads** below.
52
53 ## Runtime API entrypoints
54
55 | Entry | Transport | Use |
56 |---|---|---|
57 | `codewhale web [--port 7878]` | HTTP/SSE on `127.0.0.1:7878` + embedded client | First-class loopback-only browser client; opens the default browser. Can serve the shared app build via `CODEWHALE_WEB_DIST` ([WEB.md](WEB.md#serving-the-shared-app-build)) |
58 | `codewhale app-server --http` | HTTP/SSE on `127.0.0.1:7878` | Full `/v1/*` runtime API (canonical) |
59 | `codewhale app-server --mobile` | HTTP/SSE on loopback + `/mobile` | Runtime API + local mobile control page |
60 | `codewhale app-server --stdio` | Initialized JSONL over stdio | Compatibility controls and explicit tool-free turns through the held manager; no hidden TCP listener or full Codex interaction channel. |
61 | `codewhale app-server --socket [--socket-path P]` | RPC text messages over WebSocket on a `0600` Unix domain socket (macOS/Linux) or an owner-only named pipe (Windows) | Desktop daemon: multi-client, kernel peer identity checked, `daemon/attach` claim handshake. Windows native-app qualification remains open. |
62 | `codewhale app-server` | Initialized JSONL over stdio | Same selection as `--stdio`; HTTP requires explicit `--http`. |
63 | `codewhale serve --http` / `--mobile` | same server as `app-server --http`/`--mobile` | Compatibility aliases |
64
65 `app-server --http` and `--mobile` launch the same mature runtime API server
66 historically reached through `serve --http` — no routes or behavior changed, so
67 every endpoint documented below is identical across both entrypoints. The
68 runtime API token is read from `--auth-token`, then `CODEWHALE_RUNTIME_TOKEN`,
69 then `DEEPSEEK_RUNTIME_TOKEN`; use `--insecure-no-auth` only with a loopback
70 bind. The `serve` compatibility aliases keep their `--insecure` flag.
71 Bare `app-server` does not open an HTTP port. Selected attached HTTP listeners
72 retain their explicit bearer and non-loopback security checks.
73
74 Initialized stdio/private-socket controls support `thread/loaded/list` with
75 `{cursor?: string | null, limit?: number | null}`. The result is
76 `{data: string[], nextCursor: string | null}` from the held manager's loaded
77 engine snapshot, including idle and archived engines still in memory. It does
78 not enumerate saved history or only running turns. Omit the limit for the full
79 snapshot. A zero limit is clamped to one entry when entries remain, so an
80 empty page cannot retain an unchanged continuation. Pass the opaque
81 `nextCursor` back unchanged; loading or
82 unloading between pages can change the snapshot. The
83 `app/thread_loaded_list`, `app/thread-loaded-list` and `app/request`
84 `ThreadLoadedList` compatibility forms retain their thread-object wrapper and
85 now use that same loaded-engine authority. Full-tool `turn/start`, interaction
86 responses and subscription/reconnect parity remain unavailable.
87
88 The pinned `thread/name/set` control takes `{threadId: string, name: string}`
89 and returns `{}` after the existing held owner persists the canonical title.
90 The legacy `thread/set_name`, `thread/set-name` and typed compatibility request
91 retain their current parameter and response shapes. An empty or whitespace-only
92 name clears the title through the same manager. The durable Runtime journal
93 continues to publish `thread.updated`; the pinned `thread/name/updated` fan-out
94 and per-connection subscriptions remain part of the unfinished event contract.
95
96 Device tokens minted by the master through `POST /v1/auth/client-tokens`
97 have an immutable `intent`: `watch` (the default when omitted) or explicit
98 `drive`. Labels do not grant authority. Watch permits ordinary GET/HEAD reads,
99 Computer display and one-use display tickets; it cannot mutate Runtime state,
100 upgrade a protected HTTP read into a write channel, acquire/release control,
101 or forward display input. Drive retains the existing Runtime/control authority
102 but cannot mint, list or revoke device tokens. Display tickets retain the
103 issuing principal's intent; input still requires its current, live control lease.
104
105 `GET /v1/runtime/info` advertises `capabilities.client_token_intents: true`,
106 and the mint receipt returns `device_id`, `intent` and `expires_at`. A relay
107 grant issuer must require this capability before minting and validate that
108 receipt against the requested device/intent before exposing a token. Older
109 Engines lack enforcement and must refuse relay grants through this issuer;
110 an intent-like label or a successful legacy mint is insufficient. This change
111 does not add account/Computer ownership scopes to Engine-local device tokens.
112
113 ### Workspace file suggestions
114
115 `GET /v1/workspace/files/search?query=runtime&limit=20` returns
116 `{"paths":["src/runtime.rs"]}` through the existing authenticated `/v1/*`
117 router. Pass `thread_id` to search the workspace recorded for that thread.
118 Omit it to search the server's configured workspace. The response contains
119 workspace-relative file paths with `/`
120 separators, never file contents, absolute paths, or directories.
121
122 - `query` is a literal partial filename/path, without an `@` prefix, at most
123 256 UTF-8 bytes. Missing, empty, or whitespace-only queries return an empty
124 list without walking the filesystem. No match also returns an empty list.
125 - `limit` defaults to 20; accepted values are 1–100. Invalid limits, oversized
126 queries, and unknown query parameters return HTTP 400.
127 - Matching reuses TUI fuzzy `@file` discovery/ranking: case-insensitive path
128 prefix matches first, then substring matches, alphabetically within each
129 group. This is not glob, subsequence, content, or semantic search, and does
130 not apply the TUI's personal frecency boosts.
131 - Discovery shares the composer's ignore policy, including `.ignore` and
132 `.deepseekignore`, always-discoverable AI directories, and the bounded
133 hidden/gitignored local-reference fallback. The special `.agents`, `.claude`,
134 `.cursor`, and `.deepseek` walks intentionally bypass ignore rules, as in
135 the TUI. Ignore files are not confidentiality boundaries.
136 - Directory symlinks are not traversed. Files are canonicalized and filtered
137 for containment in the workspace before applying the result limit; external
138 and broken file symlinks are omitted. In-workspace file symlinks may appear
139 by their relative names. Suggestions are a filesystem snapshot, not
140 authorization to read a file later; consumers must revalidate when opening it.
141
142 Discovery runs off the async executor, with the shared default depth of 10,
143 at most 20,000 candidates, and a cooperative two-second discovery budget.
144 Results are best-effort, not an exhaustive listing; a slow filesystem operation
145 can finish after that budget. Each request scans anew; there is no new index or
146 cache. This read-only endpoint does not alter sessions or the pinned model
147 prompt/tool prefix.
148
149 ### Workspace files and session artifacts
150
151 Native clients browse and edit
152 the server's configured workspace through three authenticated routes. They
153 read and write the workspace directly; there is no second file store, cache
154 or index, and no path override: the workspace root is the only root.
155
156 - `GET /v1/workspace/files?path=<dir>&limit=<1-2000>` lists one directory.
157 `path` is workspace-relative with `/` separators; empty or `.` is the root.
158 Each entry carries `name`, `path`, `kind` (`file`, `directory`, `symlink`,
159 `other`), and for files `size` and `modified` (RFC 3339). Directories sort
160 first, then names case-insensitively. `limit` defaults to 200; `truncated`
161 reports a cut. `.git` is never listed or served, and symlinks are listed by
162 name only: they are never followed, so `path=<link>` returns 403.
163 - `GET /v1/workspace/files/read?path=<file>&offset=<bytes>&limit=<1-4194304>`
164 returns one byte window of a regular file with `size`, `revision` (the
165 SHA-256 hex of the **whole** file, not of the window), `modified`,
166 `offset`, `bytes`, `truncated`, `encoding` and `content`. Text windows are
167 `utf-8`; a window with a NUL byte, invalid UTF-8, or a split multi-byte
168 character is `base64`. `limit` defaults to 256 KiB. Files above 16 MiB are
169 refused with 413; a directory is 400; a link is 403; a missing file is 404.
170 - `PUT /v1/workspace/files` with `{"path", "content", "encoding"?,
171 "expected_revision"?}` writes one file atomically through the same confined
172 opener Fleet artifacts use. `encoding` is `utf-8` (default) or `base64`;
173 bodies above 4 MiB are 413. Creating a new file requires **no**
174 `expected_revision` (and creates missing parent directories inside the
175 workspace); overwriting requires the `revision` from the read that the
176 edit was based on, and a stale or missing one is 409 with the current
177 revision in the error message so the client can re-read and merge. This is
178 optimistic concurrency, not a lock: two writers racing between the check and
179 the write can still interleave. The response carries `path`, `size`,
180 `revision`, `created` and `written_at`; 201 for a new file, 200 otherwise.
181 Writes through a link, into `.git`, or to a directory are refused.
182 `PUT /v1/workspace/files?thread_id=<id>` writes into that thread's recorded
183 workspace instead (capability `thread_scoped_file_writes`), with the same
184 confinement and revision rules and the thread errors described under
185 thread-scoped reads.
186
187 Every path is validated before any filesystem access: absolute paths,
188 backslashes, `.` or `..` components are 400, and each directory on the way is
189 opened without following links (`O_NOFOLLOW` per component on Unix, reparse
190 point checks on Windows). These routes use the runtime bearer token like every
191 other `/v1/*` route; they do not consult the model's tool permission posture,
192 because the caller is the authenticated operator, not the model.
193
194 Session artifacts are the oversized tool outputs a session recorded as
195 `ArtifactRecord`s (`crates/tui/src/artifacts.rs`), stored under
196 `sessions/<id>/artifacts/`:
197
198 - `GET /v1/sessions/{id}/artifacts` lists the records a saved session carries:
199 `id`, `kind`, `tool_call_id`, `tool_name`, `created_at`, `byte_size`,
200 `preview` and the session-relative `path`.
201 - `GET /v1/sessions/{id}/artifacts/{artifact_id}?offset=&limit=` reads one
202 artifact with the same window, `revision` and `encoding` contract as the
203 workspace file read. A record whose stored path is absolute or leaves the
204 session directory is 403; a record whose file is gone is 404.
205
206 These routes only serve what a SavedSession indexes (plus immutable image
207 evidence). A runtime turn's spills are read through the turn route below. An
208 unbound runtime thread's engine has no SavedSession index at all, so for its
209 spills the turn record is the only way in.
210
211 #### Turn artifacts
212
213 A turn records what it produced as typed references on its items and on the
214 turn itself. Nothing is scanned to build them. Each fact is recorded where the
215 bytes were written:
216 - file tools and `apply_patch` report `size`/`sha256` in `mutation.files[]`;
217 - spills report `artifact_digest`;
218 - tool media reports `sha256`.
219
220 The workspace-level half comes from the turn's own restore points: the
221 `pre_turn` and `post_turn` receipts in `TurnRecord.workspace_snapshots` (see
222 "Workspace restore points" below), diffed by tree id in the existing side
223 repo. No second store, snapshot or event is involved.
224
225 A reference (`TurnArtifactRef`) carries:
226
227 | Field | Meaning |
228 | --- | --- |
229 | `id` | Stable within the turn. A file's id is `file_` plus the first 32 hex digits of SHA-256(path). A spill's is `art_<call>`. Media's is `art_image_<sha256>`. |
230 | `kind` | `file`, `tool_output` or `media`. |
231 | `path` | For `file`: workspace-relative with `/` separators. For `tool_output` and `media`: session-relative (`artifacts/...`). |
232 | `change` | For `file` only: `created`, `updated`, `deleted` or `renamed`. A rename also has `previous_path`. |
233 | `size` | Byte size. Absent when the file was deleted. |
234 | `revision` | SHA-256 hex of the whole content. This is the value `GET /v1/workspace/files/read` reports as `revision`, and file-revert's `expected_hash` is `sha256:` + `revision`. Absent when the file was deleted, or for a delta blob over 16 MiB. |
235 | `content_type` | For `media`: the exact media type. |
236 | `session_id` | For `tool_output` and `media`: the artifact session that owns the bytes. |
237 | `item_id`, `tool_call_id`, `tool_name` | The tool call that wrote it. Absent for a change seen only in the workspace delta. |
238 | `source` | `tool_mutation`, `tool_output_spill`, `tool_media`, or `workspace_changed_during_turn`. |
239 | `restore_snapshot_id` | A restore point `POST /v1/threads/{id}/file-revert` accepts for this path on this thread: the `tree_id` of a receipt recorded on this turn's `workspace_snapshots`, so the thread owns it whether or not it is bound to a saved session. For a tool write it is the call's `tool` receipt; for a delta change it is the turn's `pre_turn` receipt. Absent when the turn recorded no such receipt. |
240 | `recorded_at` | When the reference was recorded. |
241
242 Where references appear:
243 - **Items.** `TurnItemRecord.artifacts` lists what one tool call produced. It
244 is set when the call completes, succeeded or failed, so `item.completed` and
245 `item.failed` carry it live.
246 - **Legacy projection.** `artifact_refs` is derived from `artifacts`. It holds
247 only the workspace-relative paths of files that still exist: never spills,
248 media or deleted files.
249 - **Turns.** `TurnRecord.artifacts` is the turn aggregate. It is computed by
250 one merge and ordered most recent first.
251 - Spill and media refs are always kept.
252 - File refs compose in item order: created then deleted drops the file,
253 created then updated stays `created`, and a rename folds its origin.
254 - Once the workspace delta settles, it is authoritative for the net change,
255 `size` and `revision` of every path the snapshots can see. It adds files
256 no tool receipt named, such as shell and sub-agent writes. It drops an item
257 path the snapshots track but that ended the turn unchanged.
258 - The aggregate is capped at 1000 refs, and `workspace.truncated` /
259 `workspace.omitted` report the cut.
260
261 `TurnRecord.workspace` follows the delta's lifecycle. It is `null` while the
262 turn runs. `turn.completed` carries it with one of these states:
263 - `pending`: the turn recorded both a `pre_turn` and a `post_turn` receipt,
264 and their diff is still running. When it finishes, the runtime publishes
265 `turn.artifacts`
266 (`{turn_id, workspace, artifacts}`). That event may arrive after the next
267 turn's `turn.started`, so key it by `turn_id`.
268 - `settled`: the delta is merged. `pre_turn_snapshot_id` and
269 `post_turn_snapshot_id` are the tree ids of the pair.
270 - `unavailable`: no delta will come. `reason` says why:
271 - `snapshots_disabled`, `workspace_too_large`, `too_many_files`,
272 `unsafe_location`, `snapshot_failed`: the snapshot gates. A turn with a
273 `pre_turn` receipt but no `post_turn` one keeps `pre_turn_snapshot_id`.
274 - `not_captured`: the turn recorded no restore point: a compaction or purge
275 operation, or a turn whose engine ended before taking one.
276 - `runtime_restarted`: the process stopped before the delta settled. This is
277 reconciled at startup and never recomputed.
278 - `delta_failed`: the diff itself failed.
279
280 `artifacts` still holds what the tool receipts recorded. `turn.artifacts` is
281 published for every settlement outcome, so a client waiting on `pending`
282 always hears back.
283
284 What the delta means, and what it cannot see:
285 - **It is a workspace diff, not attribution.** A delta change is everything
286 that changed in the workspace while the turn ran. That includes an editor,
287 another thread, or a background job writing the same workspace at the same
288 time. `source: workspace_changed_during_turn` says exactly that.
289 - **Excluded paths are invisible to snapshots.** This covers the built-in
290 excludes (for example `node_modules/`, `target/`, `dist/`, `build/`,
291 `.next/`, and binary and media extensions) and the workspace's `.gitignore`. A file tool's write to
292 such a path is still reported from its receipt. A shell command's write to
293 one is not reported at all.
294 - **Shell writes have no per-call record.** A shell command's writes are
295 never attributed to its item, only to the turn, and only when snapshots are
296 enabled.
297
298 Routes:
299
300 - `GET /v1/threads/{id}/turns/{turn_id}/artifacts` returns
301 `{thread_id, turn_id, workspace, artifacts}` from the runtime store's turn
302 record. While the turn runs, `artifacts` is merged from its items on the fly
303 and `workspace` is `null`. An unknown turn, or a turn of another thread, is
304 404.
305 - `GET /v1/threads/{id}/turns/{turn_id}/artifacts/{artifact_id}?offset=&limit=&revision=`
306 reads one reference.
307 - It uses the workspace file read's window contract (`size`, `revision`,
308 `offset`, `bytes`, `truncated`, `encoding`, `content`) and adds:
309 - `artifact`: the reference;
310 - `source`: `workspace`, `snapshot` or `session_artifact`;
311 - `current`: whether the workspace still holds these bytes, or `null`
312 when that is not a question for this reference.
313 - `revision` selects an intermediate revision one of the turn's items
314 recorded. The default is the reference's own revision.
315 - A `file` is served from the workspace when it still holds the recorded
316 revision (`current: true`). Otherwise it comes from the turn's post-turn
317 snapshot (`current: false`).
318 - A `tool_output` or `media` reference is read under the session artifact
319 root the writer used. The same confinement, image-manifest and integrity
320 checks apply as for the session route.
321 - `GET /v1/threads/{id}/turns/{turn_id}/calls/{tool_call_id}/changes?limit=`
322 returns what **one** tool call changed, read from the same two restore
323 points the engine recorded around it (the call's `tool:` receipt and its
324 `post-tool:` partner on this turn):
325
326 ```json
327 {
328 "thread_id": "thr_1a2b3c4d", "turn_id": "turn_…", "tool_call_id": "call_…",
329 "tool_name": "exec_shell",
330 "state": "captured", "reason": null, "truncated": false,
331 "files": [
332 {
333 "path": "out/result.json", "change": "created",
334 "added": 12, "removed": 0, "size": 210, "revision": "<sha256 hex>",
335 "restore_snapshot_id": "<pre tree id>",
336 "diff": "@@ -0,0 +1,12 @@\n+{}\n", "diff_truncated": false
337 }
338 ]
339 }
340 ```
341
342 - This is the per-call counterpart of the turn aggregate, and the only
343 surface on which a **shell command's own writes** are attributable to that
344 command: a command produces no `metadata.mutation`, so nothing else names
345 what it wrote. The files a file tool changed are here too, read from the
346 same span.
347 - `change` is `created`, `updated` or `deleted` (git's `A`/`M`/`D`, with a
348 type change read as `updated`; the diff runs with `--no-renames`, so a move
349 is a delete plus a create). `added`/`removed` are `null` for a binary path.
350 - `size` and `revision` are the span's **end**, never the work tree as it is
351 now. `revision` is bare SHA-256 hex; pass `sha256:` followed by that hex as
352 `file-revert`'s `expected_hash`, or `absent` for a path deleted by the call.
353 Both are `null` when the path was deleted here or is too large to read.
354 - `diff` is the patch between the two restore points, cut at 64 KiB on a char
355 boundary (`diff_truncated` says so). It is `null` when there is nothing to
356 render: a binary path, a change with no content delta, or no patch.
357 - `state: "pending"` means the recorded call is queued or in progress and
358 its snapshot pair is incomplete. `reason` is `null` and `files` is empty;
359 read again after settlement. Once both receipts exist, the state is
360 `captured`, including when the call changed nothing.
361 - `state: "unavailable"` means the settled span cannot be resolved, and `reason`
362 says why: `call_not_bounded` (the call took no receipt — the engine judged
363 it read-only, or the turn predates receipts), `post_snapshot_missing` (the
364 opening receipt exists and the closing one was lost), `pre_snapshot_missing`,
365 or `snapshots_pruned` (the receipts are still on the turn, but the side repo
366 no longer holds the trees they name — snapshots are pruned to the newest few
367 while turn records are durable, so an older turn's span is regularly
368 unrecoverable, and a workspace whose store was deleted reads the same way).
369 This is **not** the same answer as an empty `files` list, which means the
370 span changed nothing, and the receipt's own `changed_paths` remain readable
371 on the turn record either way.
372 - `limit` (default 200, max 1000) caps the list; `truncated` says it was cut,
373 and how many paths were left off is not counted.
374 - Reading the span runs `git diff` inside the side repo. Neither the work
375 tree nor the index is touched.
376
377 | Status | When |
378 | --- | --- |
379 | 404 | Unknown thread or turn, a turn of another thread, or a `tool_call_id` this turn has no item or receipt for. |
380 | 400 | `limit` outside `1..=1000`. |
381 | 500 | A runtime item record could not be read or parsed, or an operational failure occurred reading the snapshot repository; this is not evidence that the call was unbounded or snapshots were pruned. |
382
383 The artifact routes answer:
384
385 | Status | When |
386 | --- | --- |
387 | 404 | Unknown thread, turn or artifact id, or a `revision` this turn never recorded. |
388 | 409 | A file's recorded revision is in neither the workspace nor the snapshot store (snapshots are pruned after 50 per workspace or 7 days), or a session artifact's bytes no longer hash to the recorded revision. The message names the current revision. |
389 | 410 | The turn deleted the file (restore it with `file-revert` and `restore_snapshot_id`), or a session artifact's bytes were pruned. |
390 | 413 | Content over 16 MiB. |
391 | 403 | A symlink, or a reference that leaves its root. |
392
393 Fleet receipt artifacts keep their own route
394 (`GET /v1/fleet/runs/{run_id}/receipts/{task_id}/evidence`).
395
396 ### Runtime and account identity
397
398 `GET /v1/runtime/info` reports `codewhale_version` plus the full 40-character
399 `codewhale_commit` embedded by the shared CLI/TUI build. A source archive that
400 cannot provide an exact commit reports `unknown`, allowing compatibility
401 clients to fail closed rather than accepting an ambiguous binary pair.
402
403 `sandbox.kind` names the OS wrapper commands get (`linux-bwrap`, `macos-seatbelt`,
404 `none`); `sandbox.tool_launcher` is true when the managed configuration runs
405 tools as another user. Both are computed when the route is called, and with a
406 launcher `kind` is `linux-bwrap` only after the launcher probe has passed.
407
408 The same response advertises `capabilities.account_session: true` and
409 `capabilities.turn_operation_idempotency: true`. A client must require the
410 latter before relying on `operation_key`; do not infer support from a 2xx turn
411 response because an older tolerant reader may ignore an unknown request field.
412 `capabilities.turn_operation_lookup: true` separately advertises the read-only
413 operation lookup below; clients must require it before relying on GET-based
414 recovery of a lost turn response.
415
416 `capabilities.thread_create_idempotency: true` separately advertises
417 `POST /v1/threads` with `operation_key` (or `operationKey`). Keys use the same
418 validation as turn operation keys and are scoped to the Runtime store owner.
419 Exact retries return the original thread, including after response loss or
420 restart; a different effective request with the same key returns HTTP 409.
421 The fingerprint includes the resolved model/provider, workspace, reasoning,
422 permission and shell policy, tool allowlist, tool denylist, archival state,
423 prompt/task fields, dynamic tools and environments. Creation defaults are
424 resolved before comparison.
425 Operation records retain only fingerprints and reserved identity, never the raw
426 key. Missing committed thread data is an error, never permission to create a
427 replacement. Clients must require this capability before relying on creation
428 replay, because an older reader may silently ignore an unknown request field.
429 The response also includes a token-free account receipt:
430
431 ```json
432 {
433 "account": {
434 "schema_version": 1,
435 "state": "authenticated",
436 "api_base": "https://api.codewhale.net",
437 "account_id": "acct_...",
438 "session_id": "session_...",
439 "scopes": [],
440 "expires_at": "2026-08-01T20:00:00Z"
441 }
442 }
443 ```
444
445 The Runtime reads this receipt from the exact profile- and API-origin-scoped
446 secure record written by `codewhale account login`; it does not run a second
447 login flow. States are `signed_out`, `authenticated`, `offline_cached`,
448 `expired`, or `revoked`. Scopes are copied only from explicit stored session
449 grants and are never inferred from account identity. Access/refresh tokens,
450 email, provider profile, and provider credentials are never returned.
451 `account_id` and `session_id` are included only for a request authorized with
452 the Runtime token (or an explicitly insecure loopback server); the public
453 bootstrap response remains usable but reports `signed_out`. Signed-out local
454 Work remains supported and never allocates cloud compute implicitly.
455
456 The native host account routes below require the configured master token in
457 the Authorization header. Browser/mobile device sessions and insecure mode do
458 not authorize them. Responses use `Cache-Control: private, no-store`. These
459 routes are excluded from the desktop renderer's Engine request allowlist.
460
461 | Route | Native host operation |
462 | --- | --- |
463 | `GET /v1/account/status` | Token-free account state, exact API origin/profile, opaque revision and whether legacy import is permitted. |
464 | `POST /v1/account/claim` | Renew a login claim only for the supplied `expectedRevision`, preserving existing account identity. |
465 | `DELETE /v1/account/claim` | Cancel exactly the supplied `expectedRevision`; a newer claim is preserved. |
466 | `POST /v1/account/import` | Adopt the host's completed browser authorization with `expectedRevision` and `auth`; legacy import requires pristine storage, while explicit sign-in supplies `replaceExisting`. |
467 | `POST /v1/account/lease` | Return a short-lived access credential to native main memory; Rust owns refresh and durable custody. Optional `rejectedAccessToken` requests renewal only if that credential is still current. No refresh token is returned. |
468 | `DELETE /v1/account/session` | Sign out exactly the supplied `expectedRevision`, preserving provider credentials and local work. A changed revision returns conflict rather than signing out another account. |
469
470 The lease is sensitive native-host transport, separate from the token-free
471 runtime receipt above. Native clients retain it only in main memory and fence
472 responses by Engine connection and account/session identity. Shared account
473 records use revision nonces and signed-out tombstones so cancelled or stale
474 login completion cannot restore an account after logout. Older authenticated
475 records remain readable; older binaries fail closed on signed-out tombstones.
476
477 The `--stdio` control transport uses newline-delimited RPC. Request IDs are
478 strings or signed 64-bit integers. Output omits `jsonrpc`; input also accepts
479 unknown input fields, as the pinned Codex decoder does. Complete `initialize`
480 once and receive its result. Clients then send the ID-absent `initialized`
481 notification before ordinary requests. It has no reply or authority effect;
482 as in the pinned implementation, server initialization is committed by the
483 successful initialize request. Repeated initialization and business requests
484 before initialize refuse. Malformed envelopes are discarded
485 without a fabricated null-ID response; invalid-ID method objects follow the
486 pinned notification fallback and cannot become business calls. Probe it
487 without spending model tokens:
488
489 ```bash
490 printf '%s\n' \
491 '{"id":"init","method":"initialize","params":{"clientInfo":{"name":"probe","version":"1"}}}' \
492 '{"method":"initialized"}' \
493 '{"jsonrpc":"2.0","id":1,"method":"healthz"}' \
494 '{"jsonrpc":"2.0","id":2,"method":"capabilities"}' \
495 '{"jsonrpc":"2.0","id":3,"method":"shutdown"}' \
496 | codewhale app-server --stdio
497 ```
498
499 Local control and ACP frames have an 8 MiB encoded body limit, excluding the
500 newline separator. Serialization stops at that limit before writing an
501 oversized frame. Body, newline and flush share a 30-second backpressure
502 deadline; owner attachment, request forwarding and frontend readiness keep
503 their tighter 5-second envelopes. A partial write, flush failure or deadline
504 ends the affected stream; it cannot be followed by another response or an
505 automatic replay. This write deadline also applies to compatibility stdio
506 replies/events and relay stdout. Compatibility execution, history, provider
507 catalogs, output-limit preflight and saved-config reload call the same held
508 native frontend directly; they do not make loopback HTTP requests.
509
510 `capabilities` returns the advertised method families (`thread/*`, `app/*`,
511 `prompt/*`) and the full method list; `thread/capabilities`,
512 `app/capabilities`, and `prompt/capabilities` scope it per family. The method
513 set is pinned by a drift test in `crates/app-server/src/tests.rs`, so SDK and
514 local integration clients can rely on it not changing silently. The permanently
515 refused compatibility goal setter is omitted from discovery while
516 `goal_execution` is false; goal reads and clears remain advertised.
517
518 ### Daemon socket: `codewhale app-server --socket`
519
520 The socket transport exposes compatibility controls on a long-lived daemon.
521 The same dispatcher consumes RPC objects over private-channel WebSocket text
522 messages. Process stdio uses JSONL; the private channel upgrades before its
523 attachment handshake.
524
525 **Endpoint.** `--socket-path` if given; else `$CODEWHALE_HOME/run/daemon.sock`
526 when `CODEWHALE_HOME` is set (an explicit home is an isolation boundary); else
527 `$XDG_RUNTIME_DIR/codewhale/daemon.sock`; else
528 `~/Library/Application Support/codewhale/daemon.sock` on macOS or
529 `~/.codewhale/run/daemon.sock` elsewhere. On Unix, an implicit endpoint that
530 leaves insufficient room for the store-specific socket automatically uses a
531 private deterministic short temporary directory; the data home stays in place.
532 Explicit socket selections remain exact, and an overlong explicit path is
533 refused. The directory is created `0700`, the
534 socket is `0600`, and every accepted peer must present the daemon's own uid.
535 On start, a socket file nobody answers on is removed; a live one makes the new
536 daemon exit with `a live listener already answers on <path>; refusing to
537 replace it`; a non-socket file at the path is never touched. On Windows the owner-private named-pipe transport uses the same dispatcher;
538 its native application qualification remains open. There is no TCP fallback. The daemon prints
539 `codewhale daemon: listening on <path>` to stderr once it is accepting.
540
541 **Handshake.** After kernel peer admission, upgrade the private connection to
542 WebSocket. Upgrade headers are limited to 16 KiB and five seconds; any Origin
543 header refuses. Each subsequent text message contains one complete JSON object,
544 with an 8 MiB frame and reassembled-message limit. Binary messages are unsupported
545 and discarded without negotiation of compression. Control, scoped Control, ACP
546 and listener attachments all use this framing. Process stdio remains JSONL.
547
548 The first RPC request must be `daemon/attach` (`healthz` is also allowed beforehand). Every
549 other method is refused with `-32010 attach_required` until then. After the
550 private attachment handshake, complete `initialize` followed by `initialized`
551 on the Control connection before business requests. ACP retains its JSON-RPC 2.0
552 envelope, permission response IDs and EOF cancellation policy inside WebSocket
553 text messages. Named-pipe ACLs and peer-process checks remain mandatory.
554
555 ```json
556 {"id":1,"method":"daemon/attach","params":{
557 "client":{"name":"codewhale-desktop","version":"1.2.3","pid":4242},
558 "mode":"claim",
559 "expect_daemon_version":"0.9.11"}}
560 ```
561
562 `mode` is `"claim"` (this client spawned the daemon and manages its lifetime)
563 or `"attach"` (default: a guest that found a healthy daemon). A claim while
564 another connection owns the daemon fails with `-32011 daemon_already_claimed`
565 (`data.owner` names the holder) and the client should retry with `attach`.
566 `expect_daemon_version`, when present, must equal the daemon's crate version
567 or the attach fails with `-32013 daemon_version_skew` (the bundle-skew guard).
568 The reply reports the granted `role` (`owner` / `attached`), the daemon's
569 `pid`, `version`, `socket_path`, and `uptime_ms`, the current `owner`, and the
570 live `connections` count. A second `daemon/attach` on an attached connection
571 is `-32014 already_attached`.
572
573 **Capabilities.** On this transport `capabilities.methods` is the pinned stdio
574 set plus `daemon/attach` (second entry, after `healthz`); `transport` reads
575 `unix-socket` (or `named-pipe` on Windows), and `framing` is `websocket-text`.
576 Stdio advertises `framing: "jsonl"`. `shutdown` is advertised to every connection because the method
577 exists, but only the owner may call it (below).
578
579 **Ownership.** Only the owner may `shutdown`; a guest's `shutdown` is refused
580 with `-32012 not_daemon_owner` and does not interrupt anyone's turn. When the
581 owner disconnects the slot frees, so a relaunched shell re-claims the daemon it
582 left running. The owner's `shutdown` stops the listener, closes every
583 connection, and removes the socket file. Journal replay from a client's
584 last-seen `seq` is not part of this transport yet.
585
586 ### Compatibility execution limits
587
588 The compatibility HTTP, stdio and socket interfaces advertise
589 `interactive_execution: false`, `goal_execution: false`, `tool_free_turns: true` and
590 `full_api_entrypoint: "codewhale app-server --http"`. Clients must require
591 `tool_free_turns: true` before relying on an empty allowlist: older compatibility
592 servers may ignore the field. Every `thread/message`,
593 `thread/request` message, `prompt/run`, `prompt/request` and HTTP `/prompt` or
594 `/thread` message requires an explicit `allowed_tools: []`. Omitted, null or
595 nonempty lists fail with `interactive_execution_unsupported` before creating a
596 Runtime thread or starting a turn. Malformed lists fail parameter decoding.
597 JSON-RPC reports `-32602` with `data.error: "interactive_execution_unsupported"`;
598 HTTP reports 400 with `error.code: "invalid_request"`, `error.jsonrpc_code: -32602`
599 and the same detail in `error.data`. Compatibility `thread/goal/set` and
600 `ThreadRequest::GoalSet` also refuse before changing the goal: setting an active
601 goal starts background Engine work. Reading and clearing existing goals remain
602 available; starting goals uses the full Runtime HTTP API. The known setter
603 remains recognized for older clients to get this actionable refusal, but it is
604 not advertised as an available method. For example:
605
606 ```json
607 {"jsonrpc":"2.0","id":3,"method":"thread/message","params":{"thread_id":"thr_...","input":"Summarize this conversation","allowed_tools":[]}}
608 ```
609
610 The bridge sends the same empty allowlist to the canonical Runtime for each
611 admitted turn, so a tool-enabled thread cannot widen it. It forwards assistant
612 text and terminal status. Unexpected approval or clarification requests fail
613 and interrupt the exact owned turn; they cannot wait silently. This deliberately
614 narrows the old compatibility behavior. Tool-enabled clients must migrate to
615 the authenticated `/v1/*` API and SSE rather than enabling Full Access.
616
617 ### Interrupting a turn
618
619 `thread/message` streams until the turn reaches a terminal state, which can
620 take minutes. The read loop keeps polling stdin while a turn streams, so a
621 client can send:
622
623 ```json
624 {"jsonrpc":"2.0","id":9,"method":"thread/interrupt","params":{"thread_id":"thr_..."}}
625 ```
626
627 and the runtime is asked to interrupt that turn
628 (`POST /v1/threads/{id}/turns/{turn_id}/interrupt`). The reply carries
629 `interrupted: false` when no turn is streaming for that thread — this is not
630 an error, just nothing to stop. The interrupted `thread/message` then fails
631 with a `turn interrupted` error, and its reply is written before the
632 interrupt's own reply, since the turn owns the writer until it unwinds.
633
634 `shutdown` sent during a live turn also interrupts first: it needs the same
635 bridge that the turn holds, so without that it would wait for the very turn
636 it was meant to stop. Other requests that arrive mid-turn are queued and run
637 in order once the turn finishes.
638
639 ### Running a prompt
640
641 `prompt/request` and `prompt/run` (byte-identical aliases) and the legacy
642 HTTP `POST /prompt` all execute a **real turn** on the runtime, through the
643 same bridge `thread/message` uses. There is no local fallback: nothing else
644 in the app-server can produce model output, so a prompt either runs or fails.
645
646 - `params.prompt` is required and must be non-empty (`-32602` otherwise).
647 - `params.allowed_tools` must be `[]`; interactive turns use `app-server --http`.
648 - `params.thread_id` is optional. With one, the prompt runs on that thread and
649 its history. Without one, the runtime gets a fresh thread for that single
650 turn; the mapping is dropped when the turn ends, so a one-shot prompt is not
651 addressable by `thread/interrupt`. Use `thread/message` when you need to be
652 able to interrupt.
653 - `params.model` selects the model only when the call is the one that creates
654 the runtime thread; an existing thread keeps the model it was created with.
655 - The response carries what the model actually said: `output` is the
656 concatenated `agent_message` text, `model` is the model the runtime reports
657 for the thread that ran it, and `events` are the real
658 `response_start`/`response_delta`/`response_end` frames. Over stdio the same
659 frames are also streamed to stdout while the turn runs, exactly as for
660 `thread/message`.
661 - If the runtime cannot be reached, the call fails with `-32005`
662 (`runtime_unavailable`) on stdio, or HTTP `503` with
663 `{"error":{"code":"runtime_unavailable", ...}}` on `POST /prompt`. Failures
664 are never shaped like a successful `PromptResponse`.
665
666 `POST /thread` with a `Message` body behaves the same way — it runs the turn
667 and replies `status: "completed"` with the streamed frames in `events` — where
668 it previously replied `accepted` without doing anything.
669
670 ### Compatibility list and read parameters
671
672 `thread/list` accepts only `include_archived` and `limit`; `thread/read`
673 accepts only `thread_id` and returns the complete legacy history projection.
674 Both also apply inside `thread/request`. Unknown fields fail with `-32602`
675 before contacting the canonical owner. Workspace, cursor, `archived`, search
676 and `includeTurns` parameters from the pinned v2 contract are not implemented
677 by these compatibility methods; they are rejected instead of silently ignored.
678 These method names do not establish Codex wire parity.
679
680 ### Thread ids and restarts
681
682 `thread/message`, `thread/request` messages, and HTTP `POST /thread` messages
683 take a thread id from `thread/create` (or `thread/fork`). An id that was never
684 created fails with `-32004` (`thread_not_found`) on stdio, or HTTP `404` on
685 `/thread`, before any runtime thread is started. `/prompt`, `prompt/request`,
686 and `prompt/run` are different: their optional `thread_id` is any key the
687 caller chooses, and a new key starts a new conversation.
688
689 The authenticated canonical owner keeps the full saved conversation graph,
690 its selected branch and the thread/session binding. Compatibility controls use
691 that owner; the old SQLite history remains a protected, read-only import source.
692 Import compares the complete source graph and selected leaf before publishing
693 the canonical alias. A failed alias publication retains the source and the
694 actual canonical result so recovery can report what completed.
695
696 Existing validated legacy goals are imported into the owner goal store. Active
697 goals are paused during import; historical data never starts a provider call.
698 Source goal fields participate in the same protected source comparison.
699
700 Saved-session forks preserve the complete journal, including inactive branches,
701 and copy a validated local session-goal sidecar into the new saved session.
702 An active local goal is copied as paused; the source remains unchanged.
703 That sidecar is separate from the public Runtime thread goal. A native Runtime
704 thread fork does not automatically inherit the public thread goal.
705
706 `thread/create`, `thread/start`, `thread/resume` and `thread/fork` carry a
707 client-generated `operation_key`. Capture one key for each user intent before
708 sending it, retain it after an uncertain response, and reuse it when recovering
709 that same intent. Create carries the key in `metadata.operation_key`; Start,
710 Resume and Fork carry it in `operation_key`. Two intentional forks use different
711 keys. Recovery checks
712 the original operation in the existing owner store; it never creates another
713 thread merely because the response was lost or the source later grew.
714
715 `POST /v1/thread-history/operations/lookup` is read-only. Its closed request
716 contains `version: 1`, `operation_key`, `expected_data_dir`,
717 `expected_execution_scope` and `workspace`; the response is `absent`, `pending`
718 or `committed`. A pending or committed response includes the retained receipt
719 and its exact action/source `association`.
720
721 `POST /v1/thread-history/operations/recover` accepts that lookup request in
722 `operation` and the expected `association`. It explicitly finishes an already
723 prepared target under the same owner, after checking the saved document, full
724 graph, workspace, checkpoint and action/source identity. It does not rebuild
725 the original intent from a source that may already have changed. An unprepared
726 target stays pending; a changed or unverifiable target refuses completion.
727 Repeat recovery with the same key to observe the same committed result.
728
729 New history reservations retain their original document/checkpoint observation.
730 An uncommitted recovery must match the complete prepared document and the
731 operation's own publication generation, with its original checkpoint unchanged.
732 An older reservation without that original observation stays pending or refuses
733 recovery; reading current records cannot retrospectively supply it.
734
735 The selected workspace comes from the acknowledged owner or the explicitly
736 admitted request. History and historical receipts cannot supply permissions,
737 credentials, endpoints or a different owner. A missing, changed, busy or
738 incompatible bound store is an explicit failure. A missing canonical target
739 does not start an empty replacement conversation.
740
741 `codewhale thread resume` and `codewhale thread fork` perform the durable
742 owner control and print its committed thread, session and operation receipt.
743 They do not launch an interactive frontend.
744
745 Global `--workspace` (also `--cd`), `--profile` and `--config` select an explicit
746 control scope. Relative paths are captured before attachment; the client
747 authenticates the owner, then admits that scope against the same owner receipt
748 and its captured worker setting. An incompatible profile or config, missing
749 scope facts, or a changed owner fails explicitly. Without these options, the
750 acknowledged owner supplies the workspace. Thread listing remains store-wide.
751
752 For a fresh `thread resume` or `thread fork`, global `--provider`, `--model`,
753 `--approval-policy` and `--sandbox-mode` supply proposals to the existing owner
754 decoder and permission checks. The corresponding `--set` keys are `provider`,
755 `model`, `default_text_model`, `approval_policy` and `sandbox_mode`. Credentials
756 and endpoints stay with the owner: `--api-key`, `--base-url` and other per-run
757 settings are refused for these controls. Configure and authenticate the owning
758 Runtime before using them. With a retained `--operation-key`, newly supplied
759 model, provider, policy or sandbox proposals are refused; recovery observes
760 the original admitted intent.
761
762 Interactive `codewhale resume` and `codewhale fork` use the same canonical
763 history operation. An inactive local owner is shut down and joined before the
764 existing TUI acquires the saved-session lease and store. A live owner or an
765 uncertain handoff refuses attachment. `--operation-key <KEY>` recovers the
766 original outcome, including completing a verified prepared target; an
767 unprepared or unverifiable result preserves uncertainty.
768
769 ### Changing config
770
771 `app/config/set` and `app/config/unset` write the change to the config file
772 before replying: the `--config` path, or the default `config.toml` used by the
773 canonical owner when no `--config` is given. They change user settings that
774 outlive the app-server, not just this session. The change is applied to the
775 file as it is on disk, so edits saved by other processes are kept. If the file
776 cannot be read, parsed, or written, the reply is `ok: false` and nothing
777 changes; a file that does not parse is not rewritten, so fix it by hand (or
778 `app/config/reload` after fixing it). Over HTTP `/app`, a rejected key or value
779 is `400` and a read or write failure is `500`.
780
781 ### Answering a clarification question
782
783 When a headless turn calls `request_user_input`, the runtime emits a
784 `user_input.required` event carrying a `request_id`. Reply on the runtime API:
785
786 ```
787 POST /v1/user-input/{thread_id}/{request_id}
788 ```
789
790 The compatibility control transport cannot accept that reply.
791 `app/request` with `SubmitUserInput` returns `ok: false` and
792 `error: "user_input_reply_unsupported"`. Compatibility turns require an empty
793 tool catalog and refuse interactive execution at admission, so this limitation
794 cannot leave a supported turn waiting for an answer. The fixed catalog and
795 response limitation are Codewhale implementation choices.
796
797 ## SDK contract
798
799 The `@codewhale/runtime-sdk` package currently supplies Fleet helpers and
800 read-only thread event streaming. It does not wrap thread creation, turn
801 start/steer/interrupt, approval decisions, clarification answers or model
802 discovery. Use authenticated raw HTTP for these operations; the package guide
803 provides the [request recipe](../npm/runtime-sdk/README.md#full-engine-api).
804 The hosted Responses SDK is a separate contract.
805
806 The full `app-server --http` API exists so an external SDK can answer — without scraping TUI
807 output — *what route ran, which provider/model/reasoning/permission profile was
808 effective, what events happened, how many tokens were used, and how the run
809 finished.* The durable Thread/Turn/Item data model already carries most of
810 this; the table maps each integration need to where a local client reads it.
811
812 | Integration need | Where it comes from | Status |
813 |---|---|---|
814 | Route / effective model / billing surface | `TurnRecord` + thread `model`; per-run `--provider`/`--model` overrides | available |
815 | Permission / sandbox / approval profile | thread `auto_approve`, sandbox + approval policy; `TurnRecord.permission_posture` + `TurnRecord.mode` for how *that* run was governed (the thread's own `mode` may have been switched since) | available |
816 | Run / thread / turn IDs | `thread_id`, `turn_id`, SSE event envelope | available |
817 | Event stream | `GET /v1/threads/{id}/events` (replay + live SSE) | available |
818 | Turn status / terminal classification | `TurnRecord.status` + error summary | available |
819 | Token usage | `TurnRecord.usage`; aggregate via `GET /v1/usage` | available |
820 | Action receipt (files, commands, web/MCP calls, agents, approvals and who decided, failures) | `GET /v1/threads/{id}/receipt`, `GET /v1/threads/{id}/turns/{turn_id}/receipt` | available ([RECEIPTS.md](RECEIPTS.md)) |
821
822 For one-shot/headless automation, prefer `codewhale exec` with explicit
823 `--provider <id> --model <id>` so a failure identifies the exact provider/model
824 pair. Use `app-server --http` when a local integration needs to start, resume, steer,
825 or interrupt turns, list models/capabilities, follow the event stream, or read
826 usage. Both paths share the same runtime, so route-effective model resolution
827 and the event vocabulary match.
828
829 ### Release smoke
830
831 `scripts/release/app-server-smoke.sh` is the committed pre-release check:
832
833 ```bash
834 scripts/release/app-server-smoke.sh # stdio health/capabilities probe (no tokens)
835 scripts/release/app-server-smoke.sh --matrix # + print the configured provider/model matrix
836 scripts/release/app-server-smoke.sh --matrix --real # + exec a cheap sentinel per provider
837 ```
838
839 The stdio probe runs against a throwaway config, so it never reads real keys.
840 The matrix discovers configured providers from `codewhale auth list`, skips
841 unconfigured providers, and maps a provider to a cheap sentinel model only when
842 it has a built-in cheap default. That built-in set is deliberately conservative
843 (currently `deepseek`, `zai`, `moonshot`, and `openai`); every other provider —
844 including `arcee`, `openrouter`, `xiaomi-mimo`, and `openai-codex` — is left
845 unmapped on purpose and must be given a model per run via `SMOKE_MODEL_<SLUG>`
846 rather than a guessed default (#3205). Any configured-but-unmapped provider
847 fails loudly in `--real` mode. `auth list` reports presence flags only and exec
848 output is passed through a redactor, so secrets are never printed. The parser is
849 covered by `scripts/release/app-server-smoke.test.sh` against a fake `codewhale`
850 binary.
851
852 ## ACP stdio adapter: `codewhale serve --acp`
853
854 For editor setup (including Zed), permissions and limits, see
855 [Use Codewhale from your editor](ACP.md).
856
857 ACP JSON-RPC over newline-delimited stdio is a transport over the existing
858 RuntimeThreadManager and Engine. It has no provider/tool round loop, executable
859 registry, prompt composer, or conversation writer of its own. The server loads
860 the selected config/profile and plugin discovery once; each prompt uses a
861 canonical thread, Core turn, event timeline, approval waiter, and full Engine
862 session snapshot.
863
864 The editor surface supports `initialize`, `session/new`, `session/list`,
865 `session/load` (including durable ID prefixes), `session/prompt`, `session/cancel`,
866 model discovery/selection, and the advertised mode/model config options.
867 `session/new` creates a durable bare UUID and empty checkpoint without calling a
868 provider. `session/load` replays the saved conversation as `session/update`
869 notifications before it responds: user and agent text, then each tool call with
870 its final status. Replayed tool results are masked as on the live stream: a
871 `request_user_input` answer becomes `User input submitted` and configured
872 credentials are redacted. Reasoning and images are not replayed. At most 64 idle transport bindings are retained; eviction keeps the
873 durable conversation. Resume deduplicates against the existing thread binding.
874 Full histories, tool pairs, signatures, media and partial-effect receipts are
875 saved under the same checkpoint guard and session write lease used by HTTP.
876 ACP display text may be shortened; the saved history is the full Core snapshot.
877
878 Codewhale implements a partial ACP v1 adapter. Both `session/new`
879 and `session/load` reject a nonempty client-supplied `mcpServers` list with
880 `-32602` before creating, resuming or returning a cached session. The field may
881 be omitted or `[]`; null and other non-array values are invalid. No supplied
882 command is executed during this validation. [ACP v1 requires stdio MCP support](https://agentclientprotocol.com/protocol/v1/session-setup#mcp-servers);
883 `mcpCapabilities.http: false` and `sse: false` only describe optional transports
884 and do not establish full conformance. Use the full Runtime API and its existing
885 MCP management for those integrations. The restricted tool catalog below is a
886 Codewhale host profile, not an ACP protocol restriction.
887
888 The trusted local ACP profile narrows Core to file/search/git/patch and admitted
889 foreground shell tools, plus reviewed plugin tools (`extension_host` feature) and
890 the tools of MCP servers configured in Codewhale (`mcp` feature), under the same
891 permission setting. Shell requires both editor terminal support and operator
892 `allow_shell`; a requested external sandbox that is unavailable removes shell.
893 Reviewed plugin tools and configured MCP servers are available on this transport.
894 Client-supplied MCP servers, dynamic tools, task/PTY/background shell,
895 interpreter, subagent and RLM lifecycles are unavailable on this transport.
896 ACP has no tool search, so every connected MCP tool and its schema is sent with
897 every request, and a server marked `lazy = true` never starts. A large MCP set
898 therefore costs tokens on each turn and can exceed a provider's tool limit.
899 MCP servers a model starts at run time stay out of an ACP-profile host. When
900 `serve --acp` instead attaches to a running Runtime owner (see below), its turns
901 use that owner's MCP pool, which includes servers started at run time in other
902 sessions of the same workspace.
903 Built-in overrides remove the
904 whole compatibility alias family. Final dispatch rechecks the profile, so a
905 fabricated alias, hook rewrite or omitted catalog entry cannot bypass it. Plan
906 remains read-only under Full Access. Full Access and the ordinary approval
907 posture are server-owned read-only options; the editor cannot widen them.
908 `approval_policy = "never"` is not an ACP posture, so the server refuses to
909 start with it instead of serving it as Ask.
910
911 Full Access is `yolo`. Start it with `codewhale serve --acp --full-access`
912 (the flag may also come before `serve`; `--yolo` is an alias) or set
913 `yolo = true` in config. A configured `sandbox_mode = "danger-full-access"` does
914 not turn it on: that value can only narrow the sandbox the permission picks, so
915 under Ask or Auto-Review it changes nothing, and `ask` is not a config key. At
916 startup the server writes one line to stderr naming the permission and sandbox it
917 will run with, so an editor's agent log shows which posture a launch command
918 produced.
919
920 Tool updates begin `pending`. `in_progress` means Core reached final dispatch;
921 `completed`/`failed` and typed image blocks come from the actual Core result.
922 A read or edit tool call names its file in `locations` as an absolute path
923 (relative paths resolve against the session workspace). A file write or edit
924 start carries an ACP `diff` of the requested text: `oldText` is the edit's
925 search text and is absent for a write, so it is not a whole-file before image
926 and `apply_patch` has none. The same diff leads the content of the call's
927 permission request and completion update, so the editor keeps showing it. Shell output arrives as text content; ACP has no
928 editor-owned `terminal` content on this transport.
929 `session/request_permission` correlates a private JSON-RPC ID to the same
930 Runtime-minted pending approval and Core execution ID. When a plugin tool asks
931 the core to run a tool that needs approval (`exec.core`), the request is shown
932 on the plugin tool's call, names the nested tool and carries its input, and the
933 answer releases the nested call; the nested call is decided under the session's
934 permission setting. Only an exact live
935 `allow-once` response can release that waiter; wrong IDs are ignored, invalid
936 options deny, and cancellation withdraws it. ACP grants neither remembered
937 permissions nor Native capabilities. Core typed rules, strict hooks, repo law,
938 Headless Auto-Review and hard floors remain in force, including the absence of a
939 workspace-write carve-out; a guardian-only decision refuses on this host.
940
941 Replay uses the existing bounded event reader and sequence deduplication. A
942 replay gap, closed owner or terminal store fault is an explicit error, never a
943 re-execution. Input is serviced between replayed events; each transport write has a 30-second
944 deadline. Cancel, EOF and writer
945 failure interrupt only this transport's claimed Core turn; settlement uses its
946 actual terminal receipt and preserves any completed effects. An unconfirmed
947 cancellation does not fabricate success. `stopReason` is `end_turn`, `cancelled`,
948 or typed `max_turn_requests`; Core failure remains an error. Prompts use at most
949 50 model steps (a lower configured limit still wins) and Core's bounded final
950 report response; this profile does not dispatch autonomous goal continuations.
951
952 An oversized or non-UTF8 ACP input frame produces one bounded `-32700` error.
953 After an oversized frame, input is discarded through its actual newline before
954 another request can be admitted; cancellation preserves that discard state.
955 This applies to standalone ACP and an authenticated guest of a normal Runtime
956 owner. Other input I/O failures, owner-reply validation failures and compatibility
957 control framing failures end the stream. An oversized ACP response becomes a
958 bounded `-32603` error, with a null ID if echoing the original ID would also
959 exceed the limit. Oversized notifications refuse before writing and use the
960 existing operation cleanup; they do not report truncated success.
961
962 When no process owns the Runtime store, ACP claims its own exclusive canonical
963 Runtime owner. When a non-ACP Runtime host already owns it (the desktop app,
964 `codewhale app-server --http` or `codewhale serve --http`), ACP attaches to that
965 owner as an authenticated guest over its local control socket and serves the
966 editor from the owner's store. If that owner exits, the ACP process ends with
967 an error naming the exit; pending operation outcomes may be uncertain and are
968 not replayed. A second `codewhale serve --acp` in a store another ACP server
969 already owns refuses at startup and leaves the first serving. A saved
970 conversation bound to another Runtime store also refuses; ACP does not copy a
971 live conversation into a random store. This does not expose every `/v1/*`
972 steering, job or control method to an ACP editor. Use
973 `codewhale app-server --http` for that full runtime API.
974
975
976 ## Capability endpoint: `codewhale doctor --json`
977
978 Returns a JSON object describing the current installation's readiness state.
979 Suitable for health-check polling from a macOS workbench. This command is
980 strictly structural and offline: it does not load workspace credential
981 `.env` files, inspect credential environment values, open secret/OAuth files,
982 probe an OS keyring, contact providers, or start MCP processes.
983
984 ```bash
985 codewhale doctor --json
986 ```
987
988 ### Response schema (key fields)
989
990 | Field | Type | Description |
991 |---|---|---|
992 | `version` | string | Installed version (e.g. `"0.8.9"`) |
993 | `config_path` | string | Resolved config file path |
994 | `config_present` | bool | Whether the config file exists |
995 | `paths` | object | Canonical config, settings, state, sessions, logs, automations, and secrets paths |
996 | `secret_backend` | object | Metadata-only file-store shape, or literal `unknown` / `not_probed` for system and unsupported backends |
997 | `workspace` | string | Default workspace directory |
998 | `legacy_state.primary_root` | string | Primary Codewhale state root inspected for known state paths |
999 | `legacy_state.legacy_root` | string | Legacy `.deepseek` state root inspected for known state paths |
1000 | `legacy_state.needs_attention` | bool | Whether known `~/.deepseek` state paths need review or the read-only session recovery diagnostic found missing destination filenames / could not complete |
1001 | `legacy_state.legacy_only_count` | number | Count of known state paths present only under the legacy root |
1002 | `legacy_state.dual_present_count` | number | Count of known state paths present under both primary and legacy roots |
1003 | `legacy_state.entries` | array | Per-path migration status: `{name, primary_present, legacy_present, status}` |
1004 | `legacy_state.session_recovery.status` | string | `isolated`, `no_legacy_sessions`, `migration_pending`, `migration_incomplete`, `migration_complete`, or `scan_failed` |
1005 | `legacy_state.session_recovery.read_only` | bool | Always true; doctor never invokes session migration or modifies either session directory |
1006 | `legacy_state.session_recovery.chat_contents_read` | bool | Always false; comparison is based only on top-level `.json` filenames and filesystem metadata |
1007 | `legacy_state.session_recovery.checkpoint_internals_scanned` | bool | Always false; `sessions/checkpoints/` and all other directories are skipped |
1008 | `legacy_state.session_recovery.recoverable_files` | array | Bounded sample of up to 100 missing destination filenames with source and destination paths; no chat payloads |
1009 | `legacy_state.session_recovery.recoverable_file_count` | number | Total missing destination filename count, including entries beyond the bounded sample |
1010 | `legacy_state.session_recovery.recoverable_files_truncated` | bool | Whether more than 100 recoverable filenames were found |
1011 | `legacy_state.session_recovery.recovery_command` | string or null | `codewhale sessions` when additive automatic recovery is available; null for isolated, complete, empty, or failed scans |
1012 | `api_key.source` | string | Structural source state: `config_declared`, `env_declared`, `external_auth_declared`, `secret_store_unprobed`, `secret_store_unavailable`, `oauth_unprobed`, `external_consent`, `none`, `local_runtime`, or `unknown`; declarations are not availability proof |
1013 | `api_key.availability` | string | Literal `present`, `not_required`, `not_probed`, `unavailable`, or `unknown`; only `present` and `not_required` certify structural Setup/Fleet credential readiness |
1014 | `base_url` | string | Provider URL authority only (`scheme://host[:explicit-port]`); userinfo, path, query, and fragment are omitted |
1015 | `default_text_model` | string | Default model |
1016 | `memory.enabled` | bool | Whether the memory feature is on, from `[memory]` in config or `CODEWHALE_MEMORY` |
1017 | `memory.path` | string | Path to memory file |
1018 | `memory.file_present` | bool | Whether memory file exists |
1019 | `mcp.config_path` | string | MCP config file path |
1020 | `mcp.present` | bool | Whether MCP config exists |
1021 | `mcp.probe_scope` | string | `configuration`; doctor does not start MCP servers |
1022 | `mcp.live_health_checked` | bool | Always false for doctor JSON |
1023 | `mcp.servers` | array | Per-server structural result and counts plus separate `checks`; URL userinfo/path/query/fragment and command argv, environment, header, and token values are never emitted, and all live stages are `not_checked` |
1024 | `skills.selected` | string | Resolved skills directory |
1025 | `skills.global.path` / `.present` / `.count` | — | Codewhale global skills dir (`~/.codewhale/skills`, with legacy `~/.deepseek/skills` support) |
1026 | `skills.agents.path` / `.present` / `.count` | — | Workspace `.agents/skills/` dir |
1027 | `skills.agents_global.path` / `.present` / `.count` | — | agentskills.io global skills dir (`~/.agents/skills`) |
1028 | `skills.local.path` / `.present` / `.count` | — | `skills/` dir |
1029 | `skills.opencode.path` / `.present` / `.count` | — | `.opencode/skills/` dir |
1030 | `skills.claude.path` / `.present` / `.count` | — | `.claude/skills/` dir |
1031 | `tools.path` / `.present` / `.count` | — | Global tools directory |
1032 | `plugins.path` / `.present` | — | Global plugins directory |
1033 | `plugins.bundles` | array | Discovered plugin bundles, one row each in the `codewhale plugins status --json` shape (`name`, `scope`, `state`, `trust`, `enabled`, `active`, …) |
1034 | `sandbox.available` | bool | Whether sandbox is supported on this OS |
1035 | `sandbox.kind` | string or null | Sandbox kind (e.g. `"macos_seatbelt"`) |
1036 | `storage.spillover.path` / `.present` / `.count` | — | Tool output spillover dir |
1037 | `storage.stash.path` / `.present` / `.count` | — | Composer stash |
1038
1039 ### Example
1040
1041 ```json
1042 {
1043 "version": "0.8.9",
1044 "config_path": "/Users/you/.codewhale/config.toml",
1045 "config_present": true,
1046 "workspace": "/Users/you/projects/codewhale-tui",
1047 "api_key": {
1048 "source": "secret_store_unprobed",
1049 "availability": "not_probed"
1050 },
1051 "base_url": "https://api.deepseek.com",
1052 "default_text_model": "deepseek-v4-pro",
1053 "memory": {
1054 "enabled": false,
1055 "path": "/Users/you/.codewhale/memory.md",
1056 "file_present": true
1057 },
1058 "mcp": {
1059 "config_path": "/Users/you/.codewhale/mcp.json",
1060 "present": true,
1061 "servers": [
1062 {"name": "filesystem", "enabled": true, "transport": "stdio", "args_count": 2, "env_count": 0, "status": "ok"}
1063 ]
1064 },
1065 "sandbox": {
1066 "available": true,
1067 "kind": "macos_seatbelt"
1068 }
1069 }
1070 ```
1071
1072 The mechanically checked [HTTP route inventory](RUNTIME_ROUTES.md) lists literal
1073 paths and methods registered by current source, including native-client routes
1074 whose payload contracts are specific to that client.
1075
1076 ## HTTP/SSE runtime API: `codewhale app-server --http`
1077
1078 ```bash
1079 codewhale app-server --http [--host 127.0.0.1] [--port 7878] [--workers 2] [--auth-token TOKEN] [--insecure-no-auth]
1080 codewhale app-server --mobile [--host 127.0.0.1] [--port 7878] [--auth-token TOKEN]
1081 codewhale app-server --mobile --host ::1 [--port 7878] [--insecure-no-auth]
1082 codewhale web [--port 7878]
1083
1084 # Compatibility aliases — identical server, serve flag names:
1085 codewhale serve --http [...] [--insecure]
1086 codewhale serve --mobile [...] [--insecure]
1087 ```
1088
1089 Defaults: host `127.0.0.1`, port `7878`, 2 workers (clamped 1–8).
1090
1091 A Unix supervisor may pass a listening TCP socket as descriptor 3 and set
1092 `CODEWHALE_RUNTIME_LISTEN_FD=3` for `serve --http` or `app-server --http`.
1093 The Engine captures ownership before config discovery or child execution,
1094 sets close-on-exec, and validates TCP/listening state, disabled port sharing,
1095 and the exact numeric loopback host and nonzero port requested on the CLI.
1096 Insecure unauthenticated mode is refused. Malformed, closed, non-listening,
1097 wrong-address or already-consumed descriptors fail startup; only an absent
1098 marker permits an ordinary bind. An inherited listener cannot attach to a live
1099 Runtime owner, while the existing authenticated dead-owner recovery remains.
1100
1101 The supervisor must retain its socket across normal Engine restarts and pass
1102 only the intended descriptor to the Engine. The Engine drops its descriptor on
1103 exit and never shuts down the supervisor's shared socket. Permanent shutdown
1104 must stop both the service and any socket-activation unit; stopping just the
1105 service can allow incoming traffic to reactivate it. This descriptor contract
1106 does not itself validate a supervisor's systemd PID or descriptor-count metadata.
1107
1108 The server binds to `localhost` by default. Configuration is via CLI flags —
1109 there is no `[app_server]` config section.
1110
1111 `/v1/*` routes require a bearer token unless `codewhale app-server` is started
1112 with `--insecure-no-auth` on a loopback bind such as `127.0.0.1`. Mobile mode
1113 is loopback-only: non-loopback hosts are rejected until Runtime has a TLS or
1114 verified-overlay transport boundary. The `codewhale serve` compatibility aliases
1115 use `--insecure` for the same loopback escape hatch.
1116 Set `CODEWHALE_RUNTIME_TOKEN=TOKEN` in the server's environment before starting
1117 it; `DEEPSEEK_RUNTIME_TOKEN` remains a compatibility alias. `--auth-token TOKEN`
1118 also works, but a command-line argument is visible to other local users in the
1119 process list, so do not use it in a service unit, a runbook or a shared
1120 terminal. If neither is set, the process generates a Runtime token for that process and does **not**
1121 print it. `/health`, `/v1/runtime/info`, and an enabled static client shell
1122 remain public; Runtime mutations and thread data stay behind `/v1/*`
1123 authentication. `/mobile` returns 404 when mobile mode is disabled and serves
1124 the unchanged static shell when it is enabled.
1125
1126 Authenticated clients can provide the token as `Authorization: Bearer TOKEN`,
1127 `X-Codewhale-Runtime-Token: TOKEN`, the legacy
1128 `X-DeepSeek-Runtime-Token: TOKEN`. Query-string and raw Runtime-token cookie
1129 authentication are not supported.
1130
1131 ### Local browser client
1132
1133 `codewhale web` starts the canonical Runtime API on `127.0.0.1`, serves
1134 dependency-free assets embedded in the binary, prints a single-use launch URL,
1135 and asks the operating system to open that URL in the default browser. If the
1136 browser does not open, the printed URL remains usable for ten minutes. The
1137 command cannot bind to a non-loopback host and cannot run with Runtime auth
1138 disabled.
1139
1140 By default the embedded client is served. Setting `CODEWHALE_WEB_DIST` to a
1141 built `apps/web` directory serves the shared app build instead; an invalid
1142 value is refused at startup with the reason. See
1143 [Serving the shared app build](WEB.md#serving-the-shared-app-build).
1144
1145 The browser-launch URL contains a random, short-lived, one-time bootstrap
1146 capability, never the Runtime token. A loopback request exchanges that
1147 capability for a
1148 `codewhale_web_session=…; HttpOnly; SameSite=Strict; Path=/` cookie backed by a
1149 single process-local server session that expires 12 hours after the server
1150 process starts, consumes the capability immediately, and redirects to `/`.
1151 Reused, expired, malformed, or
1152 non-loopback bootstrap attempts fail closed. The Runtime bearer token is not
1153 placed in rendered HTML, browser storage, logs, URL queries/fragments, or
1154 browser-launch arguments. The one-time bootstrap capability is printed in the
1155 local terminal and transits the OS browser launcher's argument list. A same-user
1156 process could race the browser to the exchange, which is why the capability is
1157 single-use, loopback-only, and expires after ten minutes — and why a same-user
1158 attacker has strictly easier local avenues than this race.
1159 Web fetches require the session cookie plus an origin-scoped request proof;
1160 streams use a fresh single-use ticket. The initial redirect carries the proof
1161 in a fragment, which the client removes and saves in origin-scoped
1162 `sessionStorage`, so a reload of that tab keeps working when the browser
1163 allows session storage. The server never puts
1164 the proof in a page: the session cookie is host-scoped, not port-scoped, so a
1165 listener on another loopback port can receive it, and the cookie alone must
1166 not be enough to recover the proof. A new tab opened by typing the address
1167 therefore has no proof; use the original tab, duplicate it, or restart
1168 `codewhale web` for a fresh one-time session. The page uses `no-store`,
1169 disallows framing, and grants no cross-origin read access. Nothing extends the
1170 server session or replaces an expired cookie.
1171 Cross-origin Fetch Metadata or a mismatched Origin is rejected on web API
1172 requests. Explicit bearer and Runtime-token header clients keep their existing
1173 behavior. Transient stream-ticket failures retry with capped backoff; HTTP
1174 401/403 stops ticket retries until a fresh session is opened.
1175
1176 The embedded client provides a responsive thread/search rail, Runtime-owned
1177 session facts, transcript and tool receipts, and a bottom composer. It can
1178 create, select, rename, and archive threads; choose a provider and model for a
1179 new thread without changing Runtime defaults; start or steer turns; interrupt
1180 work; resolve approvals; and answer Runtime user-input requests. Selection
1181 loads `GET /v1/threads/{id}` first, then opens the replayable event stream with
1182 `since_seq=latest_seq`; reconnection advances from the newest accepted sequence
1183 and drops duplicates or events from a stale selection. The thread detail
1184 snapshot includes `pending_approvals`, `pending_user_inputs`, and
1185 `pending_dynamic_tool_calls`; clients must hydrate those fields before
1186 subscribing so a reload cannot strand work whose request event is at or before
1187 `latest_seq`. Resolution is also published as `approval.decided`,
1188 `user_input.answered`, `user_input.canceled`, `tool_call.resolved`,
1189 `tool_call.canceled`, or `tool_call.timeout` for already-connected clients.
1190
1191 An existing thread's model, mode, permission posture, workspace, and branch are
1192 display-only in this client. Files/Changes, PTY/terminal, preview, artifacts,
1193 provider login or global-default switching, Fleet creation, and
1194 undo/retry/restore controls are not built into this page. The native desktop
1195 client covers them through the workspace-file, turn-artifact, terminal and
1196 workspace-restore routes documented here.
1197
1198 ### Mobile control page
1199
1200 `codewhale serve --mobile` starts the same HTTP/SSE runtime API and serves a
1201 phone-friendly control page at `/mobile`. It binds only to loopback
1202 (`127.0.0.1` or `::1`); a non-loopback host is rejected because this Runtime
1203 surface does not yet provide TLS or a verified overlay transport. The static
1204 HTML page contains no Runtime bearer and is not itself token-gated. When
1205 Runtime auth is enabled, the CLI prints a short-lived, single-use loopback
1206 bootstrap URL. That capability creates a 30-minute, process-local
1207 `Max-Age=1800; HttpOnly; SameSite=Strict` mobile session cookie plus origin-scoped browser
1208 proofs. A sibling port that receives the host-scoped cookie cannot use it by
1209 itself. The page can also exchange an explicitly entered bearer once, then
1210 clears it rather than storing it in browser storage or a cookie. EventSource
1211 connections use separate short-lived, single-use stream tickets.
1212
1213 The mobile page can list/create threads, send prompts, follow live SSE events,
1214 steer or interrupt an active turn, and resolve normal tool approvals through
1215 `POST /v1/approvals/{approval_id}`. It is a local-only convenience surface;
1216 do not expose it directly to another device or public network until Runtime has
1217 a TLS or verified transport boundary.
1218
1219 #### Remote pairing grants (DSH remote service)
1220
1221 Plugins granted the `remote` host service can request conversation-scoped
1222 pairings via Engine `dsh_remote`. Runtime exposes host management and loopback
1223 redemption over existing HTTP/SSE transport (no separate listener or WebSocket):
1224
1225 - `GET /v1/dsh/remote/pairings` — requires the master `Authorization: Bearer`
1226 header (never mobile/web cookies or device Watch/Drive tokens; returns `409`
1227 if auth is off). Returns a JSON array with `grant`, `plugin_id`,
1228 `plugin_name` (from the reviewed record), `session_id`, `state`
1229 (`"awaiting_host"` or `"paired"`), `plugin_label`, `client_label`, and
1230 `expires_in_seconds`. No pairing secret or client token is ever included.
1231 - `POST /v1/dsh/remote/pairings/{grant}/present` — master bearer only. Mints
1232 and returns `{ "grant", "url", "expires_in_seconds" }` (`Cache-Control: no-store`)
1233 where `url` is `http://<bind>/__codewhale/mobile/pair/<secret>`. Calling this
1234 again replaces and invalidates the prior link; callers must only invoke it on
1235 explicit human action, never by polling. Returns `404` with no detail when
1236 unknown or already paired, and `409 Conflict` without minting a secret when
1237 mobile control is off or `session_id` is not an active Runtime HTTP thread
1238 (for example a terminal session or archived thread).
1239 - `DELETE /v1/dsh/remote/pairings/{grant}` — master bearer only. Ends a waiting
1240 pairing or paired device session, returning `204 No Content` identically for
1241 known and unknown grants.
1242 - `GET /__codewhale/mobile/pair/{secret}` — unauthenticated single-use loopback
1243 redemption (`403` for non-loopback peers ignoring `X-Forwarded-For`; uniform
1244 `401` fixed text for unknown, expired, replayed, withdrawn, or malformed
1245 links). Issues a grant-backed mobile session (`HttpOnly; SameSite=Strict`
1246 cookie clamped to the grant TTL plus origin-bound fragment proof and stream
1247 ticket) without ever exposing the Engine client token or pairing secret in
1248 cookies, fragments, URLs, response bodies, or logs.
1249
1250 Grant-backed mobile sessions are validated against the Engine on every HTTP
1251 request and every SSE stream ticket, drop immediately (`401`) if withdrawn,
1252 revoked, expired, or if the bound conversation is archived/deleted (and terminate
1253 any already-open `GET /v1/threads/{id}/events` SSE stream cleanly with
1254 `stream.end { "reason": "remote_access_revoked", "retryable": false }` without
1255 delivering post-revocation events), and are strictly restricted to reading and
1256 sending/steering/interrupting turns in their single bound conversation
1257 (`GET /v1/threads` and `GET /v1/threads/summary` are filtered to that thread,
1258 `GET /v1/threads/{id}`, `GET /v1/threads/{id}/events`,
1259 `POST /v1/threads/{id}/turns`, `/steer`, `/interrupt`, and
1260 `POST /__codewhale/mobile/stream-ticket`). On `POST /v1/threads/{id}/turns`,
1261 paired device sessions cannot override `mode`, `permission_posture`,
1262 `allowed_tools`, `dynamic_tools`, `model`, `model_provider`,
1263 `model_provider_id`, `account_model_owner`, `profile_constitution`,
1264 `reasoning_effort`, `max_output_tokens`, or `environment_id` (`403 Forbidden`),
1265 nor pass `true` for `allow_shell`, `trust_mode`, or `auto_approve` (`403`);
1266 explicit `false` values on those three boolean flags are normalized to `None`
1267 so the conversation's existing posture is preserved. Foreign threads, thread
1268 creation, settings/secrets/terminals/files, pairing routes, and approval routes
1269 (`POST /v1/approvals/{approval_id}`) return `403 Forbidden`: approval cards are
1270 answered on the computer only.
1271
1272 When UI clients render `plugin_label` or `client_label`, they MUST present them
1273 as quoted third-party text inside a directional isolate (such as `<bdi>`) beside
1274 `plugin_name`, and never as a heading or host-authored prose.
1275
1276 ### Endpoints
1277
1278 **Health**
1279 - `GET /health`
1280
1281 **Sessions** (durable session manager)
1282 - `GET /v1/sessions?limit=50&search=<fuzzy>&include_archived=false&archived_only=false&workspace=<path>&sort=recent|name|size`
1283 - `GET /v1/sessions/summary?…` (same query params; projected row shape)
1284 - `GET /v1/sessions/{id}` (add `?peek=true&entries=12` for a bounded, redacted
1285 read-only peek instead of the full transcript). The full response carries
1286 `turn_outcomes` when a turn ended `Failed`: `{ status, error, ended_at,
1287 after_message_count }` per failure, oldest first, bounded to 64, with the
1288 error text the transcript showed and secrets redacted
1289 - `PATCH /v1/sessions/{id}` (`{ "title"?: string, "archived"?: bool }`)
1290 - `DELETE /v1/sessions/{id}`
1291 - `POST /v1/sessions/{id}/resume-thread` returns the open thread that already
1292 holds the whole saved session (`200`), or seeds a new thread from it (`201`)
1293 when none does, including when the session grew after that thread opened it.
1294 Without a `mode` in the body, a new thread takes the saved mode; a saved mode
1295 that is not a Runtime mode, such as `exec`, resumes as `agent`. The new
1296 thread's tool results are stored masked as live receipts are: a
1297 `request_user_input` answer becomes `User input submitted` and configured
1298 credentials are redacted. `GET /v1/sessions/{id}` still returns them unmasked.
1299 - `GET /v1/sessions/{id}/artifacts` and `GET /v1/sessions/{id}/artifacts/{artifact_id}?offset=&limit=`
1300 (see workspace files and session artifacts above; runtime-turn spills are
1301 read through `GET /v1/threads/{id}/turns/{turn_id}/artifacts/{artifact_id}`)
1302 - `POST /v1/sessions` (`{ "thread_id": string, "title"?: string }`) exports a
1303 thread as a saved session. It is idempotent: it writes only the document
1304 whose id is derived from the thread, creating it the first time (`201`) and
1305 updating it after (`200`), so a retry never makes a duplicate. A session the
1306 thread was resumed from is left unchanged.
1307 - `PUT /v1/sessions` (`{ "thread_id"?: string, "session_id"?: string }`) saves
1308 a thread's live conversation. Naming a `session_id` that another thread is
1309 bound to returns `409 Conflict`.
1310 - `GET /v1/sessions/repair` returns the last session-store repair summary, or
1311 `null` if none has run
1312
1313 Sessions and threads answer the same `include_archived` / `archived_only` pair
1314 with the same meaning, and `search` is the same fuzzy match (title, id,
1315 workspace — substring, then subsequence) the TUI session picker and the workbar
1316 Sessions list use. All three surfaces run one projection
1317 (`crates/engine/src/session_projection.rs`), so a listing cannot differ between
1318 the terminal and the dashboard.
1319
1320 `GET /v1/sessions/summary` returns rows that are field-compatible with
1321 `GET /v1/threads/summary` — `id`, `title`, `preview`, `model`, `mode`,
1322 `workspace`, `archived`, `updated_at` — plus `message_count`, `total_tokens`,
1323 `created_at`, `parent_session_id`, and `is_current`. One caveat stated plainly:
1324 `preview` is the session's recorded **title**, not its last message. Session
1325 metadata does not store a last message, and reading every transcript to
1326 synthesise one would make a list view an unbounded read. Full transcript
1327 preview lives in the TUI session picker, which reads one selected session.
1328
1329 Metadata inspection reads at most 16 MiB from each regular session file. A
1330 resource refusal returns `413` with code `session_metadata_too_large` from
1331 catalog and lifecycle routes; the source remains unchanged. A catalog with
1332 unreadable records returns an error rather than an incomplete successful list.
1333 The terminal picker retains readable rows and reports its inspection warning.
1334 These limits cover metadata inspection, not full transcript loading.
1335
1336 Saved-document and checkpoint publication uses a native source captured before
1337 snapshot preparation or queueing. Both physical records must still match under
1338 the existing session write admission before archival, pruning, replacement or
1339 checkpoint consumption. A mismatch refuses and retains recovery. Optional
1340 serialized `publication_id` metadata identifies a generation; it does not grant
1341 write authority. An unknown checkpoint needs explicit held resume/attach/promotion
1342 before automatic completion can consume it. Runtime prefix-restore validation
1343 remains distinct from the full-document predicate required for a later write.
1344 Optional usage-store damage remains visible as incomplete coverage while valid
1345 recovery data can be read without a publication receipt. Known retirement and
1346 changed raw records still refuse; this read result cannot authorize a save.
1347
1348 `PATCH /v1/sessions/{id}` renames and/or archives a saved session and returns a
1349 lifecycle receipt shaped like the thread patch receipt:
1350
1351 ```json
1352 {
1353 "session": { "id": "…", "title": "Renamed", "archived": true, "…": "…" },
1354 "changes": { "title": "Renamed", "archived": true }
1355 }
1356 ```
1357
1358 `changes` lists only what actually moved, so a no-op patch is distinguishable
1359 from an applied one. Archiving is durable and reversible: an archived session
1360 stays on disk and stays loadable, disappears from default listings, and is
1361 never chosen by `--continue` or by auto-resume. The route is the same writer
1362 the TUI picker (`e`) and `/sessions archive <id>` use — there is no second
1363 archive notion.
1364
1365 While a session is open in an interactive Codewhale process, that process holds
1366 the authoritative copy in memory and rewrites the whole document on its next
1367 autosave. `PATCH`, `PUT` and `DELETE` therefore fail closed on it with
1368 `409 Conflict` rather than writing something that would be silently reverted.
1369 Change it in the terminal instead. The open process holds a lock on the
1370 session (`sessions/.late-usage/<id>.live`), so this holds whether the request
1371 reaches the API inside that process or a separate `codewhale serve`.
1372
1373 The session store is repaired in the background at each launch and each
1374 `codewhale serve` start. The repair gives a "Recovered:" session to each thread
1375 in a Runtime store that no session is bound to. It unbinds threads whose session
1376 document is gone; they then load from their own turns. It moves unreadable
1377 documents, empty unbound stores, and old artifact directories that no session
1378 names to `sessions/.set-aside/<run>/`, and writes a `MANIFEST.jsonl` there.
1379 Nothing is deleted. `GET /v1/sessions/repair` and `codewhale doctor` report the
1380 last run; `codewhale doctor --repair-sessions [--dry-run]` runs one on demand.
1381
1382 `GET /v1/sessions/{id}?peek=true` returns a bounded, redacted, read-only view
1383 instead of the transcript: 12 entries by default, of at most 400 characters
1384 each (`&entries=N` asks for fewer or for up to 100), tool calls and
1385 results summarised to a name and a size rather than inlined, and
1386 credential-shaped substrings masked. `omitted_before` reports how many earlier
1387 messages were dropped. The payload carries `"live": false` and deliberately has
1388 no turn status, `running`, or `active` field — a saved session is a recording,
1389 and live state comes only from a resumed thread's SSE stream.
1390
1391 **Threads** (durable runtime data model)
1392 - `GET /v1/threads?limit=50&include_archived=false&archived_only=false`
1393 - `GET /v1/threads/summary?limit=50&search=<optional>&include_archived=false&archived_only=false&thread_ids=<id>,<id>`
1394 - `GET /v1/threads/running`
1395 - `GET /v1/goals?limit=50&cursor=<opaque>&status=<status>` — read-only index of
1396 the per-thread goal records across threads, newest update first. Returns
1397 `{"goals": [ThreadGoal...], "next_cursor": "<opaque>"}`; `next_cursor` is
1398 absent on the last page. `limit` is 1-200 (default 50); `status` is one of
1399 `active`, `paused`, `blocked`, `usage_limited`, `budget_limited`, `complete`;
1400 goals whose thread no longer exists are omitted; a bad `status` or `cursor`, or a cursor issued under a different `status`, is `400`. Same auth as every other `/v1` read.
1401 Goal creation, completion and removal stay on `/v1/threads/{id}/goal`.
1402 - `GET /v1/threads/{id}/notices`
1403 - `DELETE /v1/threads/{id}/notices/{notice_id}`
1404 - `POST /v1/threads`
1405 - `GET /v1/threads/{id}`
1406 - `PATCH /v1/threads/{id}` (see body shape below)
1407 - `POST /v1/threads/{id}/resume`
1408 - `DELETE /v1/threads/{id}` — removes the thread with its turns, items,
1409 events, goal and approval grants, and stops its cached engine. A thread
1410 with a running turn, or one that an active automation or a pending
1411 trigger delivers into, answers `409` naming them. The saved session bound to it is
1412 deleted too unless another thread is bound to the same session or an open
1413 terminal holds it; the answer
1414 `{deleted, session_id?, session_deleted, session_kept?, session_error?}`
1415 says which. Tasks, automations and child threads that name it keep the
1416 stale id.
1417 - `POST /v1/threads/{id}/fork` (`POST /v1/threads` also accepts
1418 `parent_thread_id` naming an existing thread)
1419 - `POST /v1/threads/{id}/read` — record the newest item a client has shown
1420 (body `{"item_id": "<item id>"}`; see "Read markers" below)
1421 - `GET /v1/threads/{id}/receipt` — what the thread did, one entry per action
1422 (read-only; shape in [RECEIPTS.md](RECEIPTS.md))
1423 - `GET /v1/threads/{id}/turns/{turn_id}/receipt` — the same, for one turn;
1424 `404` for an unknown thread or a turn that is not this thread's
1425
1426 `thread_ids` is a comma-separated list of up to 200 IDs (each at most 128 bytes).
1427 The route filters exact IDs before applying `limit`, preserving newest-first
1428 order. This is a selection filter, not an ownership or authorization check;
1429 the Runtime bearer token remains the access boundary.
1430
1431 `POST /v1/threads` accepts optional execution defaults in addition to the
1432 provider, model, workspace, and permission fields:
1433
1434 ```json
1435 {
1436 "model_provider": "openai-codex",
1437 "model": "gpt-5.6",
1438 "reasoning_effort": "high",
1439 "allowed_tools": ["read_file", "search"],
1440 "disallowed_tools": ["shell"]
1441 }
1442 ```
1443
1444 `reasoning_effort` uses the canonical Runtime vocabulary (`auto`, `off`,
1445 `low`, `medium`, `high`, `xhigh`, `ultra`, or `max`; documented compatibility
1446 aliases are accepted and persisted canonically). `allowed_tools` is a
1447 model-visible allowlist. Omitting it keeps the normal configured catalog; an
1448 explicit empty array (`"allowed_tools": []`) exposes no tools to the model.
1449 `disallowed_tools` (also accepted as `disallowedTools`) attaches persistent
1450 tool deny rules to the thread (omitted from stored records when empty); denied
1451 tools remain blocked even if listed in `allowed_tools`, and non-empty rules
1452 participate in creation idempotency fingerprints. These fields are additive:
1453 older thread records and clients that omit them retain their previous behavior.
1454
1455 When `GET /v1/runtime/info` advertises
1456 `capabilities.exact_route_thread_create: true`, clients can send the model
1457 list's `route.selection` object (`route_id` and `binding_id`) as
1458 `route_selection` on thread creation. Send the selected `model_provider`,
1459 exact wire `model` and `model_provider_id` when the list supplies one.
1460 Missing or malformed required fields return HTTP 400. If the selected route
1461 has changed or is unavailable,
1462 the server returns HTTP 409 with `error.code: "route_selection_stale"` before
1463 creating a thread or emitting `thread.started`. Refresh the model list and
1464 ask the user to reselect. The selection participates in the creation
1465 fingerprint when using `operation_key`. A matching committed retry still
1466 returns the original thread if the route has since changed.
1467
1468 ### Sessions on other agents (external agent threads)
1469
1470 For installation, sign-in and a runnable example, see
1471 [Run other agents in Codewhale](OTHER_AGENTS.md).
1472
1473 `POST /v1/threads` with `executor` runs the thread's turns on an agent CLI
1474 already installed and signed in on this computer, over Agent Client Protocol,
1475 instead of Codewhale's own agent:
1476
1477 ```json
1478 {
1479 "workspace": "/Users/you/projects/app",
1480 "permission_posture": "ask",
1481 "executor": { "kind": "acp", "agent_id": "opencode", "config": { "model": "<the agent's own option value>" } }
1482 }
1483 ```
1484
1485 `agent_id` is an `id` from `GET /v1/agents/external` whose row says
1486 `runnable: true`; `kind` is always `acp`; `config.model` is optional and is the
1487 agent's own config value, never a Codewhale provider route. When the agent cannot be driven the
1488 request is refused with a sentence and a stable `error.code`:
1489 `unknown_agent`, `not_installed`, `adapter_missing`, `below_min_version` or
1490 `no_acp` (`424`), and `needs_sign_in` (`409`) when the agent refuses to start a
1491 session because the person is not signed in to it. Turn starts and `resume`
1492 use the same codes. Codewhale never
1493 downloads an agent or adapter.
1494
1495 The thread record carries the executor; native threads have none:
1496
1497 ```json
1498 "executor": { "version": 1, "kind": "acp", "agent_id": "opencode",
1499 "agent_name": "OpenCode", "agent_version": "1.15.10", "protocol_version": 1,
1500 "foreign_session_id": "ses_…", "model": null }
1501 ```
1502
1503 `agent_name`, `agent_version`, `protocol_version` and `foreign_session_id` are
1504 filled when the agent first starts (the first turn, or `POST
1505 /v1/threads/{id}/resume`). The record never holds an environment value, token
1506 or credential: the agent uses its own login. `model_provider` is absent and
1507 `model` is the agent's model value or name.
1508
1509 Everything else is the ordinary thread API, and the Engine's records stay the
1510 one authority. `POST .../turns` sends the prompt as one `session/prompt`; the
1511 agent's updates become the usual `turn.started`, `item.started`,
1512 `item.delta` (`kind` `agent_message` or `agent_reasoning`), `item.completed`
1513 / `item.failed` and `turn.completed` events. Item kinds: `agent_message_chunk`
1514 → `agent_message`, `agent_thought_chunk` → `agent_reasoning`, tool calls of
1515 kind `execute` → `command_execution`, `edit`/`delete`/`move` →
1516 `file_change`, `switch_mode` → `status`, any other → `tool_call`, and a plan
1517 → one `status` item. Tool items carry `metadata.external_agent` with the
1518 agent's `tool_call_id`, `kind` and `locations`. Everything the agent sends is
1519 bounded (8 MiB per message, 256 KiB per item, 512 tool items per turn,
1520 control characters removed) and ignored when it names another session.
1521
1522 The agent's `session/request_permission` becomes an ordinary
1523 `approval.required` (with `external_agent`, `options` and `locations`) and is
1524 answered through `POST /v1/approvals/{id}`. The answer is recorded in
1525 `approval.decided` before the agent hears it. The thread's dial decides
1526 what is asked:
1527
1528 | Dial (`permission_posture` / `mode`) | Answer to `session/request_permission` |
1529 | --- | --- |
1530 | `ask` | always an approval card |
1531 | `accept_edits` | `allow_once` without asking for an `edit`, `delete` or `move` whose every location resolves inside the workspace or an added folder; an approval card otherwise |
1532 | `auto_review` | an approval card (no model review exists for another agent) |
1533 | `full_access` | `allow_once` (or `allow_always` if that is all it offers) without asking |
1534 | `plan` (mode) | `reject_once` without asking, whatever the posture |
1535
1536 A card's Allow selects `allow_once` (`allow_always` when `remember` is set and
1537 offered); Deny selects `reject_once` (`reject_always` when `remember`); an
1538 answer the agent offered no option for, a withdrawn card and a stopped turn
1539 answer `cancelled`. Automatic answers are recorded with `auto: true` and
1540 `decided_by: "policy"`. Codewhale sees only what the agent routes through
1541 ACP: its own tools are not sandboxed by Codewhale.
1542
1543 `POST .../interrupt` sends `session/cancel`, withdraws pending approvals as
1544 cancelled and, if the agent has not stopped after 10 s, ends its process; the
1545 turn is `interrupted`. A stop reason other than `end_turn` or `cancelled`
1546 fails the turn with it. After a restart, the next turn or resume reopens the
1547 same agent session with `session/resume` or `session/load` (whose replay is
1548 not re-recorded); an agent that supports neither says so instead of starting
1549 a new session. `steer`, `compact`, `fork`, images, dynamic tools and a
1550 per-turn provider, model, reasoning setting, output allowance or tool allowlist
1551 are refused on an external thread. Thread creation uses only
1552 `executor.config.model` for the agent's model; Codewhale provider settings,
1553 tool allowlists and system prompts are refused. `PATCH` cannot change its
1554 model, provider, system prompt or workspace. Usage is what the agent itself reports, labelled
1555 `agent reported`; cost is `unknown` because the agent bills through its own
1556 account.
1557
1558 Three thread events describe the agent process itself: `executor.started`
1559 (`agent_id`, `agent_name`, `agent_version`, `protocol_version`,
1560 `foreign_session_id`, `reopened`) when the agent starts or is reopened,
1561 `executor.stopped` (`reason`) when it exits or is stopped between turns, and
1562 `turn.agent_usage` (`used`, `size`: the agent's own context-window token
1563 figures, `source: "agent reported"`, `cost: "unknown"`) whenever the agent
1564 sends ACP `usage_update`. `turn.completed` carries `turn.error` with the
1565 reason a turn failed or was ended. Stopping an idle agent process is the
1566 Engine call `stop_external_agent`; no HTTP route exposes it yet.
1567
1568 Two shapes are reserved and refused today with `error.code`
1569 `executor_not_supported` or `environment_not_supported` (`424`), so a record
1570 written by a later build never runs here by mistake: `executor.kind:
1571 "engine"` (a child session run by another environment's own Engine), and
1572 `environment: {"id", "provider_kind"}` on `POST /v1/threads` and on the
1573 session record (absent means this computer; the names follow
1574 `codewhale_protocol::placement`). Summary rows carry `environment` when set.
1575
1576 `CODEWHALE_ACP_FIXTURE_AGENT=<absolute path to a Node ACP script>` in the
1577 Engine's environment adds a `fixture` agent for end-to-end proofs.
1578
1579 `GET /v1/threads/summary` is the read-only summary surface used by the VS Code
1580 Agent View. `search` matches thread `id`, `title`, and `model` (and, when the
1581 title is unset, the latest turn's input summary — the displayed title). It
1582 does not scan turn or item bodies: `preview` is filled only after a match, so
1583 a dashboard keystroke is not a whole-store read per thread. Each item includes
1584 `id`, `title`, `preview`, `model`, `mode`, `archived`, `updated_at`,
1585 `latest_turn_id`, `latest_turn_status`, `parent_thread_id` when the thread
1586 was forked from another (absent on threads forked before the field existed),
1587 and optional `last_prompt_at` with the RFC 3339 timestamp of the latest
1588 recorded user prompt or accepted steer. The bounded lookup skips turns
1589 without indexed message items and omits the field when it cannot establish a
1590 prompt time. Imported transcript timestamps, automatic inputs, and dropped
1591 steers do not count. A thread created for a
1592 verified automation task has `origin: {"kind": "automation"}`. Running an
1593 automation in an existing thread preserves its origin. Forks and records
1594 without persisted creation provenance omit `origin`. Workspace metadata is
1595 included alongside these fields:
1596
1597 ```json
1598 {
1599 "id": "thread_...",
1600 "title": "Implement MCP status count",
1601 "preview": "The TUI footer should count project MCP servers...",
1602 "model": "deepseek-v4-pro",
1603 "mode": "agent",
1604 "agent_preset": "standard",
1605 "branch": "feature/runtime-api",
1606 "head": "abc1234",
1607 "dirty": false,
1608 "workspace": "/Users/you/projects/codewhale",
1609 "archived": false,
1610 "updated_at": "2026-06-06T05:43:00Z",
1611 "latest_turn_id": "turn_...",
1612 "latest_turn_status": "completed"
1613 }
1614 ```
1615
1616 A conversation run by an external agent also carries
1617 `executor: {"kind": "acp", "agent_id": "opencode", "agent_name": "OpenCode"}`,
1618 so a sidebar can label and group rows by agent; native rows omit it.
1619
1620 Rows also carry `last_read_item_id` and `unread` from the thread's read marker
1621 (see "Read markers" below). Both are `null` for a thread no client has marked
1622 read.
1623
1624 `branch` is resolved from the thread workspace at request time and may be
1625 `null` when the workspace is not a Git repository or the branch cannot be read.
1626 `head` is the current short Git commit for that workspace when available.
1627 `dirty` is true when the workspace has staged, unstaged, or untracked changes.
1628 `workspace` is included so editor clients can show when an agent lane is working
1629 outside the current VS Code folder.
1630
1631 Thread forks are sibling runtime threads, not an in-place tree projection.
1632 `thread.forked` events include `source_thread_id`; internal backtrack-aware
1633 forks may also include `backtrack_depth_from_tail` and `dropped_turn_id`, and
1634 a fork anchored to a named turn (`/fork-at-turn`) reports them with the depth
1635 resolved from that turn, and names the first user turn it dropped (not the
1636 anchor, which a named-turn fork keeps, and not a prompt-less turn such as a
1637 manual compaction that sits between them).
1638 Thread list and summary responses remain flat (with `child_count` on each
1639 summary row). When `thread_graph` is `true` in `GET /v1/runtime/info`, call
1640 `GET /v1/threads/{id}/graph` (optional `?limit=1..256`, default `256`) to fetch
1641 the bounded, authenticated thread graph `{root_thread_id, nodes, edges, truncated}`
1642 with node kinds (`conversation | fork | fleet_coordinator | fleet_worker | subagent | unknown`)
1643 and recorded edge kinds (`fork | spawned | coordinates | resumed_from | unknown`).
1644 Legacy records without recorded origin or edge kind report `"unknown"`.
1645
1646 ### Conversation modes
1647
1648 `GET /v1/modes` lists the conversation modes a client can offer when it starts
1649 a conversation:
1650
1651 ```json
1652 {
1653 "default": "standard",
1654 "modes": [
1655 {"id": "standard", "name": "Standard", "description": "The everyday Codewhale agent with its normal tools and skills.", "source": "builtin", "available": true},
1656 {"id": "creator", "name": "Creator", "description": "Build, inspect and test Codewhale plugins in this conversation, with the plugin authoring tools and guides loaded.", "source": "builtin", "available": true}
1657 ]
1658 }
1659 ```
1660
1661 `reason` appears only when `available` is `false` (for example, when `[features] plugin_creator` is disabled or no supported Node.js or Bun plugin runtime is found); a client lists the row
1662 disabled and shows it. A thread's mode is its `agent_preset` string. Set it on
1663 `POST /v1/threads`, or with `PATCH /v1/threads/{id}` while the thread has no
1664 turn. A thread record with no `agent_preset` is `standard`, and the thread
1665 record omits the field for `standard`; rows from `GET /v1/threads/summary`
1666 always carry it. This field stores and reports the mode; what a mode loads is
1667 not part of it.
1668
1669 Refusals carry `error.code`:
1670
1671 | `error.code` | Status | Meaning |
1672 | --- | --- | --- |
1673 | `unknown_mode` | `400` | The id is not in `GET /v1/modes`. Never replaced by `standard`. |
1674 | `mode_unavailable` | `424` | The row is listed with `available: false`; the message is its `reason`. |
1675 | `mode_locked` | `409` | The thread already has a turn, so its mode cannot change. |
1676 | `mode_not_supported_with_executor` | `400` | `agent_preset` with `executor` (another vendor's agent). |
1677
1678 ### Read markers
1679
1680 `POST /v1/threads/{id}/read` with `{"item_id": "<item id>"}` records that a
1681 client has shown the conversation through that item, in the order
1682 `GET /v1/threads/{id}` returns items (turn order, then item start time). A
1683 client sends the id of the newest item it rendered when the person opens or
1684 reads the conversation. The item must belong to the thread: an unknown thread
1685 is `404`, and an unknown item or one from another thread is `400`. The
1686 response is the thread record. Its `last_read` holds `item_id`, `last_in_turn`
1687 (that item was the last item of its turn when it was marked) and
1688 `watermark_item_id` (the last item that turn had recorded at that moment).
1689
1690 Marking read changes nothing else: `updated_at`, list order and the thread's
1691 event stream are untouched, so opening a conversation never moves it to the
1692 top of a list or makes it unread again. The marker only moves forward:
1693 marking an item that comes before the current one leaves the marker as it is,
1694 so a window showing an older snapshot cannot make a read conversation unread.
1695 Forks start without a marker.
1696
1697 `GET /v1/threads/summary` derives `unread` from the marker: `false` while the
1698 marked item is still the newest, `true` once any later item exists, and `null`
1699 when the thread was never marked (older Runtimes had no marker, so existing
1700 conversations are not all reported unread after an upgrade; clients keep their
1701 own fallback for those). `last_read_item_id` is the item to place a "new"
1702 divider after. Known limits: `unread` follows the items each turn records
1703 while it runs, so a turn that has started but not yet recorded an item does not
1704 count until it does, and a notice added to a turn after it finished (such as a
1705 permissions change) does not count.
1706
1707 `GET /v1/threads/running` is the running-work accounting surface
1708 (#6180): threads with at least one queued or in-progress turn or one running
1709 owner-held job, each with `thread_id`, `model`, `title`, `active_turns`
1710 (`turn_id` + `status`), `active_jobs` (`job_id`, `background`,
1711 `last_progress_at`, and the hold fields above when held), and
1712 `last_progress_at`: the newest event or job output this process has seen on
1713 the thread, absent when it has seen neither since it started. A thread with
1714 only held jobs has an empty `active_turns`.
1715 Background-capable clients use it for quit/background decisions — one call,
1716 no inference from latest-turn status. Archive state is ignored (archiving
1717 has no quiescence gate); an empty array means no owned work is live.
1718
1719 `GET /v1/threads/{id}/notices` is the per-thread active-notice surface
1720 (#6180): the TUI-visible conditions a watch-only client must surface —
1721 `subagent-terminal` (a child settled), `elevation-needed` (a tool call is
1722 blocked on elevation), `model-notify` (the model asked the user to come
1723 back) — each with `turn_id` and a `subject` id for targeting. Notices are
1724 in-memory session state, bounded to 32 per thread (oldest evicted), and
1725 never persisted. Clearing: elevation auto-clears when its tool call
1726 completes; terminal/notify clear on `DELETE .../notices/{notice_id}`
1727 (204, unknown ids 404). Unknown threads 404 on both endpoints.
1728
1729 `archived_only=true` returns archived threads only (mutually overrides
1730 `include_archived`). Default behavior is unchanged: `include_archived=false`
1731 and `archived_only=false` returns active threads (#563).
1732
1733 `PATCH /v1/threads/{id}` body — every field is optional, missing means
1734 "no change". At least one field must be present. `title` and `system_prompt`
1735 accept an empty string to clear a previously-set value (#562):
1736
1737 ```json
1738 {
1739 "archived": true,
1740 "allow_shell": false,
1741 "trust_mode": false,
1742 "auto_approve": false,
1743 "model": "deepseek-v4-pro",
1744 "mode": "agent",
1745 "title": "User-set thread title",
1746 "system_prompt": "You are a useful assistant.",
1747 "model_provider": "custom",
1748 "model_provider_id": "lm-studio"
1749 }
1750 ```
1751
1752 A `system_prompt` change applies from the next turn: a loaded engine is
1753 unloaded and rebuilt from the thread's history with the new prompt. Like a
1754 `workspace` change, it is refused while the thread has a running turn.
1755
1756 `model_provider` and `model` switch the provider and model the thread's future turns use (capability `thread_model_hotswitch`). `model_provider` takes a built-in kind (`deepseek`, `xai`, ...) or a configured route name, as `/provider` does. `model_provider_id` names one exact `[providers.<id>]` table and wins over a route name. Both provider switches and bare `{model}` updates resolve and client-preflight the target route before anything is saved, so an invalid model or unready provider is refused and nothing changes. Without `model`, a provider switch takes the new provider's default model; an `auto` thread stays `auto`. The loaded engine and conversation history are kept, and the next turn installs the new route and recomputes the context window. When requested while a turn is active, the switch is deferred to the next turn boundary rather than mutating the running turn; at the boundary it saves the updated route, adds a completed `status` item to the latest turn, and publishes a `thread.model_changed` event (`from`, `to`, `source`).
1757
1758 A change of effective permission adds a completed `status` item to the thread's
1759 latest turn and publishes a `thread.permissions_changed` event (`from`, `to`,
1760 `source`).
1761
1762 When a running turn installs, enables, disables, or removes a plugin, the
1763 engine awaits plugin-host activation/teardown (for code plugins), refreshes
1764 the turn's plugin tool catalog immediately for the next model request without
1765 restarting the thread, adds a completed `status` item to that turn, and publishes
1766 a `thread.plugin_changed` event (`plugin`, `action`, `content_hash`,
1767 `decided_by`, `services`, `tools_added`, `tools_removed`).
1768
1769 **Turns** (within a thread)
1770 - `POST /v1/threads/{id}/turns`
1771 - `POST /v1/threads/{id}/turns/{turn_id}/steer` - inject guidance into the running turn. The response is a receipt for what actually happened, not for what was attempted; see [Steer delivery](#steer-delivery).
1772 - `POST /v1/threads/{id}/turns/{turn_id}/interrupt`
1773 - `GET /v1/threads/{id}/turns/{turn_id}/artifacts` - what the turn produced: typed references plus the workspace-delta state. See [Turn artifacts](#turn-artifacts).
1774 - `GET /v1/threads/{id}/turns/{turn_id}/artifacts/{artifact_id}?offset=&limit=&revision=` - read one reference from the workspace, the post-turn snapshot, or the session artifact directory.
1775 - `POST /v1/threads/{id}/compact` (manual compaction)
1776 - `POST /v1/threads/{id}/undo` - fork the thread with the last N turns removed (`{"depth": N}`, default 0 = last turn only); returns the forked thread plus `original_user_text` so a GUI can pre-populate the input box. `{"turn_id": "turn_…"}` instead names the user turn to remove, together with every turn after it, and wins over `depth`; the Runtime resolves it under the thread's restore guard, so a turn another client appends meanwhile cannot move the cut. `400` when the turn is not a user turn of that thread
1777 - `POST /v1/threads/{id}/fork-at-turn` - fork at one named user turn (`{"turn_id": "turn_…"}`, as `GET /v1/threads/{id}` reports it). The fork *keeps* that turn and every turn before it, and drops the turns after it; naming the last turn therefore keeps the whole conversation. The receipt is `/undo`'s (`thread`, `original_user_text`, `original_user_images`), carrying the *first dropped* user turn's prompt — what was asked next, even when a prompt-less turn such as a manual `/compact` sits between — so a client can put it back in the composer for editing. The source thread, its session document and the workspace are untouched, and there is no file rollback: a fork is a sibling conversation, and rewinding the workspace would rewind the branch left behind with it. Clients should name the turn instead of computing a `depth` — the transcript they render and the turn list this cuts are not the same list (steers, image-only prompts and injected handoffs each sit on one side only), and a client-side count that is off by one forks the wrong prefix while answering `201`. `400` when the turn is not a user turn of that thread.
1778 - `GET /v1/threads/{id}/patch-undo?turn_id=turn_…` - validates the selected restore without changing files or publishing a fork; returns `turn_ids`, the exact dropped range, `paths` needing restoration and an optional no-change `summary`. Requires the `thread_patch_undo_turn_id` capability.
1779 - `POST /v1/threads/{id}/patch-undo` - rolls back the files the dropped turns changed, then the same fork (`{"depth": N}` or `{"turn_id": "turn_…"}`, with `turn_id` taking precedence); returns `patch_result` (`files_restored`, `summary`, `snapshot_label`) alongside the forked thread. See [Workspace restore endpoints](#workspace-restore-endpoints) for ownership, the admission and abort rules, and the `error.code` values of a refusal.
1780 - `POST /v1/threads/{id}/file-revert` - restore exactly one file from one restore point the thread owns (`{"path", "snapshot_id", "expected_hash"}`); never forks the conversation. See [Workspace restore endpoints](#workspace-restore-endpoints).
1781 - `POST /v1/threads/{id}/retry` - fork with the last N turns removed and immediately start a new turn (`{"depth": N, "prompt": "..."}`; `prompt` overrides the original user text, which is re-used when omitted)
1782
1783 `POST /v1/threads/{id}/turns` accepts the same optional
1784 `reasoning_effort` and `allowed_tools` fields as per-turn overrides:
1785
1786 ```json
1787 {
1788 "prompt": "Review this change without running tools.",
1789 "operation_key": "cwc-request-01J7Y6Q9W4",
1790 "reasoning_effort": "max",
1791 "allowed_tools": []
1792 }
1793 ```
1794
1795 The same `model_provider` / `model_provider_id` fields on a turn route that
1796 one turn through another provider. The saved thread keeps its provider.
1797 Without `model`, the turn uses that provider's default model (an `auto` thread
1798 stays `auto`). The override is always preflighted and is part of the
1799 `operation_key` fingerprint.
1800
1801 Account-owned model turns require `capabilities.account_model_owner: true` before
1802 submission. Set `account_model_owner` to the signed-in account ID, both
1803 `model_provider` and `model_provider_id` to `codewhale`, and `model` to the exact
1804 `provider/model` account route. The Runtime requires current model access for
1805 that same secure account session and uses only that account credential; missing,
1806 expired or revoked access is refused. Local keys and other configured routes are
1807 not substitutes. A supplied profile constitution must belong to the same account.
1808 The owner participates in the durable operation fingerprint; replay of an
1809 already completed exact operation returns its receipt before fresh credential
1810 admission. The account gateway resolves the selected provider's current saved
1811 API key at use. Ordinary turns and saved Chat defaults retain their existing
1812 behavior. The Runtime Chat relay carries the same assertion as `accountModelOwner`.
1813
1814 Resolution is deterministic: a turn override wins over the thread default,
1815 which wins over the Runtime's normal configuration. For tools, reaching normal
1816 configuration means the ordinary configured catalog; `[]` is never treated as
1817 missing. Reasoning is normalized only after the exact provider/model route is
1818 resolved, and `auto` remains a per-prompt reasoning decision even when the
1819 thread uses a fixed model. The request still enters the existing
1820 `Op::SendMessage` path and the single `Engine::run_turn` loop.
1821
1822 Image input uses the same turn path: `"images": [{"mime": "image/png",
1823 "dataBase64": "..."}]`. Clients must first observe
1824 `capabilities.turn_image_inputs: true` in `/v1/runtime/info` (or the isolated
1825 Runtime Chat relay catalog). Older HTTP runtimes ignore unknown fields, so a
1826 successful text response is not evidence that an attachment was accepted.
1827 The field is omitted when empty. It is also accepted by app-server
1828 `thread/message`, `thread/request` messages, and prompt requests; that bridge
1829 checks the underlying Runtime capability before forwarding image bytes.
1830 Legacy remote Work commands do not support images and explicitly refuse them.
1831
1832 New inline images require a named model whose exact resolved route reports
1833 `image_input: "supported"`; Auto and unknown/unsupported image routes are
1834 refused before classifier or provider dispatch. This does not change the
1835 existing trusted-local attachment behavior for routes with unknown capability.
1836 A nonempty prompt is required. Inputs are limited to 10 images, 4 MiB decoded
1837 bytes per image, 5 MiB total, and an 8 MiB JSON body. PNG, JPEG, GIF and WebP
1838 must have matching MIME, canonical padded base64 and valid bounded image
1839 content: at most 8192 pixels per dimension, 33,554,432 pixels total and 64 MiB
1840 decoder allocation. The Runtime does not fetch paths or URLs from this field.
1841 Malformed images refuse the whole turn; callers can retain the draft for
1842 correction. Relay command polling uses an 8 MiB response budget; the sender
1843 must paginate by serialized bytes without advancing past unserved commands.
1844
1845 Accepted image bytes and order are retained in the existing turn records and
1846 reconstructed after restart, import and fork. Retry retains those images even
1847 when its optional `prompt` changes the text; undo responses include
1848 `original_user_images` when present. Image-bearing records require schema v3,
1849 which older readers refuse. Text-only records and operation fingerprints retain
1850 their prior representation. Validated stored local images retain the existing
1851 5 MiB per-image ceiling and prior aggregate/count semantics on import/retry;
1852 this internal storage authority does not
1853 relax exact model or permission checks. Image bytes, MIME and order participate in request
1854 identity, so changing an image under the same operation key conflicts.
1855 Compaction can summarize older context; retaining the original attachment does
1856 not promise that every later model request includes it. Image pixels are not
1857 subject to text-secret redaction.
1858
1859 `operation_key` is an optional idempotency key for clients that may lose an
1860 HTTP response after the Runtime accepted a turn. It is scoped to the current
1861 Runtime store and thread, may contain at most 128 UTF-8 bytes, and may not be
1862 empty or contain surrounding whitespace or control characters. Omitting it
1863 preserves the legacy create-a-new-turn behavior.
1864
1865 The first accepted request durably binds a SHA-256 fingerprint of the key to
1866 the Runtime turn id and a canonical request fingerprint before sending the
1867 existing `Op::SendMessage`. An exact retry returns that original turn in the
1868 normal `{ "thread": ..., "turn": ... }` response and emits no second engine
1869 operation, item, or lifecycle sequence. Reusing the key on the same thread
1870 with a different provider/model, prompt, reasoning policy, tool allowlist or
1871 dynamic-tool schema, environment, or permission policy fails closed with
1872 `409 Conflict`. The same caller key may be used independently on another
1873 thread.
1874
1875 Only the scoped key fingerprint, request fingerprint, thread id, and turn id
1876 are stored in the Runtime's private turn-operation index. The raw key is never
1877 persisted or logged, and request bodies, credentials, and attachments are not
1878 copied into that index. Existing thread/turn persistence remains the source of
1879 the returned turn after a process restart.
1880
1881 **Exact accepted-turn lookup**
1882
1883 `GET /v1/threads/{id}/turn-operations/{operation_key}` uses the same Runtime
1884 authentication as turn submission. URL-encode each path segment. It returns
1885 `200 OK` with the existing bare `TurnRecord` (the `turn` object in the POST
1886 response), identified by that exact thread and operation key. It does not use
1887 the thread's latest turn or require the original request body or current route
1888 settings to match.
1889
1890 - `404 Not Found`: no binding exists for that thread/key, or persisted identities
1891 do not match. These cases share a generic response.
1892 - `409 Conflict`: admission holds the operation claim, or its durable binding
1893 is incomplete. Retry the lookup; this response does not authorize another turn.
1894 - `400 Bad Request`: the thread ID or operation key is malformed. The key uses
1895 the same 128-byte and whitespace/control-character rules as POST.
1896 - `500 Internal Server Error`: storage or the existing claim lock cannot be
1897 checked safely. This is not evidence that the operation is absent.
1898
1899 The lookup holds a shared read lock on the existing operation claim while
1900 reading the binding and turn. It creates no files, starts no engine, emits no
1901 events, and performs no replay or recovery. Normal Runtime startup may recover
1902 an incomplete admission before a later lookup, but GET itself never does so.
1903
1904 **Approvals**
1905 - `POST /v1/approvals/{approval_id}` with body
1906 `{ "decision": "allow" | "deny", "remember": false, "client": "desktop" }`.
1907 `client` is optional and names the surface that answered: `desktop`, `phone`,
1908 `web`, `tui` or `acp`. The answer's `approval.decided` event carries it as
1909 `responder`. It is a label the client declares, not an authenticated device
1910 identity; an answer without it records no `responder`.
1911 - `GET /v1/approvals?limit=` (1-500, default 100) is the read-only history:
1912 decided and still-pending approvals across all sessions, newest ask first.
1913
1914 Each history row carries `approval_id`, `tool_name`, `outcome`, `asked_at` and
1915 `decided_at` (null while pending), plus optional `decided_by` (`user`,
1916 `session_rule`, `posture`, `host`), `target` and `summary`. `outcome` is one of
1917 `allowed_once`, `denied`, `timeout`, `cancelled`, `unavailable`,
1918 `retry_with_policy`, or `pending`. `standing_rule` (`allow` or `deny`) is present
1919 only when a remembered session rule or grant answered rather than a person
1920 (`decided_by: session_rule`); `outcome` is unchanged. `target` is the host of a
1921 URL or a workspace-relative path (absolute paths outside the workspace are
1922 reduced to `.../<basename>`); `summary` is a one-line description of what was
1923 asked. Both are redacted conservatively when the ask is recorded: a shell
1924 command keeps only the program name and plain arguments, and any quoted,
1925 `KEY=VALUE`, credential-like or unrecognised argument replaces all arguments
1926 with `[args redacted]`. Whitespace is collapsed and text is capped at 120
1927 characters. Rows recorded before these fields existed
1928 omit `target` and `summary`.
1929
1930 A pending row whose prompt is still live carries that prompt's minted
1931 `approval_id`, so `POST /v1/approvals/{approval_id}` answers it. Such a row also
1932 carries `thread_id`, and `approval_kind: "third_party_search"` when it is a web
1933 search consent. Decided rows, and pending rows with no live prompt, keep the
1934 Engine call ID as `approval_id` and omit both fields; answering with that ID
1935 returns `404`.
1936
1937 `approval_id` is minted by the Runtime, not by the model or the provider. It is
1938 an opaque `approval_<32 hex>` capability, unique per prompt, bound to the thread
1939 that raised it, and single-use: the Runtime removes it when the decision is
1940 delivered, when the prompt times out, or when the turn abandons it. Clients echo
1941 the value they were given and must not construct, derive, or guess one.
1942
1943 It is deliberately **not** the provider's tool-call ID. Providers restart their
1944 call-ID counters per response, so two threads can gate calls whose raw IDs are
1945 byte-equal; keying approvals by that value let one thread's decision settle
1946 another thread's call. The endpoint therefore performs one exact match on the
1947 minted ID and has no fallback: a raw tool-call ID, an expired ID, or a replayed
1948 ID that has already been settled all return `404` and reach no engine. A `404`
1949 means the capability is not pending — it is not evidence about how the approval
1950 was resolved; read `approval.decided` for that.
1951
1952 The Engine tool-execution ID travels separately as `tool_call_id` on
1953 `pending_approvals[]` and on the approval events. It is a correlator for
1954 attaching a prompt to the tool row it gates, and never accepted as a decision.
1955 Each thread-detail `pending_approvals[]` entry is
1956 `{ "id", "turn_id", "tool_name", "input"?, "description", "intent_summary"?, "tool_call_id"?, "summary"? }`,
1957 where `id` is the capability above. `input` holds the captured tool input. An
1958 omitted `input` means no captured value is available; an explicit JSON `null`
1959 remains a captured value. On the authenticated canonical thread surface,
1960 `approval.required` carries the same captured input.
1961 `summary` (also on `approval.required`) is
1962 a one-line description of the gated call built from the tool name and its
1963 arguments only, never from model text ("Search the web for 'espresso'",
1964 "Write notes/espresso.md"); paths inside the workspace are workspace-relative.
1965 Clients show it first and keep the raw arguments behind it. For task and
1966 automation create/update, `summary` also names the requested trust mode,
1967 shell, auto-approve, mode and workspace. For a shell command, task gate,
1968 shell input or verifier whose `curl`/`wget` request body carries a credential
1969 file or a secret-named variable, or reads stdin fed from one of those or from
1970 `env`/`printenv`, `summary` reads ``Upload credentials (`…`) with `…` ``; the
1971 built-in safety gate holds that call, so a session grant or saved allow rule
1972 cannot answer it. A shell command, shell input or verifier over 64 KiB or
1973 4,096 words whose text contains `curl` or `wget` anywhere, or one nested too
1974 deeply to read, is held the same way under its ordinary `summary`. A shell
1975 command containing a hidden Unicode character is refused before any
1976 approval is created.
1977
1978 `"remember": true` on an `allow` records a **session grant** for that tool and
1979 argument class (the approval grouping key: a shell command family for a
1980 simple, known command such as `git status` whose only options are value-free
1981 ones like `-s` or `--porcelain` — a compound, wrapper, interpreter or
1982 unrecognised command, one with any other option, or one whose arguments are
1983 what runs or is installed (`go run`, `make`, `git bisect`, package installs)
1984 is granted as its full normalized command, and a
1985 shell run given stdin (`stdin`, `input` or `data`), or a shell interact or wait call, as the exact call — a patch's file set, a `fetch_url` host, an MCP tool, a `web.run` action kind — for
1986 `open`, the hosts it opened). Computer Use consent and `app_script` calls, and
1987 any tool without a class, are granted for the exact call only. A grant never
1988 changes the thread's permission posture. Later matching calls on the thread are
1989 approved without a prompt: they still emit `approval.required`, then
1990 `approval.decided` with `"auto": true` and the `grant_id`. Creating a grant
1991 emits `approval.grant_added` with `{ "grant": { "grant_id", "tool_name",
1992 "scope", "summary", "granted_at" } }`; thread detail lists live grants in
1993 `approval_grants[]`. `DELETE /v1/threads/{id}/approval-grants/{grant_id}`
1994 revokes one (emitting `approval.grant_revoked`); the next matching call
1995 prompts again. Archiving or deleting the thread ends all of its grants
1996 (archiving emits `approval.grant_revoked` for each; unarchiving does not
1997 restore them). Grants are stored in the Runtime data directory
1998 (`approval_grants.json`). After a Runtime restart a thread's grants stay
1999 suspended, and matching calls prompt again, until an authenticated client
2000 resumes the thread. A grant store that cannot be read holds no grants, so every
2001 call prompts. A forced (non-bypassable) prompt is never answered by a grant.
2002
2003 `"remember": true, "remember_scope": "workspace"` on an `allow` saves the
2004 same exact, repo-scoped allow rule the terminal's "always allow this exact
2005 rule in this repo" writes to the user `permissions.toml`, then allows the call
2006 once; it records no thread grant. `remember_scope: "thread"` is the session
2007 grant above, and `remember_scope` without `"remember": true`, or `workspace`
2008 with `deny`, is `400 invalid_remember_scope`. Only an attached owner runtime
2009 and an owner caller may save one (`403 owner_required`, the same check as
2010 Auto-Review retry approval). Only a shell command classified safe, or a
2011 `write_file`, `edit_file` or `apply_patch` inside the thread's workspace, is
2012 eligible; publish-like, destructive or credential-touching calls,
2013 repository-law holds, sub-agent approvals, external-agent approvals and
2014 archived threads are `422 standing_rule_ineligible`, nothing is written and the
2015 approval stays pending. "In this repo" means the conversation's recorded
2016 workspace folder, exactly as spelt: not the git root, and not another path to
2017 the same folder. `approval.required` carries `standing_rule_candidates[]`, the
2018 exact rules a save would write (empty when the prompt is not eligible), so a
2019 client can show the rule before offering the button. While a save is being
2020 written, any other answer to that approval is `409`; if the save fails, the
2021 approval can be answered again. A config or permissions file that cannot be
2022 read or written is `409 permissions_unavailable`. The response adds
2023 `standing_rules[]` (each `{ tool, command?, command_exact?, path?, workspace,
2024 action }`); repeating the same request while the approval is still settling
2025 returns the same rules.
2026 Every save appends a `permission.rules_saved` event (`approval_id`,
2027 `tool_call_id`, `tool_name`, `standing_rules`) to the thread, whatever happens
2028 to the call. `approval.decided` also carries `remember_scope: "workspace"` and
2029 the same `standing_rules` whenever a rule was saved for that approval; there
2030 they mean "a rule was saved", and `remember` is `true` only when the call was
2031 also allowed. If the prompt is withdrawn, cancelled or times out while the rule
2032 is being written, the rule stays, the response says `delivered: false`, and
2033 `permission.rules_saved` is the record. Running threads of this Runtime use the
2034 new rule on their next matching call.
2035
2036 A client sends `remember_scope` only when `GET /v1/runtime/info` reports
2037 `capabilities.approval_remember_workspace`, and treats a `200` without
2038 `standing_rules` as "no rule was saved": the request body ignores unknown
2039 fields, so an older Runtime, or a misspelt field, answers the request as the
2040 plain `remember` choice.
2041
2042 **Permission rules and grants**
2043 - `GET /v1/permissions/rules` returns
2044 `{ status: "ok", path, exists, rules[] }` for the user `permissions.toml`
2045 sibling of the config the Runtime loaded. Each rule is
2046 `{ index, tool, command, command_exact, path, workspace, action, layer, removal_token }`
2047 (`layer` is `user`). A missing file is `exists: false` with no rules. A file
2048 that cannot be read or parsed, or a Runtime with no user config, answers
2049 `{ status: "unavailable", reason }` with no `rules`, never an empty list.
2050 Values are returned as data; clients escape them.
2051 - `POST /v1/permissions/rules/remove` with
2052 `{ "token": "<removal_token>", "client"?: "desktop"|"tui"|"web"|"phone"|"acp" }`
2053 removes that one rule and answers `{ ok, removed }`. Removing a `deny` or
2054 `ask` rule loosens policy, so it requires an attached owner runtime and an
2055 owner caller (`403 owner_required`); watch tokens are refused by the
2056 read-only gate. A token that is not 24 lowercase hex characters is `400
2057 invalid_permission_token`. A token that no longer describes the current file
2058 (the file changed after listing, or the rule was already removed) is `409
2059 stale_permission_token` and writes nothing; a file that cannot be read or
2060 written is `409 permissions_unavailable`. The response's `applied_to:
2061 "this_runtime"` says the scope of the live effect: running threads of this
2062 Runtime stop using the rule on their next matching call, but a running
2063 terminal session or another Runtime process on the same `permissions.toml`
2064 keeps the rule in memory until it reloads or restarts.
2065 - `GET /v1/approval-grants` returns `{ status: "ok", grants[] }` across every
2066 thread: `{ grant_id, scope_kind, thread_id, workspace_id, effect, tool_name,
2067 label, summary, created_at, last_used_at, uses, state, suspended_reason }`.
2068 Suspended grants are listed with `state: "suspended"`. An unreadable grant
2069 store answers `{ status: "unavailable", reason }`.
2070
2071 Running threads pick up rule changes made through these routes. `GET
2072 /v1/permissions/rules` lists the file, not the live policy: an edit to
2073 `permissions.toml` made by hand or by the terminal does not reach a running
2074 Runtime thread until `POST /v1/config/reload`, which re-reads the file and
2075 applies it to running threads and to threads started afterwards.
2076
2077 **Auto-Review blocks and one-use retry grants**
2078 - `GET /v1/threads/{id}/auto-review/blocks` returns `{ thread_id, blocks[] }`
2079 listing recorded Auto-Review blocks on the thread (`receipt_id`,
2080 `call_digest`, `tool_id`, `tool_name`, `action_summary`, `rule`, `reason`,
2081 `gate`, `verdict`, `approved`, `approvable`).
2082 - `POST /v1/threads/{id}/auto-review/approve` with body
2083 `{ "target": "<receipt_id_or_call_digest>", "client"?: "desktop"|"tui"|"web"|"phone"|"acp" }`
2084 requires an attached owner runtime and an owner caller (`403 owner_required`
2085 otherwise; `"desktop"`/`"phone"` web/cookie callers are also rejected), requires
2086 the thread to remain in Auto-Review (`409 not_in_auto_review`), returns `404`
2087 when no matching block exists or `409` when already approved or not
2088 approvable, and otherwise mints one exact-call retry grant bound to
2089 `(tool_name, call_digest)` returning `{ ok, thread_id, grant }` and emitting
2090 `auto_review.retry_approved`. The retried call consumes the grant on one use
2091 and still runs every non-Auto-Review gate (with `person_approved_retry` on
2092 guardian review so high/critical risk may pass if guardian allows, while an
2093 explicit guardian deny or failure still blocks). Child agents and plugin
2094 calls cannot create, read, or consume retry grants. If Auto-Review trips its
2095 interactive thresholds (3 consecutive blocks, 20 total blocks, or 3
2096 consecutive unavailable checks), it switches thread `permission_posture` to
2097 `ask` and emits `auto_review.paused` + `thread.updated`.
2098
2099 **User input**
2100 - `POST /v1/user-input/{thread_id}/{input_id}` with body
2101 `{ "answers": [{ "id": "question-id", "label": "Choice", "value": "Choice" }] }`
2102
2103 Submitted values are delivered to the active model turn but are deliberately
2104 excluded from durable Runtime items and events. The settled tool item contains
2105 only a neutral receipt and a machine-readable `response_redacted` marker. The
2106 Runtime accepts only an exact pending `(thread_id, input_id)` request; an
2107 unknown, concurrently settling, or already settled id returns 404 and is never
2108 placed in the engine mailbox. It commits the secret-free
2109 `user_input.answered` receipt before removing the snapshot-authoritative prompt
2110 or delivering the answer to the engine. That settlement runs independently of
2111 the HTTP connection, so disconnecting after submission cannot leave a prompt
2112 half accepted. Terminal-turn cancellation follows the same receipt-before-
2113 removal ordering through `user_input.canceled`.
2114
2115 **Client-executed dynamic tools**
2116 - `POST /v1/threads/{thread_id}/turns/{turn_id}/tool-calls/{call_id}/result`
2117
2118 The thread and turn in the result route must match the pending call. A call is
2119 settled at most once; wrong-route and duplicate results return 404. Terminal
2120 lifecycle events carry identifiers and status only, never tool result content.
2121 The Runtime commits the terminal lifecycle event before making a submitted
2122 result available to the model. Result delivery, timeout, and terminal-turn
2123 cancellation race through one settlement owner, so exactly one of these events
2124 is durable for a call:
2125
2126 - `tool_call.requested` — the typed client-executed call became pending;
2127 - `tool_call.resolved` — a result was durably accepted by the Runtime
2128 (`result_accepted: true`; `success` is result metadata, but result content is
2129 excluded);
2130 - `tool_call.timeout` — no result won before the bounded wait expired;
2131 - `tool_call.canceled` — the turn terminated before a submitted result won.
2132
2133 HTTP `202 Accepted` and `tool_call.resolved` share that durable-acceptance
2134 meaning. Neither claims that the model consumed the result: a concurrent turn
2135 shutdown may close the model receiver after acceptance. Once the Runtime has
2136 accepted the result, that call is terminal and a duplicate result returns 404.
2137
2138 **Events** (SSE replay + live stream)
2139 - `GET /v1/threads/{id}/events?since_seq=<u64>&replay_limit=<n>&progress=true`
2140
2141 Cursors:
2142
2143 - `since_seq` is the per-thread cursor: events with `seq > since_seq` are sent.
2144 Omitted (and no `Last-Event-ID`), the stream starts from the beginning of the
2145 thread's history.
2146 - Every journal frame carries `id: <seq>`, so a browser `EventSource` can
2147 resume through the `Last-Event-ID` header it sends on reconnect. An explicit
2148 `since_seq` wins over the header, so a deliberate replay from `0` is never
2149 overridden by a stale id. A header value that is not a decimal integer is
2150 ignored.
2151 - `replay_limit` (at most 4096) returns only the newest tail of the requested
2152 history; `previous_seq` on the first returned event advances past exactly the
2153 omitted history.
2154
2155 Durable history parsing runs off the async server workers and reaches SSE in
2156 bounded batches of at most 256 events through a backpressured channel. Broadcast
2157 delivery is only a wake-up optimization: a lagged receiver opens the same
2158 bounded durable replay from its last accepted cursor.
2159
2160 `progress=true` adds `stream.progress` transport frames
2161 (`{schema_version, event, kind, thread_id, seq, state}`, `state` is
2162 `replaying` or `live`) at the current cursor and advertises them with
2163 `x-codewhale-event-progress: 1`. The stream reports `live` only after durable
2164 history and the already-queued live tail are both drained; broadcast-lag
2165 recovery returns it to `replaying`. Progress frames never carry a new sequence
2166 number.
2167
2168 Failures before the stream opens are ordinary HTTP errors with the JSON error
2169 body, never SSE:
2170
2171 | Status | When |
2172 | --- | --- |
2173 | `401` / `403` | Missing or wrong Runtime credential |
2174 | `404` | Unknown thread |
2175 | `400` | `replay_limit` above 4096 |
2176 | `500` | The durable history could not be opened (including a replay worker crash before the first cursor) |
2177
2178 Once the response is `200`, every end the server chooses is a final
2179 `stream.end` frame; see [Ending and resuming a thread
2180 stream](#ending-and-resuming-a-thread-stream).
2181
2182 **Snapshots** (side-git restore point listing + restore)
2183 - `GET /v1/snapshots?limit=20&thread_id=`
2184 - `POST /v1/snapshots/{id}/restore?thread_id=`
2185
2186 `/v1/snapshots` lists recent side-git restore points for the runtime workspace.
2187 `limit` defaults to `20` and must be between `1` and `100`. `POST
2188 /v1/snapshots/{id}/restore` restores workspace files from the snapshot and
2189 returns `{"restored": "<snapshot-id>"}`. It is the direct operator surface for
2190 the server's own workspace (the same action as the TUI's `/restore <N>`): it is
2191 gated by the Runtime API bearer token, not by any thread's trust flag, and it
2192 is refused with `409` while a turn is active in an overlapping workspace (see
2193 below). A `pre-restore:` safety snapshot is taken first. With `thread_id`
2194 (capability `thread_scoped_snapshots`) both routes act on that thread's
2195 recorded workspace instead, under the same admission rule; an unknown thread
2196 answers `404` and a missing or changed workspace `409`
2197 `thread_workspace_unavailable`.
2198
2199 ```json
2200 [
2201 {
2202 "id": "snap_...",
2203 "label": "post-turn:1",
2204 "timestamp": 1780730580
2205 }
2206 ]
2207 ```
2208
2209 ### Workspace restore endpoints
2210
2211 Three routes mutate workspace files from side-git snapshots. They share one
2212 admission rule and one safety net, and they differ in scope and trust.
2213
2214 | Route | Scope | Trust | Forks the thread |
2215 | --- | --- | --- | --- |
2216 | `POST /v1/snapshots/{id}/restore` | whole server workspace, or the `thread_id` workspace | bearer token only (operator action) | no |
2217 | `POST /v1/threads/{id}/patch-undo` | the files the dropped turns changed | none; only files the dropped turns' own tool calls wrote, still holding the bytes the turn left, are restored | yes |
2218 | `POST /v1/threads/{id}/file-revert` | exactly one regular file | none; the restore point must be one the thread owns and `expected_hash` must match | no |
2219
2220 **Admission.** A restore reserves the same admission the Runtime uses for
2221 config reloads and session checkpoints, so no new turn starts and no saved
2222 history changes while files are being rewritten. If any thread already has an
2223 active turn in the same workspace, a nested checkout of it, or a parent of it,
2224 the request is refused with `409` and the message `already has an active turn`.
2225 The reservation is owned by the worker performing the Git mutation, so a client
2226 that disconnects mid-request cannot release it early; the operation completes
2227 or fails as a whole. Concurrent restores serialize. The reservation is
2228 runtime-wide: while a restore's safety snapshot and checkout run, new turns,
2229 steering, compaction and user-input delivery on every thread wait for it to
2230 finish, so a large workspace can add seconds of latency elsewhere during a
2231 restore. A thread whose workspace directory is not available (unmounted
2232 volume, disconnected share, missing directory) is refused with `409` rather
2233 than treated as having nothing to restore.
2234
2235 **Ownership.** A thread owns exactly the workspace restore points recorded on
2236 its own turns. While a turn runs, the engine reports each snapshot it takes —
2237 `pre_turn` before the turn, `tool` before and `post_tool` after each tool call
2238 that may write (every call that is not read-only: file tools, shell commands,
2239 programs, write-capable MCP tools), `post_turn` when it ends (always before
2240 the turn settles) — and the Runtime appends it to the turn record's
2241 `workspace_snapshots`, in order:
2242
2243 ```json
2244 "workspace_snapshots": [
2245 { "kind": "pre_turn", "snapshot_id": "<commit>", "tree_id": "<tree>", "session_id": "thr_1a2b3c4d" },
2246 { "kind": "tool", "snapshot_id": "<commit>", "tree_id": "<tree>", "session_id": "thr_1a2b3c4d", "tool_call_id": "call_…", "write_paths": ["src/lib.rs"], "changed_paths": [] },
2247 { "kind": "post_tool", "snapshot_id": "<commit>", "tree_id": "<tree>", "session_id": "thr_1a2b3c4d", "tool_call_id": "call_…", "changed_paths": ["src/lib.rs"] },
2248 { "kind": "post_turn", "snapshot_id": "<commit>", "tree_id": "<tree>", "session_id": "thr_1a2b3c4d", "changed_paths": [] }
2249 ]
2250 ```
2251
2252 `changed_paths` lists the workspace-relative paths whose content changed since
2253 the turn's previous receipt — what happened in the span the receipt closes; it
2254 is absent on `pre_turn` and when it could not be computed (a snapshot in
2255 between failed). `write_paths` is set on the `tool` receipt of a file tool
2256 (`write_file`, `edit_file`, `apply_patch`) to the paths the call declared, as
2257 it named them; a tool without it (a shell command) may write any path. On a
2258 user shell turn the `pre_turn` receipt carries the command's `tool_call_id`,
2259 since the command runs from it to `post_turn`.
2260
2261 Each receipt is also published as a `turn.workspace_snapshot` event (payload:
2262 the receipt). The engine runs every Runtime thread under the thread's own id,
2263 across restarts and engine eviction, so `session_id` is the thread id for turns
2264 the thread ran itself; it does not follow the thread's saved-session binding
2265 (`PUT`/`POST /v1/sessions`, resume), which only names a document. A fork clones
2266 its source's turn records and so owns the restore points of the turns it
2267 inherited. Another thread's, or a TUI session's, snapshots in the same
2268 workspace are never candidates. `tree_id` is the durable identity: a prune
2269 rebuilds the side repo and rewrites every commit id but keeps each tree, and a
2270 restore point resolves only to a stored snapshot with the same tree, session
2271 tag and kind. The count prune after each snapshot keeps the newest 50
2272 snapshots plus the newest 50 turn boundaries (`pre-turn:`/`post-turn:`), so a
2273 turn with more tool calls than that, or a burst from another thread, never
2274 pushes out a recent turn's own restore points. Turns recorded before receipts existed, turns imported by
2275 `resume-thread`, and turns run with snapshots off or unavailable have none.
2276
2277 **Safety net.** Every restore first records a `pre-restore:<target>` snapshot
2278 of the current workspace. That label is never a `/undo`, `patch-undo` or
2279 `file-revert` candidate, so the net does not change what later undos select.
2280 For `file-revert` the backup is mandatory: if it cannot be written, or the
2281 requested file is excluded from it (for example by `.gitignore`), the request
2282 fails and nothing is changed.
2283
2284 **`patch-undo`.** Undoes whole turns. A named `turn_id` removes that user turn and every turn after it, under the same restore admission as `/undo`. Clients must require `thread_patch_undo_turn_id` before sending selected-turn requests: older Engines may ignore that field. Preview with `GET`, then send its exact `turn_ids` as `expected_turn_ids` and `paths` as `expected_paths` on `POST`; `409 undo_selection_changed` refuses an altered range or file plan before file changes. A preview does not reserve future execution or promise idempotency. The mutation is not automatically retryable after a lost response.
2285
2286 For each dropped turn's `pre_turn` →
2287 `post_turn` window, the paths that differ between the two snapshots must all be
2288 the turn's own: changed only in the span of one of the turn's tool calls (a
2289 `tool` → `post_tool` span, or a shell turn's whole window), and, inside a file
2290 tool's span, a path that call declared. A path that changed while none of the
2291 turn's tools could have written it — another thread, an editor, a background
2292 process — is someone else's change, and the undo is refused rather than revert
2293 it. Each of the turn's paths goes back to its content before the first dropped
2294 turn that changed it, and nothing else is touched, so later work by the user or
2295 another thread in the same workspace survives. Then the conversation forks
2296 exactly as `/undo` does.
2297
2298 Snapshots never hold paths excluded by the workspace's `.gitignore` files or
2299 the built-in snapshot exclusions (`node_modules/`, `target/`, `dist/`, build
2300 caches, binary artifacts), nor paths outside the workspace. A dropped file-tool
2301 call that declared such a path is refused with `path_not_snapshotted`, because
2302 no snapshot can put it back. A shell command declares no paths: what it writes
2303 under an excluded path (build output, dependency installs) is outside what
2304 `patch-undo` restores and is not reported. `201` means either files were restored (`files_restored: true`, one
2305 `<action> <path>` line per file in `summary`, `snapshot_label` naming the
2306 pre-turn snapshot) or there was provably nothing to restore
2307 (`files_restored: false`): every dropped turn ran here without a tool call,
2308 changed no file, or its files are already back at their pre-turn content.
2309 Anything that cannot be restored aborts the whole undo with `409`, nothing is
2310 changed and no fork is published; `error.code` says why:
2311
2312 | `error.code` | Meaning |
2313 | --- | --- |
2314 | `restore_point_unavailable` | a dropped turn that may have changed files has no complete recorded restore point (older record, imported by `resume-thread`, snapshots off, or the snapshot failed) |
2315 | `restore_point_pruned` | the restore point is no longer in the snapshot store |
2316 | `path_not_snapshotted` | a dropped file-tool call wrote a path snapshots do not hold (ignored, built-in exclusion, or outside the workspace) |
2317 | `workspace_changed_since_turn` | a path the turns changed was changed afterwards (or between two dropped turns), a path changed while a dropped turn ran but outside its own tool calls, or a path that is not a regular file |
2318 | `workspace_unavailable` | the workspace directory is not available |
2319
2320 For the first four a client can offer the conversation-only
2321 `POST /v1/threads/{id}/undo` instead, and `file-revert` for individual files.
2322 Snapshot repository, listing or comparison failures abort with `500` and also
2323 preserve the conversation, so a turn is never dropped while its file changes
2324 stay on disk. Depth and history are validated before any file changes. If the
2325 fork cannot be persisted after files were restored, the response is a `500`
2326 that names the restored snapshot; the original thread still holds the turn and
2327 the `pre-restore:` snapshot holds the previous files.
2328
2329 **`file-revert`.** Request body:
2330
2331 ```json
2332 {
2333 "path": "src/lib.rs",
2334 "snapshot_id": "3f2a…40-or-64 hex…",
2335 "expected_hash": "sha256:<64 lowercase hex digits>"
2336 }
2337 ```
2338
2339 - `path`: workspace-relative, or absolute inside the thread workspace. The
2340 name is literal (brackets, spaces and glob characters are filename bytes;
2341 Git runs with `--literal-pathspecs`). It must name a regular file: directories,
2342 symlinks anywhere in the path, and `.git` components are `400`.
2343 - `snapshot_id`: the exact `tool` or `pre_turn` restore point of the change
2344 the user selected, from the thread's own turn records: a receipt's
2345 `snapshot_id` or `tree_id` (for a tool call, the receipt whose
2346 `tool_call_id` matches), or the current commit id `GET /v1/snapshots` lists
2347 for it. It must be a restore point recorded on one of this thread's turns;
2348 the server never picks "the newest snapshot that differs", because an
2349 unrelated newer snapshot can erase later user edits while leaving the tool's
2350 change.
2351 - `expected_hash`: `sha256:` of the current file bytes the client displayed,
2352 or `absent` when the client saw the file as deleted. It is checked before the
2353 safety backup and again immediately before the mutation.
2354
2355 Responses:
2356
2357 - `200 {"path", "action", "snapshot_id", "snapshot_label"}` — `action` is
2358 `modified`, `recreated` (file was missing) or `removed` (the snapshot does
2359 not contain the file, so the file the tool created is deleted; its parent
2360 directories are left in place).
2361 - `400`: malformed `snapshot_id`/`expected_hash`, path outside the workspace,
2362 or a path that is not a regular file on either side.
2363 - `404`: unknown thread.
2364 - `409`: active turn in an
2365 overlapping workspace; workspace directory not available; snapshot unknown,
2366 pruned, not recorded on this thread's turns (another thread's or a TUI
2367 session's), or not a restore point (refresh the change record); file already
2368 matches the
2369 snapshot (nothing to revert); or the file changed after the reviewed
2370 `expected_hash` (refresh and review again). Nothing is changed in any of
2371 these cases.
2372 - `422`: missing or mistyped body fields.
2373 - `500`: Git or filesystem failure; a failure after the safety snapshot names
2374 that snapshot so the previous bytes can be recovered with
2375 `POST /v1/snapshots/{id}/restore` or `/restore`.
2376
2377 Capability probe: `GET` on the route returns `405` where the endpoint exists
2378 and `404` on an older engine; clients treat any non-`404` as available and
2379 degrade with an explanation otherwise.
2380
2381 **Compatibility stream** (one-shot, backwards-compatible)
2382 - `POST /v1/stream`
2383
2384 **Tasks** (durable background work)
2385 - `GET /v1/tasks`
2386 - `POST /v1/tasks`
2387 - `GET /v1/tasks/{id}`
2388 - `POST /v1/tasks/{id}/cancel`
2389
2390 **Automations** (scheduled recurring work)
2391 - `GET /v1/automations`
2392 - `POST /v1/automations`
2393 - `GET /v1/automations/{id}`
2394 - `PATCH /v1/automations/{id}`
2395 - `DELETE /v1/automations/{id}`
2396 - `POST /v1/automations/{id}/run`
2397 - `POST /v1/automations/{id}/pause`
2398 - `POST /v1/automations/{id}/resume`
2399 - `POST /v1/automations/{id}/adopt`
2400 - `GET /v1/automations/{id}/runs?limit=20`
2401
2402 Create and update requests accept an optional `model`. When present, each
2403 scheduled or manually triggered run uses that model; omitting it keeps the
2404 runtime's default task model.
2405
2406 Create and update requests also accept an optional `destination_thread_id`.
2407 When set, each run is delivered into that existing thread as a new turn
2408 instead of starting a new task thread; the turn item carries
2409 `{"input_provenance":"scheduled","task_id":...}` metadata, and the turn uses
2410 the thread's own model and permission posture. If the thread is busy the run
2411 waits for its current turn to finish (bounded by the task wall-time budget,
2412 which pauses while a prompt on the run itself awaits a decision).
2413 A destination that no longer exists or is archived fails the run with a
2414 receipt naming the thread; it is never rerouted to a new thread. An empty
2415 string on `PATCH` clears the destination. Create and update return `404` for
2416 an unknown thread and `409` for an archived one.
2417
2418 Scheduled automations never run with `auto_approve`, `trust_mode` or
2419 `allow_shell`. An automation saved earlier with any of them is paused the first
2420 time the scheduler reads it; its stored settings are left as saved. `GET
2421 /v1/automations` and `GET /v1/automations/{id}` report such a record with
2422 `status: "paused"` and a `paused_reason` sentence, and
2423 `POST /v1/automations/{id}/resume` answers `400` with that sentence until a
2424 `PATCH` has set all three settings to `false`. Resuming is then a separate
2425 call.
2426
2427 **Delayed triggers** (one-shot messages; the HTTP face of `send_later`)
2428 - `GET /v1/triggers?thread_id=&status=&limit=50` — newest first; `thread_id`
2429 filters by destination thread, `status` is one of `pending`,
2430 `dispatching`, `fired`, `canceled`, `failed`
2431 - `POST /v1/triggers` — `{"message", "fire_at" | "delay_minutes",
2432 "thread_id"?, "workspace"?, "owner_session_id"?}`; exactly one of `fire_at`
2433 (RFC 3339, in the future) or `delay_minutes` (>= 1). `owner_session_id`
2434 defaults to `thread_id` and is required without one. Returns `201` with the
2435 `DelayedTriggerRecord`; honours `Idempotency-Key` like `POST
2436 /v1/automations`
2437 - `GET /v1/triggers/{id}`
2438 - `DELETE /v1/triggers/{id}` — cancels a pending trigger; `409` once it has
2439 been admitted
2440
2441 A trigger with `destination_thread_id` fires into that thread exactly as an
2442 automation run does above. `send_later` called from inside a Runtime thread
2443 defaults its destination to that thread, so the reminder comes back to the
2444 same conversation; `thread_id: ""` keeps the old new-task-thread behaviour.
2445 The `automation` tool accepts the same `thread_id`. From a tool, `thread_id`
2446 can name only the calling thread (`"current"` or its id); targeting another
2447 thread is a Runtime API operation.
2448
2449 When an automation or trigger names a destination thread, the Engine
2450 publishes typed events on that thread's stream: `automation.created`,
2451 `automation.updated` (`automation_id`, `name`, `rrule`, `status`,
2452 `next_run_at`, `paused_reason`), `trigger.scheduled`, `trigger.canceled` and `trigger.fired`
2453 (`trigger_id`, `message`, `fire_at`, `status`, `task_id`). They are
2454 notifications for captions, not model input.
2455
2456 **Automation mutation preconditions.** `GET /v1/runtime/info` advertises
2457 `capabilities.automation_mutation_preconditions: true`; require it before
2458 relying on the behavior below (older Engines ignore both inputs).
2459
2460 - Every `AutomationRecord` carries an integer `revision`: `1` on create, `+1`
2461 on each `PATCH`, `pause` and `resume`; legacy records read as `0`. Scheduler
2462 bookkeeping (`next_run_at`, `last_run_at`) does not change it.
2463 - `expected_revision` is an optional precondition on `PATCH`, `run`, `pause`
2464 and `resume`: a JSON body field on `PATCH`, or the `?expected_revision=N`
2465 query parameter on any of the four. On mismatch nothing is written and the
2466 response is `409` with
2467 `{"error":{"code":"revision_conflict","current_revision":N,...}}`. Omitting
2468 it behaves as before.
2469 - `Idempotency-Key` (1-255 visible ASCII characters) is optional on `POST
2470 /v1/automations`, `PATCH`, `run`, `pause` and `resume`. The first successful
2471 response (2xx) is persisted in `idempotency.json` beside the automation
2472 store, bounded to 1024 entries and a 24 hour TTL. A retry with the same key
2473 and identical request returns the stored status and body with
2474 `Idempotency-Replayed: true` and performs no second create or run. The same
2475 key with a different request is `422` `idempotency_key_reuse`. Failed
2476 attempts are not stored, so they can be retried. Keys are scoped to the
2477 route and automation id. If the record cannot be persisted after the
2478 mutation committed, the success response is still returned (the failure is
2479 logged), so a retry of that request is not deduplicated. An unparseable
2480 `idempotency.json` is renamed to `idempotency.corrupt-<timestamp>.json` and
2481 that request fails with `500`; later requests start from an empty store.
2482 `DELETE` is not covered.
2483
2484 **Operate** (always-on named operation; same `OperateRecord` as CWC
2485 `20de981` / PR #284)
2486
2487 - `GET /v1/operate` — current operation + plan board
2488 - `POST /v1/operate` — create (`direction`, optional `burnRate`)
2489 - `PATCH /v1/operate` — steer direction, `burnRate`, or `leadPlan`
2490 - `PUT /v1/operate/plan` — set `leadPlan` (`{ slices: [...] }`)
2491 - `POST /v1/operate/keepalive` — observe spend / burn; never stops
2492 - `POST /v1/operate/cancel` — explicit cancel (`/v1/operate/stop` aliases);
2493 also pauses the `cw-operate` keepalive so nothing keeps spending after cancel
2494 - `POST /v1/operate/auto-merge/check` — call landed
2495 `scripts/check-auto-merge.py --repo --pr --agent` (does not merge)
2496
2497 The operation record (`current.json`) is persisted under a cross-process
2498 file lock with atomic temp+rename writes; every PATCH / keepalive / plan
2499 save reloads the latest state inside the lock, so concurrent saves merge
2500 instead of losing writes. A `PATCH` that changes `direction` invalidates
2501 the recorded `leadPlan` (workers stop executing superseded slices) and
2502 pulls the keepalive lead run forward to re-plan. `POST /v1/operate`
2503 installs the hourly `cw-operate` keepalive and kicks its first lead-plan
2504 run immediately instead of waiting out the first recurrence; credentials
2505 resolve through the normal Z.ai provider resolution (config, `api_key_env`,
2506 secret store, or provider env vars — blank values count as missing).
2507
2508 `burnRate` is `{ "kind": "usd_per_hour", "amountUsdPerHour": number }`,
2509 a positive number, or `null` (unbounded). Status is
2510 `planning | running | idle_blocked | cancelled`. Pace
2511 (`unbounded | hold | throttle | widen`) is not a status: over-target
2512 throttles, under-target widens, no wallet-cap stop. Idle-blocked only
2513 for empty direction, awaiting lead plan, missing credentials, or a
2514 human gate. Auto-merge is `scripts/check-auto-merge.py --repo … --pr …
2515 --agent …` from codewhale-ops `origin/main` (exit 0), then
2516 `scripts/auto-merge-pr.py`. Do not invent a second checker.
2517
2518 **Workspace trust** (the persisted project decision)
2519 - `GET /v1/workspace/status` reports `workspace_trusted`: whether the server’s workspace is trusted in the discovered user config. Project skills and commands consult this decision. Project hooks and project MCP configuration require both workspace trust and separate approval of the exact file (`/hooks review`, `/mcp review`).
2520 - `POST /v1/workspace/trust` with `{"trusted": true|false}` records that decision and answers `{workspace, workspace_trusted, config_path, message}`.
2521
2522 The handler reuses `config::set_workspace_trust`, the writer behind `/trust on|off --save`, and reads the decision back through `is_workspace_trusted`. The request accepts no path; it applies only to the server’s admitted workspace. `config_path` identifies the document written. Both read and write use default config discovery, including configured environment overrides; a runtime’s explicit `--config` argument does not select this trust document.
2523
2524 Project skills and commands consult trust at their existing load or turn boundaries. Project hooks and project MCP servers (when `.codewhale/mcp.json` is already approved) also need their separate digest approval and recheck authority before execution; once approved, restart the engine or reload the pool to rebuild project MCP connections, as this request does not disconnect an existing pool or interrupt a running turn. Project instruction files such as `AGENTS.md` and project rules are loaded by the existing context loader independently of this flag, so revoking workspace trust does not remove those instructions or their persisted history.
2525
2526 This persisted project decision is separate from a thread’s `trust_mode` / Full Access and from `/trust add <path>` external-path grants. `/trust on|off --save` changes session file-tool trust and the persisted project record. This HTTP route changes only the persisted project record. Its POST requires the same Runtime write authority as other state-changing routes; watch device tokens can read status but cannot write trust.
2527
2528 **Introspection**
2529 - `GET /v1/workspace/status`
2530 - `GET /v1/workspace/files/search?query=<partial>&limit=<1-100>` (see workspace file suggestions above)
2531 - `GET /v1/workspace/files?path=<dir>&limit=<1-2000>`, `GET /v1/workspace/files/read?path=<file>&offset=&limit=`
2532 and `PUT /v1/workspace/files` (see workspace files and session artifacts above)
2533 - `GET /v1/modes` (see Conversation modes)
2534 - `GET /v1/skills`
2535 - `GET /v1/skills/{name}` — one skill's routing metadata (`source`,
2536 `invocation`, `aliases`, `bundled_tier`, `enabled`) plus its full
2537 `SKILL.md` body, so a client can compose an activation instruction for its
2538 own next turn the way TUI's `/skill <name>` does. `404` for a name no
2539 discovery root holds; `403` for a plugin snapshot whose authority is no
2540 longer current; native rows whose file has since been deleted also `404`
2541 rather than serving the stale body. Advertised as
2542 `capabilities.skill_detail` on `GET /v1/runtime/info`, which is the source a
2543 client should use rather than probing this path: a `404` here means "no such
2544 skill" and is indistinguishable from "no such route".
2545 - `GET /v1/apps/mcp/servers` — each row reports `connected` and
2546 `has_connection_backoff`; while a server is cooling down after a failed
2547 connect it also carries `last_error`, that attempt's diagnosis (at most 2048
2548 characters). `last_error` is omitted when the server is ready or connecting,
2549 when its configuration changed since the failure, and when its reviewed
2550 plugin authority no longer holds.
2551 - `GET /v1/apps/mcp/tools?server=<optional>`
2552
2553 Skill activation toggles are persisted under a cross-process transaction lock.
2554 Each mutation reloads and merges the latest exact-name state before an atomic
2555 write, and `GET /v1/skills` refreshes that shared state so another Codewhale
2556 process's successful toggle is visible without restarting the Runtime API.
2557
2558 Skill rows on `GET /v1/skills` carry `invocation`, `aliases`, and
2559 `bundled_tier` alongside the fields they always carried, so a client can build
2560 a picker, autocomplete, or activation gate without a second request per row.
2561
2562 **Desktop side browser.** A desktop host registers its side-browser MCP server
2563 with `POST /v1/apps/mcp/desktop-browser` (`{url, bearer, signature}`, signed by
2564 the host key the Engine was launched with). Agent calls to that server are
2565 fenced by the Codewhale account that admitted the turn. When a person's turn
2566 starts, the Engine records who is signed in (the account and its login
2567 session, or signed out). A later `codewhale-browser` tool call from that turn,
2568 its sub-agents or its programs is refused with a permission error saying
2569 nothing was sent once the signed-in account differs: after a sign-out, a
2570 sign-in, a replaced account or a new login session. A turn whose account could
2571 not be read is refused the same way; token refresh does not trip the fence.
2572 Known limits of this interim fence: the Engine sends the browser server no
2573 caller identity, registrations carry no generation (a delayed older
2574 registration can still replace a newer one), account states the desktop keeps
2575 to itself (development sessions, replay, an unreachable account service) are
2576 not observed, and a Platform-side revocation counts only once a refresh writes
2577 it to the local account store.
2578
2579 **Usage** (token/cost aggregation across threads)
2580 - `GET /v1/usage?since=<rfc3339>&until=<rfc3339>&group_by=<day|model|provider|thread>`
2581
2582 `since` / `until` are inclusive RFC 3339 timestamps and may be omitted (no
2583 bound). `group_by` defaults to `day`. Buckets are sorted by ascending key.
2584 Empty time ranges produce empty `buckets` (never a 404). Cost is computed via
2585 the model→pricing map; turns whose model has no pricing entry contribute
2586 tokens but `0.0` cost (#564).
2587
2588 ```json
2589 {
2590 "since": "2026-04-01T00:00:00Z",
2591 "until": "2026-04-30T23:59:59Z",
2592 "group_by": "day",
2593 "totals": {
2594 "input_tokens": 12345,
2595 "output_tokens": 6789,
2596 "cached_tokens": 0,
2597 "reasoning_tokens": 0,
2598 "cost_usd": 0.012,
2599 "turns": 42
2600 },
2601 "buckets": [
2602 {
2603 "key": "2026-04-30",
2604 "input_tokens": 1234,
2605 "output_tokens": 678,
2606 "cached_tokens": 0,
2607 "reasoning_tokens": 0,
2608 "cost_usd": 0.001,
2609 "turns": 3
2610 }
2611 ]
2612 }
2613 ```
2614
2615 ### Native client routes
2616
2617 These families serve native clients over the same bearer-token
2618 transport. They reuse the runtime's existing authorities — the engine's shell
2619 manager, the durable thread store, the workspace confinement layer, the
2620 config's credential plumbing — and add no second runtime, session store,
2621 scheduler, or credential store.
2622
2623 **Terminal sessions** (the persistent Engine-owned shell)
2624
2625 The jobs family above runs one command per job. A terminal pane needs the
2626 *other* authority: the stateful PTY-backed shell the agent's own terminal
2627 tools drive, which keeps cwd and environment across inputs. Each shell belongs
2628 to the thread whose turn started it, in that thread's workspace: two
2629 conversations that both use `term-1` in one folder get two shells. These
2630 routes attach to those shells and never create one, because conjuring a shell
2631 from an HTTP request would give the client a terminal the Engine does not
2632 know about. Input is attributable by route: `input` is the client's writer,
2633 `terminal_send` is the agent's.
2634
2635 - `GET /v1/threads/{id}/terminals` → `{thread_id, workspace, instance,
2636 terminals: [{terminal_id, name, state, running, exit_code, updated_at}]}` —
2637 the thread's live shells, newest activity first. `terminal_id` is issued
2638 when the shell starts and is never reused; the agent's terminal tool results
2639 carry the same value as `terminal_session_id`, and `terminal_reset` also
2640 reports `previous_session_id`. `instance` names this Engine process's
2641 terminal registry. While a shell lives, `state` is its latest command's
2642 state (`running`, `idle`, `canceled`, `failed`, `stale_lost` or `reset`);
2643 once the shell itself has ended it is `exited`, `running` is false and
2644 `exit_code` holds the shell's status
2645 - `GET /v1/threads/{id}/terminals/{terminal_id}/output?cursor=<bytes>&
2646 max_bytes=<1-64KiB>&format=<base64|text>` — the resumable byte stream.
2647 `{terminal_id, offset, next_cursor, total, dropped, gap, encoding, data,
2648 running, exit_code}`: pass `next_cursor` back to continue; reads never
2649 consume, so several clients may hold independent cursors; `gap` is true and
2650 `offset` exceeds `cursor` when the 512 KiB ring already discarded the bytes
2651 asked for (`dropped` counts them), and a cursor past `total` is answered from
2652 `total` rather than echoed back
2653 - `POST /v1/threads/{id}/terminals/{terminal_id}/input` — `{ "data",
2654 "encoding"? }`, `base64` by default (exact bytes) or `text` for UTF-8 →
2655 `{ "terminal_id", "written" }`. It needs the thread's shell consent (`403`
2656 `thread_shell_disabled`) and the loaded shell policy (`403`). When the
2657 thread's current posture requires a sandbox, a shell that was not started
2658 under exactly that policy refuses input (`403` `terminal_posture_changed`);
2659 an exited shell refuses it too (`409` `terminal_exited`). A lone ETX
2660 (Ctrl-C) while the agent's command runs takes the confirmed-interrupt path,
2661 so the agent's wait sees exit status 130; if the shell does not confirm it
2662 within 2 seconds the call answers `500` saying the interrupt was sent, and
2663 the client must not send it again on its own
2664 - `POST /v1/threads/{id}/terminals/{terminal_id}/resize` — `{ "rows", "cols" }`
2665 → the kernel window the child draws for
2666 - `POST /v1/threads/{id}/terminals/{terminal_id}/kill` — end the shell →
2667 `{ "terminal_id", "killed" }`, with `killed: false` when it had already
2668 exited; observe the exit through `output` (`running` / `exit_code`) rather
2669 than the acknowledgement
2670
2671 Every call resolves the thread's recorded workspace again, including directory
2672 aliases. An unknown thread returns `404`. A missing workspace or a path that
2673 fails validation during resolution returns `409` `thread_workspace_unavailable`.
2674 The Engine returns `404` `terminal_not_found` if the shell belongs to another
2675 thread or workspace, has been reset, or predates the current Engine process. The Engine never substitutes a shell with the same name.
2676
2677 Reconnect and restart semantics:
2678
2679 - **Reconnect** (a dropped connection, a reopened pane or window, or a client
2680 app restart while the Engine kept running): list the thread's terminals,
2681 confirm `instance` is the one recorded, and resume each `terminal_id` from
2682 its stored cursor. Only retained output is replayed; `gap` reports what the
2683 ring lost.
2684 - **Reset** (`terminal_reset`): the shell is killed and a new one starts under
2685 the same name with a new `terminal_id`. The old identity is `404`; the list
2686 shows the replacement, and a client switches to it only on the person's
2687 choice.
2688 - **Exit**: the identity stays listed with `running: false` and its
2689 `exit_code` until the agent resets it or the Engine restarts.
2690 - **Engine restart**: live shells end with the process. The list reports a
2691 different `instance` and none of the old identities, which answer `404`. No
2692 shell is recreated and no command is rerun; a later `terminal_run` with the
2693 same name starts a new identity.
2694 - **Input across a failure**: input already sent cannot be retracted. A client
2695 that loses the connection before the response cannot know whether the bytes
2696 reached the shell and must not resend them automatically.
2697
2698 `GET /v1/runtime/info` advertises `thread_scoped_terminals`. It is `false` on
2699 Windows and OpenHarmony builds today: the owner is Unix-only, those routes
2700 answer `501`, and a client should gate its terminal controls on the flag
2701 rather than discovering it from a failed request. The name-addressed routes
2702 `/v1/terminal/{name}/*` and their `terminal_stream`, `terminal_input`,
2703 `terminal_resize` and `terminal_kill` flags were retired in 0.10.3: a name at
2704 the server's workspace could reach another thread's shell, so those paths now
2705 answer `410` `terminal_route_retired`. Known limitations, stated because a
2706 reader would otherwise assume them: there is no `wait_ms` long poll (poll the
2707 cursor), scrollback dropped by the ring is gone with the process, shells
2708 started outside a runtime thread (the TUI dock, headless runs) have no route
2709 here, deleting a thread does not end its shells (they run until the Engine
2710 exits), and the `@codewhale/runtime-sdk` package has no terminal client
2711 wrapper yet — the raw routes are the contract for now.
2712
2713 **Jobs** (operator-scoped shell jobs; the terminal surface)
2714 - `GET /v1/jobs` — every live and known-stale job across all threads
2715 - `GET /v1/threads/{id}/jobs` — jobs owned by one thread's manager:
2716 model-launched, subagent-launched, and client-launched together
2717 - `POST /v1/threads/{id}/jobs` — `{ "command", "cwd"?, "timeout_ms"?,
2718 "tty"?, "env"? }` → `201 { "job" }`; runs as a background shell under the
2719 thread's projected sandbox policy. `tty: true` merges stderr into stdout
2720 and gives the command a terminal (required for interactive programs);
2721 background jobs are never killed at `timeout_ms`. A relative `cwd`
2722 resolves against the thread workspace. Outside trust mode `cwd` must stay
2723 inside it after symlinks resolve (`403` otherwise): unlike the shell tool,
2724 this route does not follow `workspace_follow_symlinks` or `/trust add`
2725 roots, so a symlink leading out of the workspace is refused. The job runs
2726 in the resolved directory that was checked (a later symlink retarget does
2727 not move it); a `cwd` that resolves to a non-UTF-8 path is a `400`
2728 - `GET /v1/threads/{id}/jobs/{job_id}` — one job's status + metadata
2729 - `GET /v1/threads/{id}/jobs/{job_id}/output?stream=<stdout|stderr>&cursor=
2730 <bytes>&max_bytes=<1-512KiB>&wait_ms=<0-30s>&format=<base64|text>` — the
2731 resumable byte stream. `{job_id, stream, offset, next_cursor, total,
2732 dropped, encoding, data, status, exit_code, done}`: pass `next_cursor`
2733 back to continue; `wait_ms` long-polls for new bytes on a running job;
2734 `done` means a terminal status and nothing left past the cursor
2735 - `POST /v1/threads/{id}/jobs/{job_id}/stdin` — `{ "data", "encoding"?,
2736 "close"? }`: `data` is UTF-8 text by default or `base64`, `close: true`
2737 sends EOF; works for PTY and piped jobs → `204`
2738 - `POST /v1/threads/{id}/jobs/{job_id}/kill` — bounded SIGTERM → SIGKILL
2739 escalation on the process group → `{ "job", "result" }` with the final
2740 snapshot
2741 - Owner-held jobs: the create body may add `owner_keepalive_seconds`
2742 (1-3600) and `deadline_at` (RFC 3339, at most 24 h ahead). The Engine stops
2743 the job with its whole process group when the owner misses a keepalive
2744 (`stop_reason: "owner_lost"`) or the deadline passes
2745 (`stop_reason: "deadline"`); a keyed operation's terminal record carries the
2746 same `stop_reason`. `POST /v1/threads/{id}/jobs/{job_id}/keepalive` renews
2747 the keepalive → `{ "job" }`; `409 job_keepalive_expired` once it lapsed
2748 (final), `409 job_not_held` without one, `409 job_not_running` after exit.
2749 Job views carry `owner_keepalive_seconds`, `keepalive_expires_at`,
2750 `deadline_at`, `stop_reason`, and `last_progress_at` (newest output, or the
2751 start) while running. An Engine without this support refuses the fields
2752 with `422`.
2753
2754 Reads are non-consuming: several clients may hold independent cursors, and
2755 polling never steals output from the engine's own delta consumer. The
2756 buffer is bounded with exact drop accounting — a reader whose `cursor`
2757 falls behind the retained window gets `offset` past it and `dropped > 0`,
2758 and must re-anchor. Evicted jobs keep a tail snapshot which the output
2759 route serves as the final retained window. Jobs are scoped to the thread
2760 that created them and are killed when that thread is removed; the engine's
2761 background commands use the same per-thread manager, so `GET /v1/jobs` is
2762 also how a client sees model-spawned work.
2763
2764 **Durable client job operations** (capability `job_operations`)
2765
2766 Authorized `GET /v1/runtime/info` supplies `job_operation_store_id`, the
2767 persisted runtime store identity. It survives Engine updates and restarts;
2768 it is a namespace, not a credential. Unauthorized discovery returns null.
2769 Keyed job creation adds all four fields to the existing POST body:
2770 `operation_key` (a fresh UUID v4 retained before submission), `purpose`
2771 (`setup`, `run`, `archive` or `command`), `expected_store_id`, and
2772 `expected_workspace`. The store must match the current store, and the workspace
2773 assertion must match the admitted thread workspace; otherwise dispatch refuses
2774 `409 job_operation_store_changed` or `409 job_operation_workspace_changed`.
2775 These assertions never move a thread. Omitting all four retains the legacy
2776 `201 {job}` contract.
2777
2778 A new keyed request returns `201 {job, operation, request_fingerprint}`. The same key and exact
2779 normalized request return `200` with the existing operation and never spawn
2780 again, including after restart or a lost response. Changing the bound request
2781 returns `409 job_operation_mismatch`. `job` may be null when the durable
2782 receipt survives without its live handle or retained output. The operation is:
2783
2784 ```json
2785 {
2786 "id": "opaque-receipt-id",
2787 "store_id": "runtime-store-id",
2788 "thread_id": "thread-id",
2789 "workspace": "/canonical/workspace",
2790 "cwd": "/canonical/launch-directory",
2791 "purpose": "run",
2792 "status": "running",
2793 "job_id": "shell-job-id",
2794 "job_status": null,
2795 "exit_code": null,
2796 "created_at_ms": 1794000000000,
2797 "updated_at_ms": 1794000000000
2798 }
2799 ```
2800
2801 `status` is `running`, `completed`, `rejected` or `unknown`. A completed receipt has a
2802 terminal `job_status` (`Completed`, `Failed`, `Killed` or `TimedOut`) and a
2803 nullable exit code; success requires `Completed` and exit code zero. Timestamps
2804 are Unix milliseconds; `updated_at_ms` is the last persisted transition, not
2805 proof of when an unknown outcome occurred. The opaque receipt ID does not
2806 expose the original operation key.
2807
2808 `request_fingerprint` binds the original request, including its requested
2809 workspace spelling; the operation's workspace and cwd remain canonical. It is
2810 lowercase HMAC-SHA256, keyed by the operation UUID, over UTF-8 JSON for
2811 `[2, thread_id, expected_workspace, trimmed_command, cwd_or_null, timeout_ms,
2812 tty, sorted_environment_pairs, purpose]`. Command trimming uses Unicode
2813 White_Space; environment pairs sort by UTF-8 key bytes. Omitted timeout is
2814 120000, omitted cwd is null and omitted tty is false. Persist the expected
2815 fingerprint before POST, and compare it on response and exact-key GET recovery
2816 before accepting a receipt or clearing a pending intent. An alias is not a
2817 reason to compare the canonical receipt path literally with the requested
2818 spelling. A missing or mismatched binding stays unconfirmed; do not re-POST
2819 automatically. The UUID and fingerprint do not provide encryption or protect
2820 low-entropy request values from someone who obtains both.
2821
2822 A `rejected` receipt proves the command never started: its job fields are all
2823 null. The shell executor supplies this typed witness only for audited failures
2824 before launch, such as PTY allocation or a working-directory check. It is a
2825 terminal tombstone, so the same key returns it without retrying; a new key can
2826 try again after the problem is fixed. The POST refusal uses `409
2827 job_operation_rejected`. Spawn-wrapper and post-launch failures remain unknown
2828 unless a trustworthy witness proves otherwise.
2829
2830 - `GET /v1/job-operations` and `GET /v1/threads/{id}/job-operations` return
2831 `{operations: [...]}`, including records whose workspace folder is gone.
2832 - `GET /v1/threads/{id}/job-operations/{operation_key}` returns the same
2833 `{job, operation, request_fingerprint}` envelope. A storage or admission error is not an empty
2834 list or proof of absence.
2835 - Contended admission returns `409 job_operation_pending`. A new keyed
2836 setup/run/archive overlapping an active keyed workspace script returns
2837 `409 job_operation_busy`. An overlapping unconfirmed operation refuses
2838 every new job, including legacy requests, with `409
2839 job_operation_unconfirmed`; worktree removal is fenced as well.
2840
2841 The existing runtime thread store atomically records intent before spawning;
2842 the existing shell manager remains the execution authority. A completion
2843 observer and reads persist verified terminal parent status without consuming
2844 output. Durable records contain a keyed request fingerprint rather than raw
2845 commands, environment values or operation keys. A missing live handle,
2846 different owner generation or crash around dispatch remains `unknown`, never
2847 permission to repeat the command. New job IDs use full UUIDs; clients must
2848 treat them as opaque. This is not an exactly-once OS transaction, durable
2849 output capture, automatic unknown-outcome recovery or a phased archive
2850 transaction. Detached descendants, agent/tool launches and other stores remain
2851 outside this API operation fence.
2852
2853 Admission resolves one canonical workspace before project shell policy checks
2854 and uses it for policy and cwd resolution. It rechecks the requested root and
2855 launch directory before recording intent. These pathname checks do not provide
2856 a directory-handle guarantee against replacement after the final check.
2857
2858 Thread deletion and empty-thread discard share job admission and refuse a
2859 thread whose durable client job operation is running or unconfirmed. Stop the
2860 known job and wait for its terminal receipt before deleting the conversation;
2861 an unknown outcome requires recovery rather than silently dropping the fence.
2862 Completed and rejected receipts remain in the global operation list after
2863 thread deletion.
2864
2865 **Commands** (typed command catalog, APPS-28)
2866 - `GET /v1/commands` — `{commands: [...]}`: every registered slash command,
2867 builtin and user, as the TUI's own registry holds it. Per entry: `name`,
2868 `aliases`, `summary` and `usage` (English source text — localizing is the
2869 client's surface), `subcommands` (the literal verbs the usage line
2870 declares), `takes_arguments`, `kind` (`builtin` registered code, or `user`
2871 expanding a stored template), `binding` (`host` runs locally and never
2872 reaches the model; `prompt` expands into the request the model sees),
2873 `discovery` (`primary` / `advanced` / `compatibility`, builtins only),
2874 `hidden` for rows the product does not advertise, and `shadowed_by` /
2875 `shadowed_aliases` where a user command has taken a builtin's spelling.
2876
2877 Each entry also carries the composer argument shape, computed the way the
2878 TUI composer computes it, so a client does not re-derive it from `usage`
2879 (#6230):
2880 - `requires_argument` — the usage line mentions any argument, required or
2881 optional.
2882 - `requires_required_argument` — the usage line has a `<required>` argument
2883 outside every `[optional]` group.
2884 - `composer_wants_trailing_space` — accepting the command leaves a trailing
2885 space for its arguments.
2886 - `palette_runs_directly` — the palette runs the command on selection
2887 instead of pasting it into the composer.
2888 - `show_in_empty_discovery` — the command is listed when the slash menu
2889 opens with no filter text.
2890
2891 User commands derive these from `takes_arguments`: their arguments are
2892 never required, a template that takes arguments waits in the composer and
2893 one that does not runs directly, and a `hidden` template stays out of empty
2894 discovery.
2895
2896 The same registry the TUI palette reads, so a desktop palette can be
2897 checked against it instead of drifting from it. Two rules a client must
2898 respect: a `binding: "host"` row is never submitted as a model prompt, and
2899 a user command shadowing a builtin name wins that spelling.
2900
2901 - `POST /v1/threads/{id}/commands/builtin` — run one terminal built-in
2902 against the thread and return its own answer: `{name, text, is_error,
2903 text_only}`. The body is `{name, args?}`, where `name` takes the canonical
2904 spelling or an alias, with or without the leading slash.
2905
2906 Only read-only diagnostics the server can answer from thread state are
2907 served (`/system`, `/tokens`, `/cost`); the served set lives in the
2908 terminal host and is gated a second time by the data each portable handler
2909 declares it needs, so a route cannot widen without the host widening
2910 first. Any other name — including one no host knows — answers 404. A
2911 thread whose engine is not loaded, or that has no live context estimate
2912 yet, answers 409 rather than printing zeros; the route never starts an
2913 engine. `/system` reports the effective system prompt the engine sends, and
2914 `/tokens` counts the live session transcript. Like every other POST route,
2915 it answers 403 to a watch-only device token, so a watch client cannot read
2916 `/tokens` or `/cost` through it.
2917
2918 `text_only` is `false` when the command also asked the terminal host for an
2919 action (a balance fetch, a snapshot restore): the text is still what the
2920 command answered, but no client can perform that action on the host's
2921 behalf. These executions keep no command receipt — every served handler is
2922 pure over the snapshot — so a client must not look for one. Anything that
2923 mutates the session stays a terminal-side command.
2924
2925 **Plugins**
2926 - `GET /v1/apps/plugins` — `{workspace, plugins: [...], registry_diagnostics: [...],
2927 validation_clean}`: installed and workspace plugins discovered for this
2928 workspace. Alongside `state`, `enabled`, `trust_status`, and `active`, each
2929 entry carries attribution, isolation, and host-service reachability:
2930 - `approved_by` (`PluginApprover | null`): who recorded the active trust
2931 review — `null` when untrusted/unreviewed, `{"kind": "person", "via":
2932 "terminal" | "app" | "approval_card"}`, `{"kind": "agent", "posture",
2933 "workspace", "thread_id"?, "turn_id"?, "tool_call_id"?}`, or
2934 `{"kind": "command_line"}` (CLI/non-interactive review, never shown as
2935 person-reviewed).
2936 - `enabled_by` (`PluginApprover | null`): who last turned the plugin on
2937 (`null` when disabled or unrecorded).
2938 - `cohort`: `{"kind": "reviewed"}` or `{"kind": "agent", "workspace":
2939 "<normalized-path>"}`. Agent-approved plugins stay in an isolated cohort
2940 scoped to one workspace rather than joining person-reviewed plugins.
2941 - `outside_reach` (`bool`): `true` when an agent-approved plugin belongs to
2942 another project workspace, keeping `active: false` in this workspace.
2943 - `host_services`: array of `{"service", "state": "can_use" |
2944 "not_offered", "withheld_by"?: [{ "id", "name" }]}`. `withheld_by` is
2945 omitted when empty; when present, `withheld_by` means the service is off for
2946 now because those active peers do not include that host service in their own
2947 review.
2948 - `GET /v1/apps/plugins/{selector}` — flattens the summary entry with bundle
2949 metadata (`repository`, `license`, `keywords`, `staged`), `review` (confirmation
2950 `token`, capabilities, and optional `host_services` preview for interactive
2951 person review), `reviewed_at` (`string | null`, RFC 3339 timestamp of the
2952 latest recorded review, distinct from when the plugin was enabled), and
2953 `review_history` (newest-first list of `{"reviewed_at": "<rfc3339>",
2954 "approved_by"?: PluginApprover}`). Re-reviewing an agent-approved plugin as a
2955 person via `POST /v1/apps/plugins/{selector}/trust` replaces `approved_by`
2956 with the person decision and moves `cohort` to `{"kind": "reviewed"}` while
2957 keeping the earlier entry in `review_history`. `ui_slots` lists the plugin's
2958 currently admitted client UI seats as
2959 `{"slot": "<seat>", "dsh_slot"?: "<DSH key>"}`. Pass the optional DSH key
2960 back on the `ui` call. That call also requires a loopback request and valid
2961 request context. An empty array means the plugin has no admitted seat. For
2962 an inactive plugin, `ui_slots_unavailable` reports activation before the
2963 runtime inspects the UI declaration. For an active plugin, it reports a
2964 rejected UI declaration with a message and an optional code. An active
2965 plugin with no client UI omits the field.
2966
2967 **Plugin index**
2968 - `GET /v1/apps/plugin-index` — `{workspace, items: [...], unavailable: [...],
2969 problems: [...]}`: one list across every plugin, skill, connector, hook and
2970 hand-written command. It is a projection: each item's `row` is the row its
2971 owner's own route returns (`/v1/apps/plugins`, `/v1/apps/plugins/catalog`,
2972 `/v1/skills`, `/v1/apps/mcp/servers`, `/v1/hooks`, `/v1/commands`), and
2973 `owner` names that route. Per item: `id`, `kind` (`plugin`, `skill`,
2974 `connector`, `hook`, `command`), `name`, `description`, `source`
2975 (`built_in`, `user`, `project`, `other_app`, `runtime`, `plugin`), `state`
2976 (`enabled`, `disabled`, `needs_review`, `needs_sign_in`, `unavailable`) and
2977 `labels` (what the item adds: `skill`, `connector`, `hook`, `command`,
2978 `tool`, `profile`). A plugin item also has `adds` (`skills`, `connectors`,
2979 `hooks`, `commands`, `profiles`: names, not rows), and what a plugin adds is
2980 not listed a second time as an item of its own. A built-in switch is a
2981 `plugin` item with a `tier` and no labels. `/v1/commands` rows carry
2982 `plugin_id` (the same id as `/v1/apps/plugins`, and the `plugin:<id>` item)
2983 for a command a plugin adds, and `workspace_sourced` for one read from the
2984 project; a command item's `plugin` is that id. An owner that fails is named in
2985 `unavailable` and the other kinds still list; `problems` carries the owners'
2986 load warnings. Names under `adds` are file names, so a profile's `id` inside its
2987 file can differ; a command another plugin registers through the plugin host
2988 is an item with `source` `plugin`. For an active plugin `adds.commands` comes
2989 from the `/v1/commands` rows; for any other plugin, and for `hooks` and
2990 `profiles`, it is the file names found in the bundle, at most 512 per kind,
2991 with names holding control characters left out; a cut list is reported
2992 under `problems`. A hook's row names no plugin, so `adds.hooks` stays file
2993 names. `tool` means the plugin declares native or language-server components;
2994 a screen a plugin draws is not labelled yet.
2995
2996 **Hooks**
2997 - `GET /v1/hooks[?thread_id=...]` — `{workspace, enabled, hooks: [...],
2998 problems: [...]}`: the hook set Runtime API threads run for that workspace
2999 (the server workspace, or the named thread's). Per entry: `name`, `event`,
3000 `command` (credential-shaped values masked; every URL keeps only its scheme and host), `background`, `timeout_secs`,
3001 and `source` (`global` user config, `plugin` reviewed plugin, `project`
3002 trusted and approved `.codewhale/hooks.toml`). `problems` lists hooks
3003 rejected or warned about at load, one line each.
3004
3005 Every Runtime thread builds its engine with this set: `tool_call_before`
3006 can deny a call, `shell_env` applies to shell tools, and `tool_call_after`
3007 and `on_error` (for a failed tool) fire as observers, as they do in the TUI.
3008 Clients read this route instead of keeping a hook table of their own.
3009
3010 **Context** (per-thread context pressure, APPS-90)
3011 - `GET /v1/threads/{id}/context` — `input_tokens` (the conservative live
3012 estimate the visible meter uses), `billed_input_tokens` (last
3013 provider-counted prompt size when one exists), `window_tokens`,
3014 `output_cap_tokens`, `input_budget_ceiling`, `available_input_tokens`,
3015 `compaction_trigger_tokens`, `usage_percent` and `pressure`. Served by the
3016 live engine via `Op::GetContextBudget`. Every numeric field is nullable —
3017 a route that cannot express a bounded window reports `null` rather than an
3018 invented number — and `live: false` marks responses where the engine
3019 could not be loaded and only the store-recorded route's static window
3020 resolved.
3021 - `GET /v1/threads/{id}/context/standing` (capability
3022 `thread_standing_context`) — the standing-instruction receipt the live
3023 Engine session already holds, read-only. `schema_version`, `basis`
3024 (`installed_receipt`; `no_receipt` before the session has assembled one;
3025 `unavailable` with `live: false` when the engine could not be loaded),
3026 `estimator` with `estimated: true` (token counts are the conservative
3027 `max(chars/3, bytes/4)` estimate, not a tokenizer), `global_tokens`,
3028 `project_tokens`, `constitution_tokens`, `retained_block_tokens`, the
3029 resolved `budgets`, and `items[]` with `label`, `path`, `scope`, `origin`,
3030 `action` (`kept|trimmed|skipped|refused`), `limit` (`none`,
3031 `scope_budget`, `static_guard`, `file_ceiling`, `file_content`,
3032 `empty_file`, `rules_cap`, `rules_budget`, `duplicate_path`), `tokens_kept`,
3033 `tokens_dropped`, `bytes_kept`, `bytes_dropped`, `fallback_selected` and a
3034 typed `detail` (`kind` plus its numeric fields; never an error text).
3035 `items` holds at most 200 entries and `items_omitted` counts the rest.
3036 Paths are workspace-relative for project items (`../AGENTS.md` for a
3037 parent directory's file, `../.claude/CLAUDE.md` for one in its
3038 subfolder), `~/...` for global items under the home directory, and a bare
3039 file name otherwise; no absolute path is returned, and control characters
3040 in labels and paths arrive as `?`. `delivery.cap_bytes` is the
3041 65,536-byte limit on the instruction text before the preamble and
3042 escaping are added. When a workspace-instructions message was recorded,
3043 `delivery.delivered` gives `message_bytes` and `message_tokens` for the
3044 delivered reminder body (preamble included, runtime envelope excluded) and
3045 `truncated`; read truncation from `truncated`, never by comparing
3046 `message_bytes` with `cap_bytes`. The receipt itself does not include that
3047 cap. The totals, `budgets`, `items_omitted` and `delivery` keys appear
3048 only with `basis: installed_receipt`. `not_measured` lists what the Engine
3049 does not measure per item (`skills`, `agents`, `mcp_tool_schemas`,
3050 `memory`): show "not measured yet", never zero. An unknown thread is 404.
3051
3052 **Thread-scoped reads.** `GET /v1/git`, `/v1/changes`, `/v1/diff`,
3053 `/v1/workspace/diff`, `/v1/git/graph`, `/v1/workspace/files`,
3054 `/v1/workspace/files/search` and `/v1/workspace/files/read` accept an optional `thread_id`. With it, the route
3055 reads the workspace recorded on that thread (the runtime store's thread record
3056 is the only source) instead of the server's workspace, through the same
3057 confined paths. Omitting the parameter uses the server workspace. An unknown
3058 thread returns 404. The Engine resolves the recorded absolute directory path,
3059 including an alias selected when the thread was created. If the directory
3060 is missing or the path fails validation during resolution, the Engine returns
3061 409 with `error.code` `thread_workspace_unavailable`. `/v1/workspace/status`
3062 stays on the server workspace. Mutating git routes accept `thread_id` under
3063 `thread_scoped_git_writes`, and `PUT /v1/workspace/files` under
3064 `thread_scoped_file_writes`. Check that capability before sending a scoped
3065 write: an Engine without it ignores `thread_id` on `PUT /v1/workspace/files`
3066 and writes to the server workspace.
3067 Check the `thread_scoped_reads` capability on `GET /v1/runtime/info` before
3068 sending `thread_id`. Engine 0.10.4 advertises the capability for other reads
3069 and returns HTTP 400 for scoped file search. A client receiving
3070 that response should show that search is unavailable for this conversation.
3071 Retrying without the thread ID would search the server workspace.
3072
3073 **Status unavailable.** `GET /v1/workspace/status` and `GET /v1/git` report
3074 `status_unavailable: true` when `git status` could not be read (git failed to
3075 start or exited non-zero, or the repository's filter configuration could not be
3076 inspected). `dirty` and the change counts are then unknown, not zero, and clients
3077 must not present them as clean. Status reads neutralize clean/process filter
3078 drivers defined in the repository's own configuration (local or worktree scope);
3079 drivers defined only in the user's global or system configuration, such as Git
3080 LFS, keep working.
3081
3082 **Git** (workspace repository operations, APPS-106)
3083 - `GET /v1/git` — status detail: `git_repo`, `branch`, `head`
3084 (abbreviated, for display), `head_oid`, `index_token`, `revision`,
3085 `ahead`/`behind`, counts, per-file porcelain `files[]`
3086 (`{path, index, worktree, staged, status, old_path?, rev}`), `branches`,
3087 `remotes`. `files[].path` and `old_path` are workspace-relative, the same
3088 frame the write routes take; in a workspace that is a subdirectory of its
3089 repository, rows outside the workspace are not listed (the counts stay
3090 repository-wide). A rename out of the workspace appears as its source
3091 deletion. A rename can be reported by either side of the change, so that
3092 row is a worktree-side deletion (`index` a space, `worktree` `D`) when only
3093 the working tree moved, and an index-side one (`index` `D`) when the move
3094 is staged. A copy leaves its source in place and is never shown this way.
3095 Normal Git filters and untracked settings apply. Untracked
3096 directories stay collapsed; only a row naming the workspace itself is
3097 expanded to individually addressable files. The precondition tokens are
3098 opaque:
3099 - `head_oid` — the full HEAD commit id; `null` on an unborn branch or when
3100 HEAD cannot be read
3101 - `index_token` — the whole index (mode, blob, stage and path of every
3102 entry, repository-wide). A stat-only refresh by `git status` does not
3103 change it. Status remains best-effort on repository read failures;
3104 unavailable tokens are `null`, and broken HEADs cannot satisfy guards
3105 - `files[].rev` — one row: its index entries plus the working-tree state
3106 of every file it covers (including a rename's in-workspace source).
3107 Content tokens (`c-…`) include file bytes, the executable bit on Unix,
3108 symlink targets, and submodule HEAD/status. Submodule dirty contents
3109 are summarized by porcelain status, not recursively hashed; ordinary
3110 stage/discard do not write those contents. A read hashes at most
3111 64 MiB / 4,096 files; rows past that budget or containing a file over
3112 16 MiB carry a display-only size-and-mtime token (`s-…`). Those tokens
3113 cannot guard writes. Unreadable paths, paths beneath symlinked
3114 directories, special files and broken nested repositories have `rev: null`;
3115 other rows retain their tokens. Status never looks inside a submodule, so
3116 a row for one reports only a changed commit, not dirty contents; an
3117 unreadable tracked submodule is shown with `status: "unknown"`,
3118 `worktree: "?"`
3119 - `revision` — the whole tree: `head_oid`, `index_token`, every row's
3120 `rev`, including the working-tree state of rows outside a subdirectory
3121 workspace. `null` when any row is stat-only or unreadable, a repository
3122 read is incomplete, or untracked paths are hidden; whole-tree guarded
3123 writes are unavailable in that case. Clients must not silently omit a guard
3124 - `GET /v1/changes` — the same porcelain `files[]` projection plus
3125 `head_oid`, `index_token` and `revision`, minus repo chrome
3126 (branches/remotes): one authority, so the change list can never disagree
3127 with the status read
3128 - `GET /v1/diff?path=` — one file's unified `diff` against `base` (`HEAD`,
3129 or the empty tree on an unborn branch — which reads staged adds as new
3130 files). Covers staged+unstaged in one patch; `truncated` reports the
3131 512 KiB cap. An untracked file answers `untracked: true` with an empty
3132 diff — the client reads the file itself rather than mistaking it for
3133 unchanged
3134 - `GET /v1/workspace/customizations?workspace=<path>&thread_id=<optional>` (capability
3135 `workspace_customizations`) previews the current standing rule budgets, skill
3136 listing and saved agent definitions. The workspace must be an admitted runtime
3137 workspace, a recorded thread workspace or a trusted workspace. A supplied
3138 thread must belong to the requested root. An unknown or mismatched root returns
3139 HTTP 403. The preview uses a resolvable thread or default route for budget
3140 sizing and works without opening an Engine session. Rules report retained
3141 estimated tokens and aggregate budget across the global and project scopes.
3142 `rules.refused` is true when the measured rule losses trigger
3143 `[instruction_budget].policy = "refuse"`. The estimate precedes the live
3144 static-prefix check, which depends on the turn's prompt and tool catalog.
3145 The skill index reports its four-characters-per-token budget, exclusions,
3146 shortened descriptions and names-only entries for the listing. Preloaded
3147 skill bodies have a separate budget. Agent rows estimate saved instructions
3148 for each definition independently, before any agent runs.
3149 With a thread ID, `mcp_tools` reports the logical MCP definitions in the last
3150 prepared model request of the thread's latest settled turn when the Engine
3151 captured bounded server attribution. Each server has a tool count and an
3152 estimated token count using the session's JSON estimator. The response names
3153 the source turn and step. It opens no MCP connections and omits schema text.
3154 `not_measured` includes MCP tools when the evidence is unavailable, and
3155 dynamic agent definitions when present.
3156 Each breakdown holds at most 200 metadata rows. The response includes no
3157 instruction bodies, skill bodies or tool schemas.
3158 - `GET /v1/workspace/diff?limit=` — whole-tree patch (default 256 KiB,
3159 max 4 MiB) plus a complete `--numstat` `files[]` inventory
3160 (`{path, added, deleted}`) so every changed row renders even when the
3161 patch is truncated
3162 - `GET /v1/git/graph?limit=` — bounded commit rows (`id`, `short`,
3163 `parents`, `author`, `timestamp`, `refs`, `subject`); an unborn branch is
3164 an empty graph, not an error
3165 - `POST /v1/git/stage` `{ "paths": [...] }` or `{ "all": true }`;
3166 `POST /v1/git/unstage` same; `POST /v1/git/discard` `{ "paths": [...] }`
3167 (tracked paths only — no `all`, an untracked path fails closed);
3168 `POST /v1/git/commit` `{ "message", "all"? }`; stage, unstage, discard
3169 and commit also take an optional `expect` (below). Stage, unstage and
3170 discard also take `patch`: hunks of the one path in `paths`, with file
3171 headers `diff --git a/<path> b/<path>`, `--- a/<path>`, `+++ b/<path>`
3172 naming that workspace-relative path. Stage applies them to the index,
3173 unstage reverses them in the index, discard reverses them in the working
3174 tree (`git apply [--cached] [--reverse]`). Renames, copies, mode changes,
3175 creations, deletions and binary patches are refused, and a patch that no
3176 longer applies fails with git's message and writes nothing. `POST /v1/git/push`
3177 `{ "branch"?, "expect"?: { "head" }, "remote"?, "set_upstream"? }` pushes
3178 exactly one branch at one commit (*Push* below);
3179 `POST /v1/git/branch`
3180 `{ "name", "create"? }`
3181 - Every write above also takes `?thread_id=` (capability
3182 `thread_scoped_git_writes`) and then runs in that thread's recorded
3183 workspace instead of the server's, the same scope the read routes use. A
3184 thread whose workspace is missing or changed answers `409`
3185 `thread_workspace_unavailable`.
3186 - `GET /v1/worktrees?thread_id=` — `{repository, worktrees[]}` with
3187 `{path, branch, head, main, managed, locked, prunable}` from
3188 `git worktree list --porcelain`; `managed` marks the ones under
3189 `<repository>/.codewhale/worktrees/`. Capability `worktrees`.
3190 - `POST /v1/worktrees?thread_id=` `{ "branch", "base"? }` — validates the
3191 branch with `check-ref-format`, refuses a branch already checked out
3192 elsewhere (`409 branch_checked_out`) or an existing folder
3193 (`409 worktree_exists`), adds `/.codewhale/worktrees/` to the repository's
3194 `info/exclude` so the main checkout stays clean, and runs
3195 `git worktree add -b <branch> -- <repository>/.codewhale/worktrees/<slug> <base>`
3196 (`base` defaults to the main checkout's `HEAD`). Answers `201`
3197 `{path, branch, base, head, repository}`. A client then creates a thread
3198 with `workspace: path`.
3199 - `POST /v1/worktrees/remove?thread_id=` `{ "path" }` — archives a managed
3200 worktree: refuses unmanaged or main worktrees (`403`), a locked one
3201 (`409 worktree_locked`), active turns in it (`409 worktree_busy`) and
3202 uncommitted or untracked changes (`409 worktree_dirty` with `files[]`),
3203 then runs `git worktree remove` without `--force`. The branch and its
3204 commits stay. A worktree whose folder is already gone is removed with `--force` for that exact path; other prunable worktrees are untouched.
3205
3206 Worktree removal also refuses `409 worktree_busy` while this runtime tracks a
3207 running shell job whose launch directory overlaps the worktree. Removal and
3208 API job starts share admission with new turns, and retain their guards until
3209 the mutation finishes even if the HTTP request disconnects. This covers the
3210 same runtime manager's tracked jobs. Durable client job operations additionally
3211 fence unconfirmed overlapping dispatches in their shared store, including
3212 after Engine restart. Launch directories do not prove where a
3213 command later changes directory; escaped descendants, late independent
3214 subagent launches and other runtime managers or processes remain outside this
3215 guard. It is not an OS-wide process reservation.
3216
3217 Diffs and precondition token reads run through the hardened review command
3218 (filters, fsmonitor, hooks, lazy fetches and replace-objects neutralized).
3219 Porcelain status runs through the hardened status command: fsmonitor, hooks
3220 and the filter programs the repository itself configures are neutralized
3221 (the user's own global filters, such as Git LFS, keep working), and
3222 submodules compare by commit without a status inside them; writes run through
3223 the non-interactive command path
3224 (`GIT_TERMINAL_PROMPT=0`, BatchMode ssh) so a credential or host-key prompt
3225 can never hang a request. Path lists are workspace-relative under the same
3226 confinement as the file routes (traversal → 400, `.git` → 403), passed after
3227 `--` under `--literal-pathspecs`, so `src/*` names a file called `*` and is
3228 never a glob. (Unstage of the whole tree uses the `:/` root pathspec.)
3229 Mutations answer `{ok, output, status, current}`: the refreshed status and
3230 the full `GET /v1/git` detail, so a client re-reads nothing after an
3231 operation and can chain the next write from fresh tokens. A workspace that
3232 is not a repository answers `404`.
3233
3234 *Preconditions.* Stage, unstage, discard and commit accept
3235 `expect: { head?, index?, revision?, files? }`, built from the last
3236 `GET /v1/git`. Each present field is checked and an absent one is not;
3237 `head: null` means "HEAD must still be unborn". Without `expect` (or with
3238 `expect: {}`) a write behaves exactly as before. Recommended use:
3239
3240 | Operation | `expect` |
3241 | --- | --- |
3242 | stage / unstage `paths` | `{head, files: {path: rev}}` |
3243 | stage / unstage `all` | `{head, revision}` |
3244 | discard (always — it destroys edits) | `{head, files: {path: rev}}` |
3245 | commit | `{head, index}` |
3246 | commit `all` | `{head, revision}` |
3247
3248 Malformed preconditions answer `400` before anything runs: `head` must be a
3249 40- or 64-hex id or `null`; `index` and `revision` 64 hex (an explicit
3250 `revision: null` is refused); `files` values a content-safe `c-` rev (`s-`
3251 tokens answer `400`). `files` keys
3252 (workspace-relative; `dir/` and `dir` are the same key)
3253 must name exactly the requested paths, so no path is left unguarded by
3254 accident. `files` is refused with `all: true` (use `revision`) and on
3255 commit. An unknown key inside `expect` is rejected like any other unknown
3256 field. When the repository no longer matches, the route writes nothing and
3257 answers `409`:
3258
3259 ```json
3260 { "error": { "message": "The repository changed since it was read (HEAD moved; src/a.rs changed). Nothing was written; refresh and review again.",
3261 "status": 409, "code": "git_state_changed" },
3262 "stale": ["head", "files"], "stale_paths": ["src/a.rs"],
3263 "current": { "...": "the GET /v1/git detail" } }
3264 ```
3265
3266 `stale` lists the components that moved (`head`, `index`, `files`,
3267 `revision`); `stale_paths` the `files` keys whose `rev` changed. A client
3268 re-renders from `current`, keeps the user's selection, and asks again.
3269
3270 *Push.* `GET /v1/git` advertises `named_push: true` when the route accepts
3271 `branch` and `expect.head`. A client sends the `branch` and `head_oid` it
3272 read: `{ "branch": "feature", "expect": { "head": "<head_oid>" } }`. The
3273 branch must still be checked out and its tip must still be that commit;
3274 otherwise the route pushes nothing and answers `409 git_state_changed` with
3275 `stale` naming `branch` (another branch, or a detached HEAD) and/or `head`,
3276 plus `current`. `branch` without `expect.head`, `expect` without `branch`,
3277 `head: null`, or any other `expect` field answers `400`. An Engine without
3278 `named_push` rejects the unknown `branch` field with `400` and pushes nothing,
3279 so a new client fails closed against an old Engine.
3280
3281 Every push, named or not, runs
3282 `git push --no-follow-tags --no-recurse-submodules -- <remote> <commit>:refs/heads/<branch>`:
3283 one source commit and one same-named destination branch, never a force push.
3284 `push.default`, `remote.<name>.push`, `push.followTags` and submodule
3285 recursion cannot add refs, and `remote.<name>.mirror` makes git refuse
3286 (`400`). A request without `branch` pushes the checked-out branch at its
3287 current tip; from a detached HEAD or an unborn branch it answers `400`.
3288 The remote is `remote`, else `branch.<b>.pushRemote`, `remote.pushDefault`,
3289 `branch.<b>.remote`, then `origin`, and must be a configured remote name.
3290 A branch whose upstream on that remote is a differently named branch answers
3291 `400`, as git's default `simple` mode does. `set_upstream: true` records
3292 `branch.<b>.remote` and `branch.<b>.merge` after the push succeeds. Not
3293 covered: the remote's own hooks and `pushurl`, and whatever credential
3294 helper the user configured, still apply as in the user's terminal.
3295
3296 Stage, unstage, discard, commit and branch from one runtime are serialized,
3297 so a check and its write are atomic with respect to that runtime's other
3298 windows; a second concurrent write answers `409` with
3299 `error.code: "git_busy"` rather than queueing behind a long commit hook.
3300 Push is not serialized: it only moves a remote ref and can wait on the
3301 network for up to 120 s. The lock does not cover processes outside this
3302 runtime — a terminal, an editor, or Codewhale's own agent tools — which can
3303 still change the repository in the moment between the check and git taking
3304 `index.lock`; a truly concurrent git write then fails on git's own
3305 `index.lock` (a `400` carrying git's message). A compare-and-swap commit via
3306 `commit-tree` and `update-ref` would close that window but skip the
3307 repository's hooks, which a Review-sheet commit must run, so it is not used.
3308
3309 **Diagnostics** (read-only logs, crashes, process — APPS-103)
3310 - `GET /v1/logs` → `{sources: [{dir, files: [{name, size, modified}]}]}` —
3311 the runtime's log directory plus `audit.log[.1]` from the codewhale home,
3312 newest first, capped
3313 - `GET /v1/logs/{name}?offset=<bytes>&limit=<bytes>&tail=<bytes>` →
3314 `{name, size, modified, offset, bytes, truncated, encoding, content}` —
3315 one bounded window; `tail` reads from the end and is mutually exclusive
3316 with `offset`; `truncated` means bytes remain after the returned window
3317 (a tail read at EOF is `false`), `encoding` is `utf-8` or `base64`
3318 - `GET /v1/crashes`, `GET /v1/crashes/{name}` — the same list/read contract
3319 over the crash-dump directories (`~/.codewhale/crashes`, legacy
3320 `~/.deepseek/crashes` merged)
3321 - `GET /v1/process` → `{pid, version, commit, started_at, uptime_seconds,
3322 executable, rss_bytes}` — `rss_bytes` only where the platform reports it
3323 (Linux `/proc`); absent rather than fabricated elsewhere
3324
3325 These routes package what already exists on disk for a client-side export;
3326 there is no telemetry upload route and no second log store. Names are
3327 basename-validated (no separators, no `..`), listings are capped, reads are
3328 bounded windows, and symlinks are never followed — a client bundles the
3329 files itself.
3330
3331 **Targets and remote posture** (APPS-50)
3332 - `GET /v1/targets` → `{targets: [self], remote: {supported: true,
3333 attach: "client", probe: "POST /v1/remote/connect"}, ssh: {…},
3334 cloud: {…}}` — this runtime's own record as the attachable target plus
3335 per-surface ownership; the runtime keeps no persistent target registry,
3336 so `POST /v1/targets` and `POST /v1/targets/switch` answer
3337 `501 Not Implemented` — target selection is client-owned and a switch
3338 must never move a running task server-side
3339 - `GET /v1/remote` → `{bind_host, port, loopback_only, reachable_from_lan,
3340 auth_required, mobile, tls}` — this listener's reachability posture.
3341 `tls` is always `false`: the API has no TLS terminator, so non-loopback
3342 reachability assumes a verified overlay (VPN/mesh), never plain LAN trust
3343 - `POST /v1/remote/connect` `{ "endpoint": "http://host:port" }` — probes a
3344 candidate remote's unauthenticated `GET /v1/runtime/info` (origin only;
3345 any pasted path is discarded). Answers `{ok, remote: {endpoint,
3346 runtime_api_version, codewhale_version, auth_required, …}, attach:
3347 "client"}` on success, and `{ok: false, reason: "unreachable" |
3348 "not a Codewhale runtime" | …}` as data on failure. URLs carrying
3349 credentials are refused with 400 — the remote's token is configured
3350 client-side, and a connect route that forwarded one would be an
3351 exfiltration primitive
3352 - `GET /v1/ssh`, `GET /v1/cloud` → `{supported: false, owner:
3353 "codewhale-control-plane", reason}`; `POST /v1/ssh/connect` and
3354 `POST /v1/cloud/attach` → `501`: SSH workspace provisioning and hosted
3355 cloud computers belong to the Apps control plane (ASCII Box for Managed
3356 Computer), not to a second authority inside Core
3357
3358 A remote Codewhale is a `serve --http` runtime with a token — that is the
3359 whole attach model. These routes describe and probe it; they never execute
3360 a remote request on the local machine.
3361
3362 **LSP** (workspace language intelligence, APPS-93)
3363 - `GET /v1/lsp` — capability: `enabled`, supported `languages` with their
3364 server commands, `custom_languages`, operations, poll and diagnostic caps
3365 - `GET /v1/diagnostics?path=` — file diagnostics (`items[].line`/`column` are
3366 1-based; response carries `position_base: 1`)
3367 - `GET /v1/definition?path=&line=&character=` (1-based input; `locations[].range`
3368 and `result` keep raw 0-based LSP positions, `position_base: 0`,
3369 `position_encoding: "utf-16"`)
3370 - `GET /v1/references?path=&line=&character=` (same input/output position
3371 contract as `/v1/definition`)
3372 - `GET /v1/symbols?path=&query=` — empty query returns document symbols (same
3373 0-based output positions as `/v1/definition`)
3374
3375 One lazily-built workspace-level `LspManager` serves these; engine threads
3376 keep their own per-thread managers for the post-edit hook, and a server that
3377 never serves an LSP route never spawns a language server. `path` is
3378 workspace-relative under the same confinement as the file routes. Normal
3379 absence is data: no language server, a disabled or missing `[lsp]` config, a
3380 server the person has not approved for the workspace, or a timeout answers
3381 `200` with `ok: false` and a machine-readable `reason` (`no_server`,
3382 `lsp_disabled`, `not_approved`, `lsp_error`). A server starts only in a
3383 workspace trusted permanently and approved for that server with
3384 `/lsp approve <name>` in the terminal app (headless and container runs read the
3385 same approval, so make it once there); without an `[lsp]` table the
3386 manager is disabled and `GET /v1/lsp` reports `enabled: false`; malformed input is a 400 and a
3387 missing file a 404.
3388
3389 **Voice** (host dictation & uploaded voice / TTS, CW-8218)
3390 - `GET /v1/voice` — capability: `available` (host mic recorder),
3391 `upload_available`, `tts_available`, detected `recorder` command, resolved
3392 `asr` `{kind, model}`, `modes`, `send_phrases`, `max_record_seconds`,
3393 `max_upload_bytes`, `tts_voices`
3394 - `POST /v1/voice/dictate` — record then transcribe → `{ ok, text }`
3395 - `POST /v1/voice/send` — same capture with the "send it" / 发送/發送
3396 suffix contract: `send: true` tells the client to submit (empty `text`
3397 with `send: true` means submit the client's current draft)
3398 - `POST /v1/voice/control` `{ "composer": "draft text" }` — assisted
3399 dictation that shows the model the composer text; `assisted: false` in the
3400 response means local whisper, Groq, or DeepSeek ASR handled the audio and the
3401 composer context was never seen
3402 - `POST /v1/voice/transcribe` `{ "audio_base64", "mime_type", "mode",
3403 "composer", "language" }` — transcribe client-uploaded WAV/OGG audio without
3404 requiring a host microphone (`CODEWHALE_DISABLE_VOICE=1` does not block
3405 uploaded audio)
3406 - `POST /v1/voice/tts` `{ "text", "voice", "voice_id", "format",
3407 "filter_markdown" }` — synthesize speech audio via the active Xiaomi MiMo or
3408 configured DeepSeek Tools TTS route and answer JSON `{ ok: true, mime_type,
3409 audio_base64, voice_id, provider, model, format }` or `{ ok: false, reason,
3410 message }`
3411
3412 The runtime owns the host microphone, uploaded audio decoding, TTS synthesis,
3413 and ASR dispatch — the same implementation the TUI's `/voice` commands run,
3414 headless. Recording is one blocking capture per host (requests serialize; the
3415 loser gets `ok:false`/`no_speech`, not a fought-over device). Provider ASR
3416 resolves its key lazily so local-whisper and Groq paths work without provider
3417 auth; uploaded audio and TTS support DeepSeek `/v1/tools/asr` and
3418 `/v1/tools/tts` when configured. Interim and final transcription use the
3419 selected ASR backend. If local whisper or Groq fails, the error stays on that
3420 backend: the runtime never retries the recording or composer text with the
3421 active model provider. Select provider ASR explicitly to use that route.
3422 Failure is data: `no_recorder`, `no_speech`, `no_provider_auth`,
3423 `invalid_input`, `transcription_failed`, `synthesis_failed`.
3424 `CODEWHALE_DISABLE_VOICE=1` is an operator kill-switch for host microphone
3425 recording (`available: false`), while uploaded audio continues to follow
3426 `upload_available`.
3427
3428 ## Provider and model selection
3429
3430 These three routes are how a GUI renders a model picker whose contents are true
3431 for *this* runtime instead of guessed from a version snapshot. They were
3432 undocumented until 2026-08-04, which cost a desktop integration a day: the
3433 client probed `/v1/models`, `/v1/runtime/models`, and `/v1/runtime/providers`
3434 (all correctly 404) and concluded the capability did not exist.
3435
3436 ### `GET /v1/providers`
3437
3438 ```json
3439 {
3440 "current": "modelstudio-token-plan",
3441 "providers": [
3442 {
3443 "id": "modelstudio-token-plan",
3444 "model_provider_id": "modelstudio-token-plan",
3445 "display_name": "Alibaba Cloud Model Studio",
3446 "default_model": "qwen3.8-max",
3447 "has_model_catalog": true,
3448 "credentialState": "configured"
3449 }
3450 ]
3451 }
3452 ```
3453
3454 `current` is the active generic provider id. Only the active entry carries an
3455 exact identity: an active built-in normally repeats its canonical id in
3456 `model_provider_id`, while an active named custom route has `current` set to
3457 `custom` and the exact configured key there (for example `lm-studio`). Other
3458 entries have a null exact id; a null id on the active `custom` entry identifies
3459 the released legacy root-level custom route. Preserve both fields from the
3460 selected entry and send a non-null exact id back as `POST /v1/threads`'s
3461 `model_provider_id`; dropping a named custom id would collapse the selection to
3462 the legacy root custom route. `credentialState` is a stable, non-secret
3463 projection of the Runtime's existing structural credential classification:
3464
3465 - `configured`: credential material is structurally available;
3466 - `login_required`: the route needs login or a usable login capability;
3467 - `missing`: an API-style credential is unavailable;
3468 - `no_auth`: the route explicitly disables credential use;
3469 - `local`: the exact route is local and keyless;
3470 - `legacy`: the compatibility route cannot be classified more precisely.
3471
3472 For an active named custom provider, this state is calculated from the exact
3473 route named by `model_provider_id`, not from a generic custom-provider default.
3474 It deliberately collapses saved-key and imported-token details into
3475 `configured`, and login/consent-source details into `login_required`.
3476
3477 The response never includes endpoint URLs, credential environment-variable
3478 names, filesystem paths, credential values, consent-source details, or token
3479 metadata. `credentialState` is not a provider canary: `configured` does not
3480 prove endpoint reachability, credential validity, model entitlement, or a
3481 successful request. The models route below is also only a selection catalog; a
3482 non-empty list does not prove that the route can currently serve a request.
3483
3484 `lastCheck` is the outcome of the last real call this process made on the
3485 provider, and is absent until a turn has used it:
3486 `{ "ok": true }` after a completed turn, or
3487 `{ "ok": false, "category": "rate_limit", "message": "HTTP 402: …" }` after a
3488 provider-owned failure (network, authentication, authorization, rate limit or
3489 quota such as HTTP 402, timeout). `message` is the provider's error text cut to
3490 120 characters. The record lives in memory and starts empty when the Engine
3491 restarts.
3492
3493 ### `GET /v1/providers/{id}/models`
3494
3495 ```json
3496 {
3497 "provider": "deepseek",
3498 "models": [
3499 {
3500 "id": "deepseek-v4-flash-vision-exp",
3501 "image_input": "supported",
3502 "reasoning_effort": "unknown",
3503 "reasoning_effort_levels": [],
3504 "reasoning_effort_source": null
3505 }
3506 ]
3507 }
3508 ```
3509
3510 For an exact configured route, supply `?model_provider_id=vision-work` and
3511 require the response to echo that same `model_provider_id`. The Runtime resolves
3512 that identity under the requested provider kind before reading model support.
3513 Unknown or mismatched identities return `400`. Named pagination cursors bind the
3514 configuration identity, endpoint and catalog snapshot; changing any of those
3515 requires restarting pagination. Omitting the query preserves the legacy catalog
3516 projection and omits the identity echo.
3517
3518 The catalog for one provider. Returns `400` for an unknown id, and for the
3519 legacy `deepseek-cn` alias, which has no provider metadata — use `deepseek`.
3520 An empty `models` array means the Runtime has no discoverable or configured
3521 model ids for that provider; it does not report credential presence.
3522
3523 The ids returned here are exactly the values accepted by `POST /v1/threads`'s
3524 `model` field and by the switch route below. `image_input` is the exact resolved
3525 provider/model route's capability state: `supported`, `unsupported`, or
3526 `unknown`. Keep `unknown` unknown rather than inferring from the model name or
3527 wire protocol. `supported` describes the model route; it does not mean a given
3528 client implements an image-upload control.
3529
3530 `reasoning_effort` uses the same three capability states and describes whether
3531 the exact model's metadata publishes a selectable effort ladder.
3532 `reasoning_effort_levels` contains only canonical, recognized active effort levels
3533 from that metadata. Off and provider synonyms such as none are excluded: the
3534 Apps/Chat protocol treats off as omission, which does not prove support for an
3535 explicit provider disable command. A model capable of reasoning may still have
3536 an unknown active effort ladder.
3537 Codex levels are also excluded when native compatibility would change their
3538 wire value (currently minimal and auto). This projection does not change native
3539 compatibility behavior or advertise a tier the Runtime cannot send unchanged.
3540 No levels are inferred from a provider-wide default or a familiar model name
3541 on a custom endpoint. `reasoning_effort_source` identifies `catalog`,
3542 `codex_cli_cache`, or `codex_app_server`; missing, stale, and unrecognized model
3543 metadata stays unknown. Codex roster metadata describes the external CLI's
3544 roster, not proof that a separately configured Runtime credential belongs to
3545 the same account or that an authentication boundary is approved.
3546
3547 Pass `?model_provider_id=<exact configured id>` when selecting a named route.
3548 The Runtime validates the provider kind and exact identity together, returns
3549 `model_provider_id` alongside that route's model list, and leaves the active
3550 configuration unchanged. An empty or unknown requested identity, or a mismatched kind, returns
3551 `400`; it never falls back to another named route.
3552
3553 The Runtime Chat relay publishes the same effort fields in camelCase
3554 (`reasoningEffort`, `reasoningEffortLevels`, `reasoningEffortSource`). These
3555 model facts do not enable tool execution or establish account entitlement.
3556
3557 For a thread-scoped choice, send the provider fields from the selected entry
3558 alongside the selected model. Omit `model_provider_id` when it is null:
3559
3560 ```json
3561 {
3562 "model_provider": "custom",
3563 "model_provider_id": "lm-studio",
3564 "model": "local-vision-model"
3565 }
3566 ```
3567
3568 This creates one thread on the exact named custom route without changing the
3569 Runtime's provider or model defaults.
3570
3571 ### `PUT /v1/providers/{id}/key` — write-only credential
3572
3573 ```json
3574 // request
3575 { "key": "sk-…" }
3576
3577 // response
3578 { "provider": "openai", "stored": true, "backend": "keychain",
3579 "credentialState": "configured", "configPath": "/…/config.toml" }
3580 ```
3581
3582 The optional `scope` field accepts `"durable"` (the default) or `"session"`.
3583 Durable scope stores a provider API key through the same transactional write as
3584 `codewhale auth set --provider <id> --api-key-stdin`: the secret store under
3585 the provider write lock, plus the `[providers.<id>] auth_mode` metadata
3586 marker persisted to the config document and mirrored into the live runtime
3587 config so `GET /v1/providers` reports the new state immediately. `backend`
3588 names which secret backend holds the key and `configPath` which config
3589 document carries the marker (the user-global file when the ambient config
3590 is workspace-scoped).
3591
3592 For a key held only in the running Engine's memory, send:
3593
3594 ```json
3595 // request
3596 { "key": "sk-…", "scope": "session" }
3597
3598 // response
3599 { "provider": "openai", "stored": false, "scope": "session",
3600 "backend": "memory", "credentialState": "configured" }
3601 ```
3602
3603 A session key matches only the exact provider identity; it never falls back to
3604 a sibling sharing a durable slot, such as `deepseek` and `deepseek-anthropic`.
3605 It is bound to the full resolved endpoint it was set for. An accepted config
3606 reload removes incompatible bindings; rejected reloads leave the live overlay
3607 unchanged. Lookups through older config snapshots cannot remove newer keys. It never applies to `auth_mode = "none"` or remote
3608 custom endpoints, and session writes to those routes are refused. Within those
3609 limits it overrides other credential sources, except a route bound to a
3610 required Codewhale account owner retains that requirement without fallback.
3611 It is never serialized or written to the secret store or config document, and
3612 does not change the live provider settings. It survives config reloads within
3613 the Engine process while the endpoint remains the same, but does not persist
3614 across an Engine restart. Running turns retain the key they started with;
3615 clearing the overlay takes effect from the next turn. The response omits
3616 `configPath` because no config document is saved.
3617 Request bodies reject unknown fields, so an older Engine that does not support
3618 `scope` rejects a session request instead of silently storing its key.
3619
3620 Set `CODEWHALE_RUNTIME_KEY_SCOPE=session` before HTTP startup to require
3621 session-only provider keys. A durable request, including one that omits
3622 `scope`, returns `409`. The policy is fixed for the process and preserved
3623 through reloads. An unset or empty variable preserves normal behavior; any
3624 other value refuses server startup. Strict mode does not use stored, environment,
3625 subscription OAuth or configured alternate-auth headers as a fallback. Explicit
3626 keyless routes remain keyless. Required Codewhale account ownership remains a
3627 separate restriction and cannot be overridden with a session key.
3628
3629 `GET /v1/runtime/info` advertises `capabilities.session_provider_keys: true`
3630 only in this strict mode, where both set and clear are memory-only. Browser
3631 sign-in is unavailable in this mode. Ordinary subagents share the in-process
3632 credential context, but external Fleet workers resolve their own credentials
3633 and have no session-key handoff. Strict mode therefore refuses Fleet creation,
3634 activation, restart and launch, including restored leases, and advertises its
3635 Fleet create/start/local-target capabilities as false. It never forwards a
3636 provider key through a worker command line, environment or config file.
3637 Other configuration and MCP routes may still write their non-key settings to
3638 disk; this is a provider credential policy, not a read-only filesystem.
3639
3640 Memory-only custody is not a vault: anyone with root access on the machine can
3641 read a running Engine's memory. The key is not zeroized or locked against swap,
3642 and this route does not protect it from a snapshot that captures process
3643 memory. Existing process hardening disables core dumps on Linux when its
3644 hardening calls succeed; failures log a warning, and that hardening is a no-op
3645 on other platforms.
3646
3647 The key is never returned — there is no read route for credential material,
3648 and neither the key nor its length appears in the response, errors, or
3649 logs; the response carries only the readiness projection
3650 (`credentialState`). An unknown provider id, the `deepseek-cn` legacy
3651 alias, a key that is empty after normalization, or a normalized key over 4 KiB
3652 is `400`. Both scopes remove whitespace, control and invisible characters with
3653 the shared key normalizer before validation; `openai-codex` refuses API-key writes.
3654 `credentialState: "local"` after a successful durable write is honest output for
3655 a keyless local route: the key is
3656 accepted, but the route classifies as not needing one.
3657
3658 ### `POST /v1/providers/{id}/key/check` — verify a key without storing it
3659
3660 ```json
3661 // request
3662 { "key": "sk-…" }
3663
3664 // response
3665 { "provider": "openai", "valid": true, "checked": true }
3666 ```
3667
3668 Asks the provider's own `/models` endpoint once whether it accepts the key. It
3669 never stores a key and never switches the provider. `checked` is `false` when
3670 the provider has no `/models` endpoint to ask, so the key is accepted
3671 unverified. A key the provider rejects (HTTP 401 or 403) answers `422`; any
3672 other failure to ask (a network error, a timeout, another status) answers
3673 `502`, which a client can treat as "could not verify" and still `PUT` the key.
3674 The route applies `PUT`'s credential-writability rules and key-shape limits and
3675 refuses OpenAI Codex. An Engine without this route answers `404`.
3676
3677 ### `GET /v1/agents/external` — agent CLIs installed on this computer
3678
3679 ```json
3680 // response
3681 { "agents": [
3682 { "id": "opencode", "name": "OpenCode", "state": "installed",
3683 "version": "1.19.5", "acp": null, "transport": "acp", "transports": ["acp"],
3684 "auth_methods": [],
3685 "website": "https://opencode.ai", "adapter_installed": false, "runnable": true },
3686 { "id": "qoder", "name": "Qoder", "state": "not_installed", "version": null,
3687 "acp": null, "auth_methods": [], "website": "https://qoder.com",
3688 "adapter_installed": false, "runnable": false }
3689 ] }
3690 ```
3691
3692 The [agent registry](../crates/engine/src/fleet/agents.rs) and configured custom
3693 agents supply the inventory. The route resolves executables on `PATH` and in
3694 known install directories, checks installed versions with `--version`, and
3695 checks for required adapter binaries. Opening the list never initializes ACP.
3696
3697 `state` is `installed` or `not_installed`. `runnable` means the executable and a
3698 supported transport are available locally. A detected version below the
3699 minimum disables that route. An undetermined version is reported as `null`.
3700 `transport` and
3701 `transports` identify the launch routes. For native ACP, the inventory reports
3702 `transport: "acp"`, `acp: null` and `auth_methods: []`. For an adapter-based
3703 agent `acp` is `adapter` and `adapter_installed` reports local availability.
3704 An agent that supports direct CLI can also offer `cli`.
3705
3706 Explicit agent options or a session start negotiate with the selected agent.
3707 The CLI also verifies a selected native ACP agent for `--agent`. An agent may
3708 request sign-in or refuse the handshake at that point. `auth_status` reflects a
3709 previously observed sign-in result and otherwise reports `unknown`.
3710
3711 `depth` is `driven` when a local launch route is available, `observed` for an
3712 installed agent with no available route, and `null` for a missing binary.
3713 Unavailable rows include `reason` and `reason_code`, for example
3714 `below_min_version`, `adapter_missing` or `not_installed`.
3715
3716 ### `DELETE /v1/providers/{id}/key` — clear a Codewhale-owned credential
3717
3718 ```json
3719 // response
3720 { "provider": "openai", "cleared": true, "credentialState": "missing" }
3721 ```
3722
3723 Removes any session key for the exact provider identity before attempting a
3724 durable clear, even when the durable operation subsequently fails. Unless
3725 `CODEWHALE_RUNTIME_KEY_SCOPE=session`, it also clears the durable credential
3726 through the same shared owner as
3727 `codewhale auth clear`: the config document is snapshotted and restored if
3728 its save fails, the secret store is only touched once that save has landed,
3729 and the cleared markers are mirrored into the live runtime config so
3730 `GET /v1/providers` reports `missing` on the next read rather than after a
3731 restart.
3732
3733 Under `CODEWHALE_RUNTIME_KEY_SCOPE=session`, DELETE removes only the memory
3734 overlay and does not touch the durable secret store or config document:
3735
3736 ```json
3737 // response under session-only policy
3738 { "provider": "openai", "cleared": true, "scope": "session", "backend": "memory" }
3739 ```
3740
3741 This response omits `credentialState` and does not probe or clear a durable
3742 store. After removal, subsequent turns cannot fall back to stored or environment
3743 keys. A running parent turn and children using its already-materialized client
3744 retain their credential until they finish; clearing memory is not provider-side
3745 revocation. This mode validates canonical provider identity but does not apply
3746 durable ownership checks to removing the Engine's own session key.
3747
3748 Clearing an already-clear route returns `cleared: true` — a client retrying
3749 a revoke must not be told something went wrong. If the config entry is
3750 cleared but the secret backend refuses the delete, the route answers `500`
3751 and names the slot: reporting success while the key is still in the keyring
3752 would be a lie about a security action.
3753
3754 ### Credential ownership: `credentialSource` and `credentialWritable`
3755
3756 Durable PUT and the durable portion of DELETE refuse a route whose credential
3757 Codewhale does not own, independently of any session key. `GET /v1/providers`
3758 classifies that underlying durable owner so a client can disable its durable
3759 credential control *before* submitting instead of failing late:
3760
3761 | `credentialSource` | `credentialWritable` | Meaning |
3762 | --- | --- | --- |
3763 | `secret_store` | `true` | A Codewhale-owned durable credential slot. |
3764 | `account_session` | `false` | Codewhale account model access owns the credential; disconnect through account sign-out. |
3765 | `config` | `false` | A literal key in a config file, which wins at request time when no session key is present. |
3766 | `external_auth` | `false` | An active external consent (OAuth) owns the credential. |
3767 | `none` | `false` | The route sends no credential, or has no credential slot. |
3768
3769 When `credentialWritable` is `false`, `credentialWritableReason` carries
3770 user-facing copy naming the owner. Durable PUT and the durable portion of
3771 DELETE answer `409` with that same reason. DELETE still removes the memory
3772 overlay regardless of the durable credential owner. An existing session key
3773 can be updated with session scope without changing that owner, subject to the
3774 endpoint and auth-mode restrictions above. The ownership classification is
3775 based on declared auth mode, consent state and the *kind* of any configured
3776 `api_key` value. When account model access is bound, it also resolves the
3777 credential source with the session overlay excluded to determine whether the
3778 account owns the route. The result is a class and never a value, a path, or an
3779 environment variable name.
3780
3781 ### `POST /v1/providers/orcarouter/connect` — browser sign-in without a terminal
3782
3783 ```json
3784 // response
3785 { "attemptId": "0f3c…", "authorizeUrl": "https://www.orcarouter.ai/auth?…",
3786 "expiresIn": 900 }
3787 ```
3788
3789 Runs the same OrcaRouter OAuth 2.0 + PKCE sign-in as `codewhale auth orcarouter`
3790 for a client that has no terminal. The Engine binds its loopback callback
3791 (`http://127.0.0.1:<port>/callback`), returns the consent URL, and waits on a
3792 worker for up to `expiresIn` seconds. The client opens `authorizeUrl` in the
3793 system browser — never an embedded view — and polls the attempt. When the
3794 browser comes back, the Engine exchanges the code, refuses a key whose granted
3795 scope is not `api`, and stores the key through the same seam as the CLI, then
3796 mirrors the credential markers into the live config the way
3797 `PUT /v1/providers/{id}/key` does. It does not switch the active provider; use
3798 `POST /v1/providers/{id}/switch` for that.
3799
3800 The callback listens on the Engine's own computer, so a client offers this
3801 route only for an Engine on the same computer as the browser and outside
3802 session-only key policy. Strict mode refuses before binding a callback or
3803 starting authorization. A new `POST`
3804 cancels the previous attempt, and only the current attempt can be read.
3805 Refusals: `400` for an id other than `orcarouter`, `409` when the route's
3806 credential is not writable (the same reason `credentialWritableReason`
3807 carries), `500` when the callback cannot be bound. `GET /v1/providers` marks a
3808 route that supports this with `"browserConnect": true`; the field is absent
3809 otherwise and on Engines without the route.
3810
3811 ### `GET /v1/providers/orcarouter/connect/{attemptId}` and `DELETE …` — status and cancel
3812
3813 ```json
3814 { "attemptId": "0f3c…", "status": "failed", "reason": "key_not_saved" }
3815 ```
3816
3817 `status` is `waiting`, `connected`, `declined` (the user refused in the
3818 browser), `expired` (no callback in time), `cancelled` or `failed`. `failed`
3819 carries a `reason`: `authorization_error` (the browser came back with another
3820 error), `callback_failed`, `not_writable` (the route's endpoint or credential authority changed before
3821 local activation), `exchange_failed`,
3822 `scope_refused` or `key_not_saved`. After `scope_refused` or `key_not_saved`,
3823 OrcaRouter created a key that Codewhale did not keep; the user should revoke
3824 it under Authorized Apps in OrcaRouter. `exchange_failed` can follow a key
3825 OrcaRouter created before the response was lost.
3826
3827 `DELETE` cancels a pending attempt, including an exchange in progress, and
3828 prevents its later local activation. It does not revoke a key already created
3829 by OrcaRouter; revoke that key under Authorized Apps. If local activation
3830 completed first, cancellation returns the terminal status instead. Clearing
3831 or replacing the provider key also cancels its pending connect attempt. These
3832 mutations retain their serialization if the HTTP client disconnects. An unknown
3833 or superseded `attemptId` is `404`. Only the `POST` response carries the consent
3834 URL; no status, error or log line carries it, the key, the code or the verifier.
3835
3836 ### `POST /v1/providers/{id}/switch`
3837
3838 ```json
3839 // request (model is optional; omit to take the provider default)
3840 { "model": "qwen3.8-max" }
3841
3842 // response
3843 { "provider": "modelstudio-token-plan", "model": "qwen3.8-max",
3844 "message": "…", "persisted": true }
3845 ```
3846
3847 **Use this rather than simulating a switch with repeated `POST /v1/config`
3848 writes plus a reload.** Provider and model move together here, the change is
3849 validated against the provider's catalog before it is applied, and `persisted`
3850 reports whether it was written to config or applied to the live session only.
3851 Rejects an unknown provider id and the `deepseek-cn` alias with `400`.
3852
3853 ### `GET` and `POST /v1/config` — reply style and sub-agent limit
3854
3855 ```json
3856 // request
3857 { "key": "subagents_max_concurrent", "value": "4", "persist": true }
3858
3859 // response
3860 { "key": "subagents_max_concurrent", "value": "4", "persisted": true,
3861 "requires_reload": true, "message": "…" }
3862 ```
3863
3864 `GET /v1/config` reports and `POST /v1/config` writes two config.toml keys a
3865 person chooses:
3866
3867 - `verbosity`, the root reply-style key: `normal` or `concise`, compared
3868 without regard to case. Unset reads as `normal`.
3869 - `subagents_max_concurrent`, the `[subagents] max_concurrent` limit on
3870 sub-agents running at once: an integer from `0` to `128`. Larger values are
3871 stored as `128`, and `0` turns sub-agents off, as `max_concurrent = 0` does
3872 in config.toml. Unset reads as the limit the Engine applies (top-level
3873 `max_subagents`, else 64); the Engine never writes that default for you.
3874
3875 Any other value is `400`, also when `persist` is false. The response `value`
3876 is what was stored. As with the other config.toml keys, a persisted write
3877 takes effect after `POST /v1/config/reload`.
3878
3879 ### Third-party web search consent
3880
3881 `GET /v1/runtime/info` advertises `capabilities.search_consent: true`. Require
3882 it before reading the fields below, sending `search_provider` on an approval
3883 answer, or rendering the consent card.
3884
3885 `GET /v1/config` reports:
3886
3887 - `search_third_party`: the effective `[search] third_party` value, `ask`, `on`
3888 or `off`.
3889 - `search_third_party_source`: `config` (the key is set), `implied` (unset, but
3890 search was already set up with a pinned provider, `CODEWHALE_SEARCH_PROVIDER`,
3891 a Tavily key, `[search] api_key` or `FIRECRAWL_API_KEY`, which reads as `on`)
3892 or `default` (unset, reads as `ask`).
3893 - `search_providers[]`: `{ id, label, keyless }` choices, starting with
3894 `{ "id": "any" }`, then the keyless services, then keyed services whose key is
3895 present now.
3896
3897 `POST /v1/config` with key `search_third_party` accepts `ask`, `on` or `off`;
3898 `ask` removes the key. Any other value is `400`. Running threads read the key
3899 again before each web search, so the response has `requires_reload: false`.
3900 Key `search_provider` with value `any` removes the `[search] provider` pin.
3901
3902 With `ask`, an interactive turn whose web search would go to a third-party
3903 service (every backend except the route's provider-native search and a
3904 self-hosted `[search] base_url`) first raises a consent approval: an
3905 `approval.required` event, and a `pending_approvals` entry in the thread
3906 snapshot, whose approval object carries `"approval_kind": "third_party_search"`.
3907 Only the Engine sets `approval_kind`. It also removes any `third_party_search`
3908 key that a model, an MCP call or an `execute_tools` program puts in a tool's
3909 input. Recognize a consent approval only by `approval_kind`; an approval
3910 without it is an ordinary approval even when its `input` has a
3911 `third_party_search` object. On a consent approval, `input.third_party_search`
3912 is `{ version: 1, selected, providers[] }` for rendering, `tool_call_id` names
3913 the search call it gates, and `standing_rule_candidates` is empty.
3914
3915 Answer it at `POST /v1/approvals/{approval_id}`. `deny` saves
3916 `third_party = "off"`, and the model gets a short "web search is off" result
3917 without a network call. `allow` saves `third_party = "on"`; the search then
3918 gets the approval decision it would have had with `on`, so a posture that asks
3919 before a web search raises an ordinary `approval.required` for the same call
3920 next. If the Engine cannot save config.toml, the answer still applies for the
3921 rest of the session, sub-agents included, and the thread gets a status line
3922 saying the save failed.
3923
3924 An `allow` may carry `search_provider`: `any` (nothing is pinned) or one of the
3925 offered ids, which the Runtime saves as `[search] provider` before delivering
3926 the answer. It first checks that this client may answer the approval, so a
3927 refused answer (`403 owner_required`, `404`, `409`) saves nothing, and it takes
3928 the pin back if the answer then cannot be delivered. With `allow`, a value that
3929 is not offered, or `search_provider` on an approval without `approval_kind`, is
3930 `400 invalid_search_provider`; a failed save is
3931 `500 search_provider_persist_failed` and the approval stays pending. With
3932 `deny`, `search_provider` is ignored. No grant, posture or remembered choice
3933 answers this card, and a timeout, steer or cancelled turn saves nothing.
3934
3935 Unattended turns never raise the card, and for them `ask` behaves as `on`.
3936 Sub-agents and Fleet workers never raise it either; a sub-agent of an
3937 interactive session follows the person's answer, and while the value is still
3938 `ask` its search returns a short "third-party web search has not been enabled
3939 yet" result instead of contacting the service. `off` is honored everywhere.
3940
3941 ### Migrating a saved whale name or color
3942
3943 A client upgrading from local storage can use `POST /v1/config` to fill an
3944 empty `whale_name` or `whale_color`. Send the saved preference in `if_unset`
3945 and omit `value`.
3946
3947 ```json
3948 {"key":"whale_name","if_unset":"First Mate","persist":true}
3949 ```
3950
3951 The Engine checks and writes the field under the settings lock. A successful
3952 response contains the normalized `value` and `persisted: true`. HTTP 409 means
3953 the setting already has a value. Read it from `GET /v1/settings/schema`.
3954 Keep the local preference until either read or write confirms a saved value.
3955
3956 ## Runtime data model
3957
3958 The runtime uses a durable Thread/Turn/Item lifecycle.
3959
3960 - **ThreadRecord** — `id`, `created_at`, `updated_at`, `model`,
3961 `model_provider` (generic kind), `model_provider_id` (optional exact configured
3962 route), `workspace`, `mode`, `task_id`, `system_prompt`, `latest_turn_id`,
3963 `latest_response_bookmark`, `archived`
3964 - **TurnRecord** — `id`, `thread_id`, `status` (`queued|in_progress|completed|
3965 failed|interrupted|canceled`), `effective_provider`, `effective_model`,
3966 `effective_billing_surface`, timestamps, duration, usage, error summary,
3967 `artifacts` and `workspace` (see [Turn artifacts](#turn-artifacts))
3968 - **TurnItemRecord** — `id`, `turn_id`, `kind` (`user_message|agent_message|
3969 tool_call|file_change|command_execution|context_compaction|status|error`),
3970 lifecycle `status`, `metadata`, `artifacts` and the legacy
3971 `artifact_refs` projection
3972
3973 Events are append-only with a global monotonic `seq` for replay/resume.
3974
3975 `effective_billing_surface` is a non-secret classification derived from the
3976 endpoint that served the turn. Recognized StepFun routes use `stepfun-payg` or
3977 `stepfun-plan`; unknown and custom endpoints leave it unset. The raw base URL is
3978 not persisted in `TurnRecord`.
3979
3980 ### Restart semantics
3981
3982 - If the process restarts while a turn or item is `queued` or `in_progress`,
3983 the recovered record is marked `interrupted` with an `"Interrupted by
3984 process restart"` error.
3985 - The trailing newline is an event append's commit marker. On startup, a final
3986 JSONL fragment without that delimiter is truncated and fsynced even when its
3987 bytes form valid JSON; it is an uncommitted append, and its already-reserved
3988 sequence number is not reused. Newline-terminated malformed records are not
3989 identifiable crash debris and continue to fail closed during replay.
3990 - If a terminal turn record reached disk but its terminal event sequence did
3991 not, the first async read reconciles any unresolved dynamic calls as
3992 `tool_call.canceled` and then emits one `turn.completed`. Existing terminal
3993 call and turn receipts are detected and never duplicated.
3994 - Turn-operation bindings survive restart. Retrying the same `operation_key`
3995 and request returns the original recovered turn (including an `interrupted`
3996 turn recovered from an in-progress process exit); mismatched reuse remains a
3997 conflict. A crash-created binding that never acquired a turn is discarded at
3998 startup because engine submission happens only after both records are
3999 durable.
4000 - Task execution performs its own recovery on top of the same persisted
4001 thread/turn store.
4002
4003 ### Approval model
4004
4005 - The `auto_approve` flag applies to the runtime approval bridge and engine
4006 tool context. When enabled for a thread/turn/task, approval-required tools
4007 are auto-approved in the non-interactive runtime path, shell safety checks
4008 run in auto-approved mode, and spawned sub-agents inherit that setting.
4009 - When omitted, `auto_approve` defaults to `false`.
4010 - [Authorization order](AUTHORIZATION_ORDER.md) describes where typed rules,
4011 registered tool requirements, safety floors, repository law, approval
4012 transport, and sandbox enforcement sit relative to one another.
4013
4014 ### SSE event stream
4015
4016 The SSE event payload shape for `/v1/threads/{id}/events`:
4017
4018 ```json
4019 {
4020 "schema_version": 1,
4021 "seq": 42,
4022 "previous_seq": 38,
4023 "event": "item.delta",
4024 "kind": "item.delta",
4025 "thread_id": "thr_1234abcd",
4026 "turn_id": "turn_5678efgh",
4027 "item_id": "item_90ab12cd",
4028 "timestamp": "2026-02-11T20:18:49.123Z",
4029 "created_at": "2026-02-11T20:18:49.123Z",
4030 "payload": {
4031 "delta": "partial output",
4032 "kind": "agent_message"
4033 }
4034 }
4035 ```
4036
4037 Compatibility notes:
4038
4039 - `schema_version` is the HTTP/SSE envelope schema version. It is independent of
4040 the runtime store schema used for persisted thread/turn/event records.
4041 - `event` remains the SSE event name in existing clients; it is preserved as-is.
4042 - `kind` mirrors `event` in the stable envelope for typed clients.
4043 - `seq` is allocated globally across all Runtime threads. Consequently, gaps
4044 between a thread's events are normal when other threads interleave. On this
4045 per-thread SSE stream, `previous_seq` is the sequence of the last event
4046 delivered for this thread (or the requested replay cursor for the first
4047 event); clients detect loss by comparing it with their accepted per-thread
4048 cursor, not by requiring `seq == previous_seq + 1`. Sequence allocation is
4049 also not rewound after an append is transactionally rolled back, so a retry
4050 can intentionally skip an unused value without implying a missing event.
4051 - `thread.started`, `turn.started`, and `turn.completed` are emitted as SSE event
4052 names exactly as before.
4053 - `timestamp` remains the canonical event time for schema version 1. `created_at`
4054 is an equivalent alias for clients that use `created_at` naming elsewhere; do
4055 not require both fields to be present.
4056
4057 ### Ending and resuming a thread stream
4058
4059 Whenever the server ends a `/v1/threads/{id}/events` stream that already
4060 returned `200`, the last frame is `stream.end`, sent exactly once and always
4061 (it does not need `progress=true`):
4062
4063 ```
4064 event: stream.end
4065 data: {"schema_version":1,"event":"stream.end","kind":"stream.end","thread_id":"thr_1234abcd","reason":"replay_failed","last_seq":42,"retryable":true}
4066 ```
4067
4068 - It is a transport frame, not a journal event: it has **no `seq`** and **no
4069 SSE `id:`**. Clients that acknowledge on `seq` skip it, and a browser's
4070 `Last-Event-ID` stays on the last real event.
4071 - `last_seq` is the stream's cursor when it ended: the last journal `seq`
4072 delivered on this connection, or the effective start cursor if none was
4073 (after a `replay_limit` tail, that is already past the omitted history). It
4074 is exactly the `since_seq` that resumes with no loss and no repeats.
4075 - `retryable` says whether resuming from `last_seq` can succeed. Key the client
4076 on it, not on the reason list. Treat an unknown `reason` by its `retryable`.
4077 - There is no free-text message. The underlying error is in the Runtime log,
4078 and it can contain store paths.
4079
4080 | `reason` | Meaning | `retryable` |
4081 | --- | --- | --- |
4082 | `replay_failed` | The durable history read that feeds the opening replay failed, including a replay worker crash after the first cursor | `true` |
4083 | `catch_up_failed` | After broadcast lag, the durable re-read from the stream's cursor could not be opened or failed | `true` |
4084 | `runtime_shutdown` | The Runtime API server is stopping (SIGINT, SIGTERM, or SIGHUP; Ctrl+C or Ctrl+Break on Windows). Open streams get this frame within a bounded drain window before the process exits | `true` |
4085 | `remote_access_revoked` | A grant-backed paired remote device session ended because the pairing was withdrawn, the plugin was revoked, the session TTL expired, or the bound conversation was archived/deleted | `false` |
4086
4087 Every `200` response carries `x-codewhale-stream-end: 1`. With that header, an
4088 EOF **without** `stream.end` means the connection or the Runtime process died
4089 without the server choosing to end the stream: a network or proxy drop, a
4090 crash, or a kill that allows no drain (for example `SIGKILL`). A Runtime that
4091 predates this frame sends no header; there EOF stays ambiguous, so treat it as
4092 connection loss.
4093
4094 Client resume rule:
4095
4096 1. Keep `cursor` = the `seq` of the last journal frame you accepted. Ignore
4097 frames with `seq <= cursor`. If a frame's `previous_seq` is not your
4098 `cursor`, you missed events: reload the thread snapshot rather than trust
4099 local state.
4100 2. On `stream.end` with `retryable: true`, reconnect with
4101 `since_seq = last_seq` after a bounded backoff, and tell the user what the
4102 Runtime said (for example, "Runtime is shutting down — reconnecting").
4103 With `retryable: false`, stop, show the reason, and fall back to the
4104 snapshot.
4105 3. On EOF or a transport error without `stream.end`, reconnect with
4106 `since_seq = cursor` after a bounded backoff and show a connection problem,
4107 not a Runtime error.
4108 4. A `401`/`403` or `404` before the stream opens is terminal (a credential or
4109 thread problem). Retry `5xx` with backoff.
4110 5. Never reconnect from `0` to "start over": replay is idempotent only by
4111 cursor.
4112
4113 Fleet streams (`/v1/fleet/runs/{run_id}/events`) keep their own end frames,
4114 `fleet.stream.error {retryable}` and `fleet.replay.cursor_unavailable`. They
4115 differ from `stream.end`: they carry no cursor, because a Fleet client resumes
4116 from the opaque `cursor` of the last Fleet event it accepted.
4117
4118 ### Steer delivery
4119
4120 Putting a steer into the engine's mailbox is not the same as the model reading
4121 it. The engine discards a steer whose turn has already moved on, and an
4122 interrupted or failed turn drops whatever it had queued. The API reports the
4123 engine's real verdict rather than the attempt:
4124
4125 - The item is persisted `queued` when the steer is accepted into the mailbox.
4126 - **Delivered.** The engine committed the text into the turn's record: the item
4127 becomes `completed`, `steer_count` rises, and `turn.steered` + `item.completed`
4128 are emitted. `POST .../steer` returns `200` with that turn.
4129 - **Not delivered.** The turn moved on, was interrupted, or failed first: the
4130 item becomes `canceled`, `steer_count` does not rise, and `turn.steer_dropped`
4131 is emitted carrying `input`, `reason`, and the settled `item`. `POST .../steer`
4132 returns `409`, so a client can keep the user's text and resend it rather than
4133 clearing a composer over guidance that was never seen.
4134 - **Still pending.** A steer sent while the engine is inside a long tool call
4135 cannot settle until that call returns, and the request does not hang for it.
4136 After a short wait `POST .../steer` returns `200` with the item still `queued`;
4137 the eventual `turn.steered` or `turn.steer_dropped` event carries the verdict.
4138
4139 A client that treats `200` as "the model saw it" is therefore wrong in the third
4140 case: read the item's status, or wait for the event.
4141
4142 Common event names: `thread.started`, `thread.forked`, `turn.started`,
4143 `turn.lifecycle`, `turn.usage`, `turn.steered`, `turn.steer_dropped`,
4144 `turn.interrupt_requested`,
4145 `turn.completed`, `turn.artifacts`, `item.started`, `item.delta`, `item.completed`,
4146 `item.failed`, `item.interrupted`, `tool.execution_started`,
4147 `approval.required`, `approval.decided`,
4148 `approval.timeout`, `user_input.required`, `user_input.answered`,
4149 `user_input.canceled`, `tool_call.requested`, `tool_call.resolved`,
4150 `tool_call.timeout`, `tool_call.canceled`, `sandbox.denied`,
4151 `permission.rules_saved`, `turn.workspace_snapshot`, `turn.provider_request`,
4152 `runtime.store_failure`.
4153
4154 A tool call's item is announced once with `item.started` and status `queued`:
4155 the model asked for it, but it may still be waiting behind another call, for
4156 an approval, or for its turn in the batch. When it passes its gates and starts
4157 running, the item becomes `in_progress` and `tool.execution_started` carries
4158 `execution_id` and the updated `item`; no second `item.started` is sent. A call
4159 that ends without ever starting (skipped by a steer or Stop, denied, or refused)
4160 goes straight from `queued` to `item.completed` or `item.failed`, with
4161 `started_at` equal to `ended_at`.
4162
4163 `turn.usage` is one model call's receipt, emitted when a parent model call
4164 reports usage — not once per turn. Its `payload` carries the call's `usage`,
4165 its `duration_ms` / `first_token_ms` / `request_ms` timings, the
4166 `maxOutputTokens` allowance, `billed_prompt_tokens` (the prompt size the
4167 provider billed: the last itemised request's input when retries were reported,
4168 else the call's own input count), and `cost` — that call priced on the route it
4169 was dispatched on, as `{usd, cny, usd_priced, cny_priced}`.
4170
4171 `cost` is `null` when the route cannot price every token class the call used; a
4172 client must not read that as a free call. A currency whose `*_priced` flag is
4173 false is unpriced. These receipts cover the parent model calls; child and
4174 compaction usage arrive through other paths. Summed per-call prices are
4175 therefore partial estimates, not the complete turn bill.
4176
4177 `turn.provider_request` retains the captured route, logical request identity,
4178 bounded `physical_requests` identities, typed `transmission`, `coverage`, reported
4179 usage and outcome. An observed send or absent response headers do not prove
4180 provider acceptance or free work. Unknown primary outcomes remain unpriced in
4181 the turn diagnostics and usage totals; known primary usage stays in parent
4182 accounting. These receipts do not yet reconcile late cumulative primary usage.
4183 Inference automatically retries only an ordinary rate limit, a proven
4184 transient connection failure before dispatch, or a request that received no
4185 response headers (`stream.open_retries` times, default once). A later explicit
4186 user turn is a new request, not an automatic replay of an uncertain request.
4187
4188 `turn.completed` carries the turn's authoritative cumulative token usage in
4189 `payload.turn.usage`, including routed work. It replaces the running token
4190 counts; it does not supply an authoritative last-turn cost. The thread totals
4191 at `GET /v1/threads/{id}/usage` remain the accounting record. The mobile page
4192 keeps the observed priced-call estimate after completion, marks it as a
4193 partial estimate, and resets its figure when a new turn starts. Replayed
4194 journal sequences are counted once. `billed_prompt_tokens` is available to
4195 API clients; the mobile header shows token usage and partial cost.
4196
4197 `turn.provider_request` carries diagnostic request observations, not additional
4198 billing usage. See [per-request cache receipts](CACHE.md#per-request-receipts).
4199
4200 `runtime.store_failure` is the runtime reporting a fault in the operator's own
4201 on-disk state: a thread, turn, or item record under the session's runtime
4202 store could not be read, parsed, or written. The payload carries `operation`
4203 (`read` | `parse` | `write`), `record_kind` (`thread` | `turn` | `item`),
4204 `record_id`, `path`, the full `error` chain, the root-cause `reason`, a
4205 `next_action` (which file to move aside, or where to check free space and
4206 permissions), and a one-line `message`. When `terminal` is `true`, the turn's
4207 own record is unreadable or unwritable and no `turn.completed` will follow;
4208 clients waiting on that turn should treat it as failed.
4209
4210 Agent-message and reasoning deltas are materialized into the item projection
4211 before their corresponding `item.delta` event is sequenced. To avoid an fsync
4212 for every provider fragment, adjacent deltas are coalesced to configured bounds
4213 of at most 32 ms or approximately 16 KiB before publication (an indivisible
4214 upstream chunk can itself exceed the byte target). A process crash inside that
4215 unpublished window can lose the recent suffix; no durable event claims that
4216 suffix existed. Once an `item.delta` is durable, snapshots at or beyond its
4217 cursor include the same materialized prefix.
4218
4219 `approval.required` events may include a `matched_rule` string when an
4220 execution-policy rule caused the prompt. This field is explanatory metadata for
4221 clients and does not grant or persist permissions.
4222
4223 `approval.required`, `approval.decided`, and `approval.timeout` carry two
4224 distinct identifiers. `approval_id` is the Runtime-minted, single-use capability
4225 described under **Approvals** — the only value `POST /v1/approvals/{id}` accepts
4226 — and `approval.required` also repeats it in the legacy `id` field for older
4227 clients. `tool_call_id` is the Engine tool-execution ID, present for
4228 correlation only. Automatically resolved prompts (thread `auto_approve`, and the
4229 Auto-Review posture, which never opens a modal) mint an `approval_id` as well, so
4230 the field has one meaning on every path; those IDs register no waiter and are
4231 inert against the endpoint. Clients must never treat `tool_call_id` as an
4232 approval capability or assume it is unique across threads.
4233
4234 The thread event stream forwards these payloads intact. The compatibility turn
4235 stream carries `approval_id`, its `id` alias and `tool_call_id`; the pending
4236 snapshot carries the same capability and correlator so reconnecting clients can
4237 attach an approval prompt to its tool row. Resolutions carry their resolution
4238 flags through that projection too: `timeout: true` marks the deny produced when
4239 the configured decision budget expires, and `cancelled: true` marks a deny
4240 forced by a turn interrupt or turn teardown where no user selection
4241 was made — clients should clear the pending prompt rather than report a
4242 refusal.
4243
4244 ## Security boundary
4245
4246 - **Localhost by default**. The server binds to `127.0.0.1` by default.
4247 `--mobile` is also loopback-only and rejects a non-loopback host until a TLS
4248 or verified-overlay transport boundary exists. The runtime does not provide
4249 user isolation or TLS.
4250 - **Optional token guard**. `CODEWHALE_RUNTIME_TOKEN` (or the
4251 `DEEPSEEK_RUNTIME_TOKEN` alias, or `--auth-token`, which other local users can
4252 read in the process list) requires a matching bearer token for `/v1/*` routes. This is a local
4253 convenience guard, not a replacement for TLS, VPN, or a trusted reverse
4254 proxy on public networks.
4255 - **No provider-token custody**. The server never returns the API key. The
4256 `api_key.source` capability field reports `env`, `config`, or `missing` —
4257 never the key itself.
4258 - **No hosted relay**. The app-server is a local process under the user's
4259 control. There is no cloud component.
4260 - **Capability responses** never leak secrets, file contents, or session
4261 message bodies. They report *metadata*: presence, counts, status flags.
4262
4263 ### CORS allow-list
4264
4265 The runtime API ships with a built-in dev-origin allow-list:
4266 `http://localhost:3000`, `http://127.0.0.1:3000`, `http://localhost:1420`,
4267 `http://127.0.0.1:1420`. To add additional origins (e.g.
4268 when developing a UI on Vite's default `:5173`), use any of:
4269
4270 - CLI flag (repeatable): `codewhale serve --http --cors-origin http://localhost:5173`
4271 - Env var (comma-separated): `DEEPSEEK_CORS_ORIGINS="http://localhost:5173,http://localhost:8080"`
4272 - Config (`~/.codewhale/config.toml`):
4273 ```toml
4274 [runtime_api]
4275 cors_origins = ["http://localhost:5173"]
4276 ```
4277
4278 User-supplied origins **stack on top of** the built-in defaults; they do not
4279 replace them. Wildcard origins are not supported — the explicit allow-list
4280 model is preserved. Cross-origin preflights advertise only `Authorization`,
4281 `Content-Type`, `Accept`, `X-Codewhale-Runtime-Token`, and the compatibility
4282 `X-DeepSeek-Runtime-Token` request header; custom request headers are not
4283 allowed (#561, #4454).
4284
4285 ## Managed Fleet Runtime and SDK helpers
4286
4287 `GET /v1/fleet/profiles` reads the captured workspace's effective roster,
4288 including its selected Fleet and admitted plugins, without opening a run ledger.
4289 `GET /v1/fleet/profiles/{id}/document` addresses an exact effective member ID.
4290 Its shared `FleetProfileDocument` contract returns `id`, `kind` (`profile` or
4291 `fleet`), `origin`, nullable `path`, `text`, opaque source-bound `revision`,
4292 `writable` and nullable `refusal_reason`. Personal/project profile documents and
4293 selected Fleet files return exact UTF-8 bytes through a bounded, pinned reader
4294 (one MiB maximum). Changed identity, missing source or linked paths are refused.
4295 Built-in, config-backed and foreign-managed members instead return an explicitly
4296 read-only effective profile projection with no file path; sentinel paths and
4297 native preset entry identifiers are never opened as documents.
4298
4299 All documents currently advertise `writable: false`. No document PUT is exposed;
4300 use the terminal or the defining source to edit. A revision is not write
4301 permission or a live-roster adoption receipt. Watch clients may read these
4302 resources under the existing workspace and authentication boundaries.
4303
4304 The Runtime SDK lives in `npm/runtime-sdk` and is exposed as
4305 the `@codewhale/runtime-sdk` workspace package. It is deliberately thin: every
4306 helper calls the local Rust Runtime API and therefore cannot bypass Codewhale's
4307 sandbox, approval prompts, provider configuration, or fleet ledger authority.
4308
4309 ```js
4310 import { createRuntimeClient } from "@codewhale/runtime-sdk";
4311
4312 const client = createRuntimeClient({
4313 baseUrl: "http://127.0.0.1:7878",
4314 token: process.env.CODEWHALE_RUNTIME_TOKEN,
4315 });
4316
4317 const created = await client.createFleetRun({
4318 target: "this_computer",
4319 roles: [{ name: "reviewer" }, { name: "verifier" }],
4320 workflow: {
4321 id: "release-check",
4322 kind: "parallel",
4323 tasks: [
4324 { id: "review", name: "Review", instructions: "Review locally.", worker: { role: "reviewer" } },
4325 { id: "verify", name: "Verify", instructions: "Verify locally.", worker: { role: "verifier" } },
4326 ],
4327 },
4328 });
4329
4330 // POST /runs only prepares durable work. This call crosses the launch gate.
4331 await client.startFleetRun(created.run.id);
4332
4333 let cursor;
4334 for await (const event of client.fleetEvents(created.run.id, { after: cursor })) {
4335 if (event.cursor) cursor = event.cursor;
4336 if (event.event === "fleet.replay.cursor_unavailable") {
4337 // Reload getFleetRun(created.run.id), then reconnect without the old cursor.
4338 }
4339 }
4340 ```
4341
4342 The managed path is deliberately two-step. `POST /v1/fleet/runs` validates and
4343 persists the run and queue without starting a worker. A separate authenticated
4344 `POST /start` activates it and schedules the executor driver; its `202` response
4345 reports `leased: 0` because the driver performs all leasing after it owns the
4346 run. Creation requires named roles, one task owner per role, a `parallel`
4347 Workflow, and an explicit Runtime target. Codewhale currently executes
4348 only `this_computer`; `another_computer` and `cloud` return `501` rather than
4349 silently executing locally. Worker IDs are generated per run; caller-assigned
4350 `worker_specs` return `501` until custom workers can be given collision-free
4351 managed identities. Parallel tasks with overlapping effective write roots are
4352 rejected before the run is journaled. Managed `security_policy` overrides also
4353 fail closed until that document can be enforced end to end; executable
4354 authority comes from each named role's tool posture and bounded task workspace
4355 scope.
4356
4357 Fleet helpers cover this HTTP surface:
4358
4359 | Helper | Runtime API route |
4360 |---|---|
4361 | `createFleetRun(spec)` | `POST /v1/fleet/runs` |
4362 | `startFleetRun(runId)` | `POST /v1/fleet/runs/{run_id}/start` |
4363 | `listFleetRuns()` | `GET /v1/fleet/runs` |
4364 | `getFleetRun(runId)` | `GET /v1/fleet/runs/{run_id}` |
4365 | `listFleetWorkers(runId)` | `GET /v1/fleet/runs/{run_id}/workers` |
4366 | `getFleetWorker(workerId)` | `GET /v1/fleet/workers/{worker_id}` |
4367 | `updateFleetWorker(workerId, body)` | `PATCH /v1/fleet/workers/{worker_id}` |
4368 | `interruptWorker(workerId)` | `POST /v1/fleet/workers/{worker_id}/interrupt` |
4369 | `stopWorker(workerId)` | `POST /v1/fleet/workers/{worker_id}/stop` |
4370 | `restartWorker(workerId)` | `POST /v1/fleet/workers/{worker_id}/restart` |
4371 | `reviveWorker(workerId)` | `POST /v1/fleet/workers/{worker_id}/revive` |
4372 | `stopFleetRun(runId)` | `POST /v1/fleet/runs/{run_id}/stop` |
4373 | `replayFleetEvents(runId, options)` | `GET /v1/fleet/runs/{run_id}/events/replay` |
4374 | `fleetEvents(runId, options)` | `GET /v1/fleet/runs/{run_id}/events` (SSE) |
4375
4376 `reviveWorker` resumes a stopped, failed, or interrupted native Fleet worker from
4377 its saved checkpoint while keeping `worker_id` and `runtime_thread_id` unchanged
4378 and recording `"continued from checkpoint"` as the turn input source; retired or
4379 unprovable workers return `409 Conflict`. `PATCH /v1/fleet/workers/{worker_id}`
4380 (capability `fleet_worker_model_hotswitch`) validates `WorkerModelPool` and
4381 model/route preflight before saving, defers mid-turn switches to the next turn
4382 boundary, emits `thread.model_changed`, and refuses external/remote workers.
4383
4384 `stopWorker` durably cancels that worker's active task and leaves the rest of
4385 the Fleet running. `interruptWorker` is the compatibility name for the same
4386 attempt-fenced cancellation transition. `stopFleetRun` cancels every queued or
4387 active task and marks the whole run cancelled.
4388
4389 Replay covers aggregate run/task transitions and privacy-bounded individual
4390 worker transitions. Event bodies omit prompts, tool call IDs, completion text,
4391 artifact paths/checksums, and cancellation identities; bounded failure reasons
4392 pass through secret redaction. `cursor` is opaque and stable across ordinary
4393 appends and Runtime restarts. Clients reconnect with `after=<cursor>`. A fresh
4394 request returns a bounded newest tail and marks `history_truncated` when older
4395 history exists. Ledger compaction can remove an old cursor; the JSON endpoint
4396 then returns `409`, while the SSE endpoint emits
4397 `fleet.replay.cursor_unavailable`, so the client reloads the current run
4398 projection instead of accepting a silent gap.
4399
4400 `GET /v1/runtime/info` advertises `fleet_run_create`, `fleet_run_start`,
4401 `fleet_event_replay`, `fleet_event_stream`, and `fleet_local_target`. Older
4402 runtimes without a requested route still produce a typed SDK
4403 `RuntimeCapabilityError`.
4404
4405 A runtime that advertises `fleet_worker_provider_pins` accepts `worker.provider` together with a concrete `worker.model` on a Fleet task. Send the exact configured provider ID. Older runtimes omit the flag, so clients should limit explicit model selections to the inherited provider. A saved member’s pinned route takes precedence and conflicting task pins fail validation.
4406
4407 Use the `fleet_mission_board` capability in `GET /v1/runtime/info` to select the run membership and board APIs.
4408
4409 `GET /v1/fleet/runs/{run_id}/membership` returns the coordinator, the selected run’s task and worker IDs, and transcript availability. A caller can set `coordinator_thread_id` when creating a run. The ID must identify an open thread in the Fleet workspace. When `fleet_worker_thread_executor` is `true`, local native (`this_computer`) workers run in-process on their own Runtime thread with `parent_thread_id` pointing to the coordinator and report `availability: "thread"` directly (while SSH, Tailscale, and external ACP/CLI workers remain on the subprocess path). Legacy subprocess workers report `thread` when one active runtime thread holds their receipt’s saved session, `saved_session` when only the saved transcript is available, or `unavailable`. Read `GET /v1/threads/{id}/fleet-runs` to look up runs from a conversation.
4410
4411 `GET /v1/fleet/runs/{run_id}/board` replays addressed Agent Mail events for one mission. It accepts `after` (a sequence returned by the same board) and `limit` (1–100), and returns `run_id`, `events`, `next_after` and `has_more`. Treat each event as the current delivery record for its `envelope.message_id`. Events carry `sequence`, sender, destination, content and status in the existing mail schema. Subscribe at `/board/events` using `Last-Event-ID` to resume the stream. Both reads leave mail delivery untouched.
4412
4413 `POST /v1/fleet/runs/{run_id}/board` accepts the Agent Mail send body. The Engine verifies both open thread addresses against the same mission and uses the source Engine thread ID as `sender.identity`, then applies the existing idempotency and safe-boundary delivery rules. Reusing a message ID for another mission is a conflict. Older runs without addressable membership remain readable but cannot address a worker until the Engine can prove its current thread. Direct inbox mail from earlier releases is not imported into a run by inference.
4414
4415 Verification:
4416
4417 ```bash
4418 npm test --workspace @codewhale/runtime-sdk
4419 ```
4420
4421 ## Thread Fleet members
4422
4423 `thread_fleet_members` in runtime capabilities enables
4424 `POST /v1/threads/{id}/members`. The body is
4425 `{operation_key, member_id, display_name, prompt, fleet}`, where `fleet` is a
4426 complete Fleet v2 document (the same shape as a saved `fleets/*.toml`, as JSON)
4427 and `member_id` names one of its members with an exact `provider` and `model`.
4428 The thread's Engine starts that member as an ordinary child of the session,
4429 through the same spawn path as the `agent` tool: the member's provider and
4430 model are bound exactly and never fall back to the session route, its
4431 instructions join the child's task prompt as its Fleet profile, and the child
4432 keeps the session's permissions and spawn limits. The document is used for this
4433 start only; it is not saved and does not change the selected Fleet.
4434
4435 Member starts are durable when runtime capabilities report
4436 `thread_fleet_member_durable_operations_v1`. The body may also carry
4437 `expected_store_id` (the `job_operation_store_id` from `/v1/runtime/info`; a
4438 different store answers `409 member_operation_store_changed`) and
4439 `request_fingerprint` (checked against the server's own fingerprint of the
4440 request; a mismatch answers `400 member_request_fingerprint_mismatch`). The
4441 body is capped at 2 MiB (`413`).
4442
4443 Before the Engine is asked, the start is reserved in the Runtime store under
4444 `(store, thread, operation_key)` with a pre-minted `agent_id`, and the child is
4445 spawned under that id and persisted before its acceptance is written. Every
4446 answer is a receipt `{thread_id, member_id, operation_key,
4447 request_fingerprint, runtime_store_id, agent_id, state}`: `200` with state
4448 `accepted` once the child exists, or `202` with state `unknown` when the thread
4449 is mid-turn (host requests are handled between turns) and the start has not
4450 settled within 20 seconds. Read the outcome later with
4451 `GET /v1/threads/{id}/members/operations/{operation_key}`; an unknown key, or a
4452 key that belongs to another thread, is `404`. `accepted` is reported only while
4453 the thread still owns a worker with that id started for that member; otherwise
4454 it reads as `unknown`.
4455
4456 Repeating the same `operation_key` with the same body returns the same receipt
4457 and never starts a second child, including after an Engine restart or a
4458 timeout. A different body under the same key is refused with
4459 `409 member_operation_mismatch`. A reservation that did not produce a child
4460 before the Engine that held it stopped is reported as `abandoned`, and a
4461 repeated start answers `409 member_operation_abandoned`; start again with a
4462 new key. A start the Engine refuses withdraws its reservation, so the same key
4463 may be retried. A thread with a start still in flight cannot be deleted or
4464 discarded until it settles.
4465 The child appears in `/v1/agent-runs` with `owner_session_id` set to the
4466 thread and its `member_id` as `session_name` (a display name may hold spaces or
4467 non-ASCII text, which session names refuse); `agent.spawned`,
4468 `agent.progress` and `agent.completed` arrive on the thread's event stream.
4469 Stop it with `POST /v1/agent-runs/{id}/cancel`, which also stops its
4470 descendants. A second start for a member whose child is still running is
4471 refused by the existing session-name rule; follow up with that child instead.
4472
4473 ## Agent Run Receipts
4474
4475 Sub-agent lanes persist compact run receipts in
4476 `.codewhale/state/subagents.v1.json`. The Runtime API exposes those receipts as
4477 a read-only inspection surface:
4478
4479 | Operation | Endpoint |
4480 |---|---|
4481 | List persisted agent runs | `GET /v1/agent-runs` |
4482 | Inspect one run | `GET /v1/agent-runs/{run_id}` |
4483 | Stop one run | `POST /v1/agent-runs/{run_id}/cancel` |
4484 | Follow up / revive one run | `POST /v1/agent-runs/{run_id}/followup` |
4485
4486 The response is the same worker-record shape surfaced by `agent` receipts:
4487 `spec.run_id`, `actor_kind`, lifecycle `status`, bounded `events`,
4488 `follow_up`, `takeover`, `artifacts`, `usage`, and `verification`. `run_id`
4489 falls back to the worker id for older records, and `{run_id}` may be either the
4490 run id or the worker id.
4491
4492 These endpoints do not start or steer sub-agents. The API surface exists so
4493 app/editor/headless clients can inspect the same handoff receipts that the TUI
4494 and parent model see, and stop a run they are showing.
4495
4496 `POST /v1/agent-runs/{run_id}/cancel` takes no body. It stops the run through
4497 the same session-scoped path as the TUI's stop and the `agent/cancel` tool:
4498 descendants stop with it, and a write-scoped child's changed files are named in
4499 its result rather than dropped. It answers with the worker record:
4500
4501 - `200` when the record is terminal (stopping an already-finished run is a
4502 no-op that returns its receipt);
4503 - `202` when the owning engine accepted the stop but has not recorded the
4504 terminal receipt within a few seconds; poll `GET /v1/agent-runs/{run_id}`;
4505 - `404` for an unknown run;
4506 - `409` when the run belongs to a session this runtime is not hosting (for
4507 example a separate terminal session); stop it from that session.
4508
4509 ## Session lifecycle (native UI supervision)
4510
4511 | Operation | Endpoint |
4512 |---|---|
4513 | List sessions | `GET /v1/sessions` |
4514 | List session summaries | `GET /v1/sessions/summary` |
4515 | Get session | `GET /v1/sessions/{id}` |
4516 | Rename / archive session | `PATCH /v1/sessions/{id}` |
4517 | Delete session | `DELETE /v1/sessions/{id}` |
4518 | Session store repair summary | `GET /v1/sessions/repair` |
4519 | Resume into thread | `POST /v1/sessions/{id}/resume-thread` |
4520 | Create thread | `POST /v1/threads` |
4521 | List threads | `GET /v1/threads` |
4522 | Attach to events | `GET /v1/threads/{id}/events?since_seq=0` |
4523 | Send message | `POST /v1/threads/{id}/turns` |
4524 | Steer | `POST /v1/threads/{id}/turns/{turn_id}/steer` |
4525 | Interrupt | `POST /v1/threads/{id}/turns/{turn_id}/interrupt` |
4526 | Compact | `POST /v1/threads/{id}/compact` |
4527
4528 ## Compatibility tests
4529
4530 Contract snapshots live in `crates/protocol/tests/`. Run:
4531
4532 ```bash
4533 cargo test -p codewhale-protocol --test parity_protocol --locked
4534 ```
4535
4536 This validates that the app-server's event schema hasn't drifted from the
4537 documented contract. CI runs this on every push to `main` and on release tags.
4538
4539 The app-server stdio control surface has its own drift guard — the advertised
4540 `capabilities` method set is pinned in `crates/app-server/src/tests.rs`:
4541
4542 ```bash
4543 cargo test -p codewhale-app-server capabilities
4544 ```
4545
4546 Before a release, run the headless smoke (stdio probe + optional provider
4547 matrix, no secrets leaked):
4548
4549 ```bash
4550 scripts/release/app-server-smoke.sh --matrix # dry-run plan
4551 bash scripts/release/app-server-smoke.test.sh # parser self-test (fake binary)
4552 ```
4553
4554 ## Profile constitution
4555
4556 `profile_constitution` in runtime capabilities enables profile snapshots on
4557 `POST /v1/threads/{id}/turns`. The optional `profile_constitution` field contains
4558 `{accountId, revision, constitution}`. `constitution` is exactly
4559 `{schemaVersion: 1, detail, initiative, collaboration, notes}`; choices are
4560 `brief|balanced|detailed`, `check|judgment|moving`, and `direct|critical|coach`.
4561 Notes are limited to 4,000 Unicode characters. Invalid data is refused.
4562
4563 The authenticated account transport supplies the snapshot, which participates in
4564 the turn's replay identity. The Engine renders it through its existing personal
4565 constitution renderer and records it in native session history. The snapshot is
4566 unchanged across provider retries and compaction. A new snapshot fully replaces
4567 earlier personal preferences. Permissions and approval policy are unaffected.
4568 Internal follow-ups and RLM child calls inherit the admitted preferences;
4569 they do not re-read the host operator's account in the middle of that work.
4570
4571 Without a supplied snapshot, the Engine reads the signed-in profile from the
4572 configured account service at turn admission. When that Engine-loaded profile is
4573 unavailable or invalid, the turn uses the signed-out local constitution and shows
4574 a notice once per session; an invalid host-supplied `profile_constitution` snapshot still fails
4575 the turn, and `GET /v1/constitution` still reports the error. An account without saved
4576 preferences uses an explicit default snapshot; a signed-out account uses the
4577 existing local constitution. Hosted transports always supply the owning
4578 account snapshot, including defaults, so local preferences cannot leak between
4579 accounts.
4580
4581 `GET /v1/constitution` reads the next-turn profile and its model guidance. It is
4582 not a receipt that an active turn adopted the edit. `POST /v1/constitution/preview`
4583 accepts a constitution document and returns `{modelGuidance, saved:false}` without
4584 saving anything. `modelGuidance` is the Engine-rendered guidance body: GET and
4585 preview return identical text for the same document. It excludes the session
4586 record's attribution line or envelope; `source` and `revision` carry provenance.
4587 Both routes use normal Runtime authorization. Older runtimes
4588 must be upgraded before account transports submit profile-bearing turns.
4589
4590
4591 ### Attested watch-event turns (preview)
4592
4593 `watch_event_turns` is true only when the dedicated route and configured Runtime bearer exist. `POST /v1/threads/{id}/watch-turns` accepts only `operation_key`, `prompt`, and `watch_event`. It requires the actual master `Authorization: Bearer ...` header. Device Watch/Drive tokens, cookies, token-header aliases and insecure no-auth do not authorize this route. The existing thread's provider, workspace, tools and permissions remain authoritative; the body cannot grant or replace them.
4594
4595 The closed version-1 receipt is at most 4 KiB when normalized. Required fields are `version`, `platformAccountId`, `projectId`, `watchId`, `watchRevision`, `definitionSha256`, `sourceKind`, `occurrenceSha256`, `eventSha256`, `runId`, `roomThreadRootId`, and `source`. References are bounded ASCII (200 bytes), except `repo` has two `[A-Za-z0-9_.-]` components of 1..100 bytes each (201 including `/`). Revisions are positive safe integers and hashes are lowercase SHA-256. `roomThreadRootId` is empty or a `pm_` id. `sourceKind: "schedule"` carries only `source.slot`, the exact canonical 24-byte UTC ISO schedule occurrence `YYYY-MM-DDTHH:mm:ss.sssZ` with a valid calendar/time (no offsets, date-only or leap seconds); `"github.pull_request"` carries only installationId, bindingId, repo, number, deliveryId and eventName. Unknown fields, mismatched kind/source or grant fields refuse. Runtime-owner attestation does not independently verify Platform's webhook signature or current watch policy.
4596
4597 This manager-owned source uses Runtime provenance through the same turn admission and execution path. It cannot count as a person's answer or resume a goal requiring that answer. The operation fingerprint includes normalized intent, prompt and Runtime-derived owner/thread/workspace context. Fresh admission returns 201, exact replay 200, conflicting intent 409. UserMessage metadata durably retains `input_provenance: "watch_event"`, `watch_event`, SHA-256 of the exact UTF-8 admitted prompt (preserved without trimming for typed watch input) as `input_prompt_sha256`, and the derived `runtime_binding`. Metadata alone never selects this authority. Ordinary `/turns` and the local `/rc` consumer refuse watch authority.
4598
4599 The existing authenticated operation lookup returns the same flat TurnRecord for ordinary turns and additive watch fields from that durable input for watch turns. It holds the existing shared operation claim while reading, creates no record or lock, and never starts a turn. Missing, incomplete or mismatched lookup is not proof of nonadmission. A Platform accepted command ACK precedes native admission; recovery may acknowledge an exact already-admitted receipt but must not send a replacement POST on absence, revocation or uncertainty. Disable/re-enable fencing belongs to Platform's existing queue and revalidation owner. This route does not make revocation atomic with later dispatch or confirm cancellation of earlier accepted work, and it does not implement whole continuous operation.
4600
4601
4602 ### App Server wire migration status
4603
4604 The selected reference is Codex `rust-v0.166.0`, commit
4605 `6ff1e1ca3b30fc8b914720681fcf5fe62e95f856`. The shared RPC envelope and
4606 initialization lifecycle serve JSONL stdio and private-channel WebSocket text
4607 messages. The decoder includes request, notification, response and error
4608 variants with signed-i64 or string IDs. Legacy thread/message and response
4609 events remain compatibility methods; they do not establish Codex thread/turn/item
4610 parity. TCP WebSocket listener, full-tool turn/start, independent Codex subscriptions, bidirectional interactions, durable idempotent
4611 settlement and the complete SDK remain required. The native Engine journal
4612 and turn loop remain authoritative. No default approval deadline is introduced.
4613 Owner restart interrupts active work rather than re-offering pending interactions.
4614
4615 `/v1/chat/completions` admits one nonempty user text message through the existing
4616 manager and journal. Unsupported histories, system/tool messages, tools, images,
4617 streaming and other options refuse before admission. Standard usage and
4618 finish_reason remain null until their native completeness mapping is implemented;
4619 no zero or final-reason guess is made. This bounded compatibility input does not
4620 establish complete chat or Codex parity.
4621
4622 ## Local whale voice
4623
4624 A host-token client can list saved specialists with `GET /v1/whales` and create one with
4625 `POST /v1/whales`. Send a lowercase specialist `id`, a display `name`, and optional
4626 `purpose`, `soul`, `model`, `model_provider_id`, `external_agent_id`, `color`,
4627 `permission_posture`, `child_posture` and `home_thread_id`. A home must be an active
4628 Engine thread created with the same `whale_id`. The Platform owns account-agent associations.
4629 The Engine saves a native TOML profile in the personal agents directory. The
4630 profile ID remains stable when the display name changes. The list response
4631 contains a `whales` array and an `unreadable_profiles` count. Detail and mutation responses contain a single row.
4632
4633 Read `GET /v1/whales/{id}` before editing. Send its quoted SHA-256 `revision` in
4634 `If-Match` with `PATCH /v1/whales/{id}`. A stale revision returns 412.
4635 `DELETE /v1/whales/{id}` retires the source outside profile discovery and
4636 accepts an optional revision. Existing threads keep their captured settings.
4637 `POST /v1/whales/{id}/recycle` accepts an optional `workspace`, creates a
4638 home conversation and returns its `home_thread_id`. Send a unique `Idempotency-Key`
4639 header per user action. Retry with the same key and workspace to recover the original
4640 home. A new action can supersede an interrupted, uncommitted reservation. The original key
4641 then reports that its home is unavailable. A missing specialist returns HTTP 404 with `error.code=saved_whale_not_found`. The previous conversation
4642 remains accessible through the thread API.
4643
4644 A local whale's `SOUL.md` describes its personality and voice. Read the exact local file with `GET /v1/whale/soul` and save it with `PUT /v1/whale/soul`. Both operations require the host Runtime token. The response carries the path, text, revision and writable state. Send the returned revision quoted in `If-Match` with a JSON object containing `text`. A stale edit returns HTTP 412 so the editor can keep the draft. Files are private to the current OS user (mode 0600 on Unix), UTF-8, regular single-link files with a 16 KiB limit. An existing `SOUL.md` requires a matching `whale.toml` identity (`id = "default"`); an absent local whale is created only by an explicit save. A concurrent edit returns HTTP 409 instead of waiting for the other writer. An explicitly imported account whale has a read-only local copy.
4645
4646 The root Engine captures the local whale's voice at turn admission and charges it to the global instruction budget. The instruction receipt includes `whale_soul_source_path` and `whale_soul_revision`; internal follow-ups reuse the captured voice. Its personality applies within the existing permissions.
4647
4648
4649 The additive exact-route inventory and fenced thread-selection fields are documented in [Route inventory](ROUTE_INVENTORY.md).
4650
4650 lines MARKDOWN