返回 CodeWhale
AGENT_RUNTIME.md
根目录 / docs / AGENT_RUNTIME.md
1 # The Codewhale Agent Runtime — one durable substrate, familiar launchers
2
3 > 阅读简体中文版:[zh_hans/AGENT_RUNTIME.md](zh_hans/AGENT_RUNTIME.md)
4
5 This document explains how sub-agents, the headless `exec` path, Agent Fleet,
6 and Runtime relate. These concepts had drifted into *two* parallel "worker"
7 systems. The fix is to make the **Runtime worker run** the durable execution
8 primitive: fleet owns Agent identity, membership, and selection; Runtime owns
9 execution, authority, and lifecycle. "Sub-agent" remains useful product
10 vocabulary for a nested role, but it must not imply a separate execution
11 substrate with weaker lifecycle semantics. It also answers the open direction
12 question in #2972 ("how much Claude Code convergence is right?").
13
14 ## The core idea
15
16 There is exactly **one** thing that runs detached Agent work: a **headless
17 Runtime worker** with a durable execution lifecycle. It is a model loop with
18 the full, authority-gated tool surface that can, in turn, delegate child work
19 through the same lifecycle. Everything else is a way to select, launch, or
20 observe that one Runtime.
21
22 ```
23 ┌──────────────────────────────────────┐
24 │ headless Runtime │
25 │ execution · authority · lifecycle │
26 │ can spawn child workers │
27 └───────────────┬──────────────────────┘
28 │
29 ┌───────────────┴──────────────────────┐
30 │ one durable execution substrate │
31 └───────┬───────────────┬──────────────┘
32 │ launches │ launches
33 ┌──────────────┴──────┐ ┌─────┴────────────────┐ ┌──────────────────────┐
34 │ TUI turn │ │ `codewhale exec` │ │ Agent fleet │
35 │ interactive, in-proc │ │ headless CLI │ │ identity · membership │
36 │ │ │ full tools · stream │ │ · selection │
37 └─────────────────────┘ └──────────────────────┘ └──────────┬───────────┘
38 │
39 └─ selects a Runtime worker
40 ```
41
42 - A **sub-agent** is the user-facing name for a *nested assignment* with a role
43 (`explore`, `reviewer`, `implement`, `test`, ... — see the canonical seven in
44 `docs/SUBAGENTS.md`). It should be backed by
45 the same Runtime worker lifecycle used for a fleet-selected Agent. `agent` is
46 the model-facing launcher, not a second runtime.
47 - **`codewhale exec`** is the headless front door: usable by anyone at any time
48 (CI, scripts, another agent), full tools, emits a `stream-json` event stream,
49 and can spawn sub-agents. It is *the* runtime with a CLI on it.
50 - A **fleet-selected Agent** executes in-process on its own Runtime thread for
51 local native (`this_computer`) workers, or as a Runtime `codewhale exec` run
52 for SSH, Tailscale, and external ACP/CLI workers. fleet supplies identity,
53 membership, and selection; it does not re-implement execution. Runtime owns
54 the durable ledger, scheduling/leasing/retry, authority, local or SSH
55 transport, and terminal lifecycle.
56
57 So "fleet vs sub-agent" is not a choice between execution substrates. fleet
58 answers **who** is eligible and selected, Runtime answers **how and where** the
59 authorized work executes, and sub-agent remains the role/UX vocabulary for a
60 nested assignment.
61
62 ## The cutover rule
63
64 Detached `agent` children and Runtime workers must preserve the same request
65 evidence and recovery state. A timeout after possible dispatch is an unknown
66 outcome on both paths and cannot authorize automatic inference replay, apart
67 from the bounded header-timeout re-send described next.
68
69 The compatibility `agent` runtime retries ordinary rate limits and proven
70 transient connection failures before dispatch. A request that received no
71 response headers is sent again `stream.open_retries` times (default once).
72 After that, a header timeout, like an interrupted stream or other uncertain
73 outcome, preserves a checkpoint and returns a continuation handle without
74 automatically sending another inference request.
75 Reported usage stays attached to the original request; missing usage remains
76 unknown. Restart, remote execution and Runtime-ledger scheduling retain their
77 own durability requirements.
78
79 The target rule is:
80
81 - durable or long-running work goes through the Runtime worker lifecycle;
82 - `agent` should enqueue
83 or observe a Runtime worker run instead of owning an independent
84 lifecycle;
85 - in-process children are allowed only as a small compatibility/latency
86 optimization, and they must expose the same terminal states, retry semantics,
87 receipts, and inspection handles as the durable Runtime path.
88
89 In product language it is fine to say "open a sub-agent". In architecture
90 language that means "start a nested Runtime worker with this role", optionally
91 using a member selected from fleet.
92
93 ## Why this shape (and why it fixes the lag)
94
95 The motivating problem: spawning many in-process sub-agents made the TUI lag,
96 because each child cloned a heavy runtime and rebuilt the whole tool registry,
97 *and* the TUI rendered a full card/transcript per child.
98
99 Surveying Claude Code, Codex, and Kimi, the thing that keeps an orchestrator
100 light at high fanout is **not** a process boundary — all three run sub-agents
101 in-process. It is **isolation + a compact event stream**:
102
103 - a child's transcript **never** flows back into the parent — the parent gets a
104 result summary and a small lifecycle event stream;
105 - the UI renders **counts** (`2 running / 3 done`), not a child session per
106 worker;
107 - each worker's tool surface is built directly from a **role/capability
108 profile**, not "build everything then filter".
109
110 "Headless" therefore means *the execution is not shaped like the UI* — it does
111 **not** mean fewer abilities. A headless worker keeps the full toolset and can
112 spawn sub-agents.
113
114 When the work also needs to be **durable** (survive the TUI closing, a laptop
115 sleeping) or **remote** (SSH), Runtime runs the worker out-of-process as
116 `codewhale exec`. fleet may supply the selected Agent identity, but Runtime
117 retains execution authority and lifecycle ownership. The heavy construction
118 then lives in another process entirely, so the orchestrator stays smooth
119 regardless of fanout, and the run survives restarts — the day-scale autonomy
120 goal of #3154.
121
122 ## One recursion axis
123
124 A worker runs at `spawn_depth = 0` and may spawn children while
125 `spawn_depth + 1 ≤ max_spawn_depth`, so a budget of `N` affords `N` nested
126 delegation levels. Sub-agents and fleet-selected Runtime workers share **one**
127 axis, sourced from `codewhale_config`:
128
129 Runtime delegation defaults to a maximum spawn depth of 3 (`DEFAULT_SPAWN_DEPTH`). Explicit owner depth
130 settings may raise or lower that ceiling and cannot be widened by a child. Zero
131 blocks child delegation while leaving the root worker available. The internal
132 `u32` representation rejects overflow; it is not a suggested work budget.
133
134 The model-facing `agent` schema omits depth controls. Legacy `max_depth`,
135 `maxDepth` and `max_spawn_depth` inputs are parsed for compatibility but ignored
136 when a model requests a child; receipts identify that choice. Exact Fleet and
137 saved-runtime authority remains enforced.
138
139 Workflow IR structure is independent of child delegation. Its `max_depth`
140 default is zero (uncapped); positive operator values are honored. Parser and
141 VM stack/memory boundaries still validate documents before execution.
142
143 ## Event vocabulary
144
145 The Runtime execution ledger persists the worker's own event stream rather than
146 a separate, simulated taxonomy. Compatibility APIs and types still expose this
147 through the `Fleet...` prefix. `codewhale exec --output-format stream-json`
148 emits
149 `{"type": "content" | "tool_use" | "tool_result" | "agent_spawned" |
150 "sandbox_denied" | "workflow_event" | "session_capture" | "service_released" |
151 "turn_usage" | "metadata" | "status" | "request_image_window" | "done" |
152 "error"}` lines, which map onto the Runtime ledger's compatibility type
153 `FleetWorkerEventPayload` (`RunningTool`, `WorkflowEvent`, `Running`,
154 `Completed`, `Failed`, …). `workflow_event` carries the typed
155 run/phase/task/gate receipt while a Workflow is in flight and is retained as a
156 typed `WorkflowEvent` in the Runtime execution ledger; the enclosing Runtime
157 worker still owns the terminal `done` or `error`. One vocabulary, two surfaces.
158
159 `session_capture` is emitted once, when the exec run persisted its transcript
160 as a saved session, and carries the recoverable id in exactly one place:
161
162 ```json
163 {"type": "session_capture", "schema": "codewhale.exec-stream", "schema_version": 1,
164 "content": "<redacted:…>", "saved_session_id": "01J…"}
165 ```
166
167 - `saved_session_id` is the raw saved-session id, emitted only after a
168 successful save. For local Fleet workers, the parent assigns a fresh ID and
169 shares the Runtime's existing session directory. The executor advertises
170 `FleetReceipt.saved_session_id` only when that exact ID was reported and its
171 saved transcript can be loaded. A client with Runtime API access can then
172 read the reply through `GET /v1/sessions/{id}`. SSH workers retain their
173 excerpt and remote log, but do not advertise an unavailable local session
174 link. An ID is a lookup key, not a substitute for Runtime authentication.
175 - `content` is the same redacted fingerprint the terminal `metadata.session_id`
176 carries, so a captured `metadata` receipt stays safe to log on its own and
177 the two events can still be correlated. `metadata.resume_command` therefore
178 names this field (`codewhale exec --resume <session_capture.saved_session_id>`)
179 rather than carrying the id itself.
180
181 The terminal `metadata` receipt also carries the worker's visible final answer:
182 `visible_final_answer_chars` is the real character count of the final
183 assistant reply, and `visible_final_answer_excerpt` is a bounded (4,000
184 characters, `...` when cut), secret-redacted excerpt of it, omitted when the
185 current turn produced no visible answer. Resumed turns never reuse an older
186 reply, and failed/interrupted receipts may carry partial current-turn text;
187 the receipt status remains authoritative. The Runtime executor reads the excerpt from
188 this receipt — never from the streamed `content` deltas, which are the run
189 thinking out loud — and attaches it to `Completed.summary` and, for a task
190 with no scorer and no file artifact, to the receipt notes as the task's
191 deliverable. Lifecycle event labels and worker inspection summaries show a
192 short excerpt; the event `payload` and the receipt keep the full excerpt.
193
194 `turn_usage` is the per-model-call usage receipt, emitted once per model
195 request (turn-step) when the provider reported usage for that call:
196
197 ```json
198 {"type": "turn_usage", "schema": "codewhale.exec-stream", "schema_version": 1,
199 "turn": 1, "input_tokens": 1200, "output_tokens": 180,
200 "reasoning_tokens": 90, "prompt_cache_hit_tokens": 900,
201 "prompt_cache_miss_tokens": 300, "prompt_cache_write_tokens": 0,
202 "reasoning_replay_tokens": 40, "duration_ms": 1834}
203 ```
204
205 - `turn` is the 1-based index of the model call within the exec run;
206 `input_tokens`, `output_tokens`, and `duration_ms` are always present.
207 - Optional token fields are **omitted** when the provider does not report
208 them — never emitted as null and never backfilled with zeros. Field names
209 mirror the terminal `metadata` receipt: `prompt_cache_hit_tokens` is the
210 provider's cache-read count (Anthropic `cache_read_input_tokens`),
211 `prompt_cache_write_tokens` the cache-creation count
212 (`cache_creation_input_tokens`). `reasoning_tokens` appears only for
213 provider paths that report it (OpenAI-compatible
214 `completion_tokens_details` / Responses `output_tokens_details`; Anthropic
215 does not report a thinking-token count). `reasoning_replay_tokens` is a
216 client-side estimate for DeepSeek V4 interleaved-thinking replays.
217 - `finish_reason` is the provider's stop reason for that step (for example
218 `stop`, `tool_calls`, or `length`), omitted when the provider reported none.
219 - When a provider reports no usage at all for a call, the whole event is
220 skipped for that call. Latency/convergence analysis should sum
221 `turn_usage` events instead of inferring per-step tokens from wall time;
222 the terminal `metadata` receipt carries the cumulative totals when the
223 provider reported them, and its `usage_status` says whether they are
224 `complete`, `partial` or `unreported`.
225
226 ## Convergence with Claude Code (#2972)
227
228 Codewhale should converge with Claude Code on **shape**, not on branding:
229
230 - **Adopt**: a headless runtime with a real CLI/SDK front door; sub-agents as
231 isolated runs that return summaries (not transcripts); a compact, event-driven
232 fanout projection; capability/role tool profiles; the skills ecosystem
233 (#2743); structured run receipts.
234 - **Keep distinct**: Codewhale branding and first-class DeepSeek/GLM/MiniMax/
235 multi-provider support; the local-first **Agent fleet** as the identity,
236 membership, and selection layer; durable local/SSH execution and authority in
237 Runtime; Workflow as the ordering overlay.
238 - **Do not** fork execution semantics per surface. The TUI, `agent`,
239 `exec`, and the Runtime API must all drive the *same* Runtime and observe the
240 *same* event stream. fleet selections are passed to that Runtime rather than
241 creating a second execution path — divergence there is what produced the
242 "two moving targets" this document exists to prevent.
243
244 The litmus test for any new agent surface: *does it launch and observe the one
245 runtime, or does it invent a second one?* Only the former is allowed.
246
247 ## Historical note: what remained after v0.9.0
248
249 Archived roadmap snapshot — live state is the issue tracker, not this list.
250 Refreshed 2026-08-17 from a full audit of the older 0.9-era documents. Those
251 plans are evidence, not a second source of truth. v0.9.0 consolidated the
252 underwater shell, message-first Operate, permission postures, the wired
253 Workflow engine and durable run journal, Lane CLI/runtime, setup with
254 `operate_ready`, constitution rebalance, and ProviderLake/Models.dev. The
255 remaining work belongs to later releases:
256
257 1. **Rebrand completion** — the `deepseek`/`deepseek-tui` binary shims and
258 shim release assets have been removed; the remaining obligation is the
259 Homebrew `codewhale` formula rollout (`docs/REBRAND.md`).
260 2. **Operate as a value stream** — a control-board surface over the underwater
261 shell (WIP, queue age, bottleneck); phase history (#4039); Workrooms Phase 2
262 (#3209/#3210) as the inbox substrate;
263 receipt reconciliation.
264 3. **Flow control** — real WIP limits and visible queues (#4015, #4016),
265 reconciled with the shipped 16-concurrent/1k-run access model (#4292).
266 4. **fleet identity and Runtime/Workflow convergence residuals** — live
267 tmux/verifier-gate dogfood closing #4175/#4177/#4178/#4179; fleet consuming
268 canonical AgentProfiles and selecting members while Runtime owns execution;
269 Conductor/topology (#4010, #4012) as stretch.
270 5. **TTC design implementation** (design doc in `codewhale-ops`) — approved and now unblocked after v0.9.0.
271 6. **HarnessProfile completion** — the status/UX display lane
272 (`docs/rfcs/HARNESS_PROFILE_CUTLINE.md`).
273 7. **File decomposition, landed** — the v0.9.0-era offenders were split out:
274 `main.rs` is now a thin stub and `ui.rs` has been decomposed into focused
275 modules under `crates/tui/src/tui/` (~3.9k lines today; the
276 `docs/rfcs/FILE_DECOMPOSITION_0_9_0.md` figures are the 0.9.0-era snapshot).
277 The remaining work is the "thin TUI over core" north star tracked in
278 `docs/design/POST_0_9_1_SEAMS.md`.
279
280 Explicitly deferred by their own documents: external workflow memory (boundary
281 only), automatic harness evolution, hosted workrooms, `constitution_modules`
282 (needs sign-off), permission profiles (#3211, needs design), and plan-ceiling
283 probing (needs a product decision).
284
285 ## Public launch contract for an external harness (#4641)
286
287 An external evaluation harness (for example a future Verifiers v1 built-in
288 harness) embeds Codewhale by launching the public `codewhale exec` front door
289 against an interception endpoint it owns. Codewhale owns only its **launch
290 contract**; the harness owns interception, traces, model-call timing, token
291 accounting, retries, rollout limits, and runtime orchestration. Do not add a
292 harness runtime, trace parser, or receipt schema to Codewhale.
293
294 A reproducible headless launch uses only existing generic surfaces:
295
296 - an explicit temporary config that names the route and the credential
297 **environment variable**, never the secret itself:
298
299 ```toml
300 provider = "openai"
301
302 [providers.openai]
303 base_url = "" # the harness fills in its interception endpoint
304 model = "" # the harness fills in the target model
305 api_key_env = "VF_CODEWHALE_API_KEY"
306 ```
307
308 - `CODEWHALE_HOME` set to a fresh per-run directory;
309 - `CODEWHALE_SECRET_BACKEND=file`;
310 - `CODEWHALE_MCP_CONFIG` pointing to a generated per-run MCP JSON file that
311 contains only the task servers the harness supplies
312 (`{"mcpServers":{"task-tools":{"url":""}}}`; the `mcpServers` alias and
313 URL-based Streamable HTTP / SSE transports already exist);
314 - `CODEWHALE_MEMORY=false` and `CODEWHALE_TELEMETRY=false`. Codewhale defaults
315 usage counting on with an opt-out. Every sealed harness explicitly
316 sets the run-scoped kill switch so a test cannot collect or send from a
317 fresh or reused home. Ordinary enabled sessions send aggregate counts to an endpoint
318 (`https://telemetry.codewhale.net/v1/telemetry`, the shipped default) rather
319 than to a local file. It is a hard floor — an explicit "off" in the
320 environment beats `--telemetry true` and `telemetry = true` in config. Set
321 `CODEWHALE_TELEMETRY_ENDPOINT=` (empty) instead if a harness wants an enabled
322 home to keep buffering locally without contacting anything. See
323 [`docs/TELEMETRY.md`](TELEMETRY.md);
324 - `CODEWHALE_ALLOW_INSECURE_HTTP=1` **only** when the harness supplies a
325 trusted `http://` interception endpoint (container/tunnel endpoints are not
326 always loopback);
327 - `--append-system-prompt` and `--disallowed-tools` when the caller supplies
328 them.
329
330 The interception secret stays in the child environment (resolved through the
331 route's `api_key_env`); it is never written into argv, the route config, logs,
332 the `stream-json` stream, or any generated file.
333
334 The exact argument order is:
335
336 ```sh
337 codewhale \
338 --config .vf-codewhale/config.toml \
339 --workspace . \
340 --no-project-config \
341 --skip-onboarding \
342 exec \
343 --auto \
344 --sandbox danger-full-access \
345 --output-format stream-json \
346 -- "<task prompt>"
347 ```
348
349 `--no-project-config` must appear **before** the subcommand (like
350 `--skip-onboarding`). The public dispatcher parses it and forwards it ahead of
351 the TUI subcommand; `Exec` then skips the workspace-specific
352 `[workspace]`/`[projects]` user-config overlay so the config surface depends
353 only on the explicit `--config`. `crates/tui/tests/integration/verifiers_harness_contract.rs`
354 is the provider-free acceptance lock for this contract.
355
356 ### Future upstream checklist (out of scope here — do not run)
357
358 Actually adding Codewhale as a built-in harness lives in the external Verifiers
359 repository; the public, immutable Codewhale GitHub Releases with checksum
360 manifests are published on GitHub Releases.
361 That upstream change is expected to be limited to a new
362 `verifiers/v1/harnesses/codewhale/` package plus its test-matrix and docs
363 registration, with `CodewhaleHarnessConfig` pinning the target release,
364 `setup()` downloading and verifying the released archive, and `launch()`
365 writing the temporary route/MCP files above and calling `runtime.run_program(...)`.
366
367 Holdouts, explicitly **not** performed by this contract work: tagging,
368 publishing, or creating a Codewhale release; opening or submitting the upstream
369 Verifiers PR; running its credentialed E2E matrix; or claiming
370 runtime/architecture support before the exact released archive has run in that
371 upstream runtime.
372
372 lines MARKDOWN