返回 CodeWhale
TS_EXTENSION_HOST.md
根目录 / docs / design / TS_EXTENSION_HOST.md
1 # Codewhale TypeScript extension host: design
2
3 > **Repository copy.** This is the design as reviewed on 2026-09-25, copied from
4 > the private release plan (`codewhale-ops/releases/0.10.1/plans-20260925/`) so
5 > the code and its design live together. The "As built" sections below
6 > record where the implementation (`crates/engine/extension-host/`,
7 > `crates/engine/src/extension_host/`, behind `[features] extension_host`) differs
8 > from the text that follows. Where they disagree, the newest "As built"
9 > section and the code are current; the rest is the plan for later phases.
10
11 ## As built: independent Computer Use plugin (2026-10-26)
12
13 Computer Use is installed and updated through the ordinary plugin catalog. Its
14 runtime and native Mac helper are no longer embedded in the Engine. References
15 below to the former CU embedding are historical design evidence, not the
16 current CU distribution contract. The TypeScript extension host retains its
17 own packaging; it does not own or distribute the CU runtime.
18
19 ## As built: authored prompt sections, owner-local storage and invocation identity (2026-10-02)
20
21 `prompt` and `storage` are host-provided shim services whose replacement is
22 refused. `ctx.prompt.registerSection({id, text})` uses the existing owned
23 registration lifecycle and Rust's reviewed owner registry. Live snapshots are
24 scoped to one Engine attachment, validated against its desired plugin hashes
25 and current Native authority before and after collection, and sorted by
26 owner/id. Rust bounds raw text, section counts and the final attributed block;
27 the existing user-role runtime-message path delivers the complete bounded
28 snapshot at turn boundaries, including explicit withdrawal, without changing
29 the pinned system header or truncating it into workspace context deltas.
30 An author cannot replace the system prompt or choose another session. See
31 `docs/EXTENSIONS.md` for the exact byte/count limits and grammar.
32
33 `ctx.storage.get`, `set` and `delete` expose bounded plain JSON in the directory
34 Rust assigned to that owner. Atomic per-key replacement, corrupt-data refusal, symlink
35 refusal, serialized owner writes and live-owner checks preserve local state.
36 Storage has no session-history or credential access and introduces no protocol
37 method. It remains plugin-local state in the existing directory, rather than
38 another Codewhale session store.
39
40 `tool/call` and `command/run` add optional `session_id`, `agent_id` and
41 `origin_turn_id` wire strings. The host exposes only supplied fields as frozen
42 per-call `sessionId`, `agentId` and `originTurnId`; no identity is cached during
43 activation. A user slash command supplies its known session only. These are
44 labels, not handles or new authority. Older callers can omit every field.
45
46 ## As built: programmable pre-execute mods (2026-10-02)
47
48 `ctx.on('tools/pre-execute', (exec, next) => ...)` now registers an owned `hook` handle through Cordis's `internal/listener` extension point. `hook/evaluate` is core-to-host only, carries a Rust-composed frozen call projection with DSH's `name`, `arguments`, `callId`, and cancellation `signal` spelling, and accepts monotonic `abstain`, `deny`, `ask`, `annotate`, and `revise` proposals. DSH `allow` maps to abstention; unsupported answers fail closed. No runtime, session, agent, invocation ticket, or approval handle is given to a listener.
49
50 `HostAttachment::tool_before_hooks` scopes dispatch to this engine's desired reviewed owners, validates Native authority and owner generation before and after dispatch, and uses the existing owner cancellation and host supervision. Native hook results followed by TypeScript proposals enter `fold_tool_call_before_results`; the existing `reprepare_tool_call_after_hook` and all later policy/approval gates consume the revised arguments. Strict no-verdict semantics cover malformed replies, errors, the bounded five-second listener batch, and revocation. Multiple listeners share the existing deny/ask/last-input/context fold. The real-host acceptance drives native reads and a read-to-write revision through a real Engine, alongside owner withdrawal and workspace isolation.
51
52 This is the bounded pre-execute part of phase 4. It does not implement DSH's around-execution waterfalls or replace its agent/token runtime; `next()` is an abstention rather than tool execution. `prepend`/`global`, post-result transformations, and lifecycle events remain absent. Standalone ACP has no TypeScript attachment; its native hook contract is preserved.
53
54 ## As built: `core/call`, capability tickets and the gate for extension tools (2026-10-02)
55
56 Slice B of the tier plan, and the first thing the host can ask the core to do.
57 Still protocol v1 (a new method and an optional field); corpus `22`, `58`-`66`.
58 User-facing rules: `docs/EXTENSIONS.md`, "Asking the core to run a tool".
59 Nested shell and network calls force a fresh user prompt under the accepted
60 Slice B contract, including semantic action aliases. The separate routing hook
61 remains outstanding; programmable pre-execute proposals do not implement it.
62
63 - **Protocol.** `core/call` (host to core, request, both tiers)
64 `{owner, ticket, name, input}`, answered with the existing `ToolResultWire`;
65 `core_call::` below. New error codes `Refused` (-32002: policy, a limit, an
66 invalid ticket) and `Denied` (-32003: the user declined the card).
67 `tool/call` gains an optional `ticket`. `host_protocol_never_gains_core_authority`
68 has its reviewed row for `core/call` and was not weakened (the method name
69 mentions none of the core-only words); corpus `22` flipped from invalid to
70 valid and was renamed.
71 - **Tickets** (`extension_host/ticket.rs`). A Rust-minted opaque id (244 random
72 bits) indexing a Rust-side row `{kind, tier, host_generation, owner, method,
73 target, expires, uses_left}`. `TicketKind` has one variant, `Invocation`
74 (multi-use, budgeted); a process launch, fetch or MCP grant join with their
75 redeemers. `redeem` checks every field under one mutex (kind, tier, host
76 generation, the whole `OwnerRef`, method, a stated target as parsed JSON,
77 expiry, uses) and refuses an unknown, expired, replayed (exhausted), wrong-owner,
78 wrong-tier, wrong-generation or wrong-method ticket. Which field mismatched is
79 not told to the host. Eight invalid presentations within a minute from one
80 host process are a protocol violation (`HostRequestContext::violation` ends
81 the host through the reader's kill path); a valid ticket merely out of uses
82 does not count. Tickets are never persisted or logged (`Ticket`'s `Debug` is
83 redacted; nothing quotes one) and are revoked when the invocation ends (the
84 guard's `Drop`, so also when the tool call's future is dropped), when the
85 owner is revoked (reconcile, `ext/faulted`) and when the host exits.
86 Backstop expiry is 24 h: an invocation's life is bounded by its own deadline,
87 which pauses while a person decides, so a short ttl would be wrong.
88 - **Where one exists.** `HostToolSpec::execute` mints an `Invocation` ticket only
89 when the tool's context carries a `NestedCallGate` that the turn loop built
90 *for this tool* (`NestedCallGate::for_extension(caller, specs)`; the tool
91 checks the caller matches its own). The turn loop attaches one when a
92 registry spec says `extension_caller()` (a `ToolSpec` method, default
93 `None`), in `execute_tools_with_nested_gate`, the same function that serves an
94 `execute_tools` program's gate, in a sub-agent's turn as in the session's. A
95 test and a tool nested in `execute_tools` (whose invoker takes the gate from
96 the nested context) have none, nor does any command, timer or activation: the
97 tool gets no `exec.core` and a forged request finds no ticket.
98 - **One gate, one executor.** The turn loop serves the request with
99 `gate_nested_call`, now parameterised by who is asking
100 (`ToolCallSource::Extension`), so planning is `plan_tool_calls` unchanged
101 (budget, allow/deny lists, preparation, hooks, ask-rules, Auto-Review, repo
102 law, the authority envelope, the fleet guard). The caller side is the same
103 `CodemodeInvoker` code mode uses (`for_extension`; `invoke` is now `call` plus
104 a mapping): the concurrency cap, the exclusive/shared order lock, the
105 `PauseClock`, the receipts, the result bounding and spill. What this removed
106 rather than copied: nothing about the executor was duplicated; the only new
107 code in `codemode.rs` is the withdraw plumbing and the `NestedFailure` type
108 that lets a caller see the decision (code mode maps it back to
109 `DriverError`).
110 - **Refused outright** (`core_call::refusal`), before planning on the host's
111 name and again by the turn loop on the name planning resolved and the final
112 input (after a hook rewrite): everything `refusal_before_gate` refuses; any
113 extension tool (`ToolSpec::extension_caller`, found by case-insensitive name
114 and by canonical alias), the caller's own tool included; `mcp_*` and the MCP
115 resource tools, Computer Use included (founder's default: not in v1); tool
116 search and `retrieve_tool_result`; `remember`; and a name table for what
117 changes or schedules beyond the session (`request_plugin_install`, goals,
118 `automation*`, `send_later`, starting MCP servers). Names compare ASCII
119 case-insensitively and by canonical alias.
120 - **Approval** (`core_call::origin_approval`, applied at the end of
121 `plan_tool_calls` for `Extension` and only ever raising). `Required` unless the
122 tool is in `EXT_AUTO_ELIGIBLE` (`read`, `read_file`, `list_dir`, `file_search`,
123 `grep_files`; a test pins each as a registered, read-only, auto-approved tool;
124 the action-based `Git` tool is left out until its read-only actions can be
125 told apart by name) *and* planning found nothing
126 that asks. Shell and network (the registered tool's capabilities and concrete
127 execution-envelope classification, plus the authority categories and `web.run`,
128 `git_fetch`, `run_tests`, `run_verifiers`)
129 set `approval_force_prompt`. The card text is composed in Rust ("Requested by
130 `extension:<plugin>` from inside its tool `<tool>` (core/call): ...") and the
131 audit events say `caller: extension` with the extension and tool. Keys are
132 origin-scoped (`extension_origin_approval_keys`: `extcall:<ext:plugin@hash>:`
133 plus the usual key), so a grant for the model's call never covers an
134 extension's and the reverse.
135 *How "forced" meets the existing postures* (a documented choice, tested in
136 `extension_calls_resolve_against_every_posture_as_documented`): the engine
137 always raises the card with `approval_force_prompt`; what answers it is
138 `resolve_approval_request_disposition`. Ask and Full Access: a modal every
139 time, no session grant consulted. The Engine-minted `extcall:ext:` approval
140 namespace identifies extension-origin calls; host labels cannot select this
141 policy. Explicit session denials still win. Other forced policy holds retain
142 their Full Access refusal. Never refuses these extension calls without opening
143 a card, while Auto-Review routes held extension calls (including these forced
144 nested calls and held plugin host tools) to the Auto-Review guardian with
145 host-minted plugin identity and no routine or allow-rule bypass. Every other call an
146 extension makes (Required, not forced) is, in Full Access, auto-approved as the
147 model's would be, and in Ask promptable and groupable under the extension's
148 own keys.
149 - **Two fixes the plan named.** (1) `await_tool_approval` takes an optional
150 withdraw token (`request_tool_approval_until`; the old name is a wrapper):
151 when it fires the wait ends with a `Cancelled` outcome in the approval log, a
152 status line and a cancelled error, and the call is never decided for the
153 person. The token fires on the host's `$/cancel` of the request, the owner's
154 revocation, the host's exit and the invocation's end (which includes the
155 tool call's deadline and the turn being cancelled); a request withdrawn
156 before the server starts it is dropped unplanned (`NestedCallRequest::is_stale`).
157 (2) `HostProcess::call_with_clock` measures the `tool/call` deadline on the
158 invocation's `PauseClock`, paused while any `core/call` waits on the gate
159 (`call` is the same with a clock nothing pauses), so a person taking a minute
160 on a card does not time the tool out; the deadline is otherwise as before.
161 - **Caps.** Per invocation 50 core calls in all (the ticket's uses), 4 at once
162 (code mode's `MAX_CONCURRENT_CALLS`; a fifth waits for a slot), and one
163 approval card at a time (the turn loop serves one gate request at a time; a
164 second call needing approval waits behind the first); per host 256 requests in
165 flight (A2's table). The call's result metadata gets `core_calls`: at most 50
166 receipts (decision, status, bytes, a note cut at 256 bytes).
167 - **Host.** `exec.core.call(name, input?, {signal?})` (`src/shims/core.ts`),
168 present on a tool's `exec` only when the call carried a ticket (so the frozen
169 `exec`'s keys are unchanged otherwise); it answers `{content, isError,
170 structured?}` or rejects with `CoreCallError` whose `code` is `refused`,
171 `denied`, `cancelled`, `unavailable` or `failed`. The host refuses locally
172 what it must not send (a bad name, input that is not plain JSON). The tool's
173 `exec.signal` and an optional per-call signal send `$/cancel` for the pending
174 `core/call`. The ticket is never exposed to plugin code. No DSH equivalent was
175 found in the vendored DSH surface (DSH reaches tools through its own
176 `ToolRuntime` service, which the host deliberately does not provide), so there
177 is only the Codewhale-native API.
178 - **Tests.** Rust: the ticket table (every field, expiry, exhaustion, burst
179 window, revocation, redaction); spoofing against `serve` (wrong owner, other
180 token, other tier, generation bump, unknown, after revoke/exit/end); the real
181 host through a stand-in gate (read plus receipts, every refusal in many
182 spellings before the gate is asked, no ticket without this tool's extension
183 gate, a command has no `core`, a held approval outliving a 1 s deadline,
184 withdrawal on drop, owner revoke and host kill, 50 total and 4 concurrent);
185 the real turn loop with a fake extension tool (forced prompt in Ask and Full
186 Access with Rust-composed card and extension-scoped keys, read unprompted and
187 write carded, refused calls raise no card, a withdrawn card recorded
188 cancelled, one card at a time) and `await_tool_approval`'s withdraw token on
189 its own; the refusal list and the approval table; the posture matrix; the key
190 scoping in both directions; the corpus and the lint. JS: `exec.core` against a
191 fake core (payload, absence without a ticket, every error code, local refusals,
192 cancel, concurrency).
193
194 Withdrawn calls emit the typed `ApprovalWithdrawn` identity after committing the
195 cancelled outcome. Terminal and runtime clients retire the matching card and
196 continue draining events; a queued allow cannot win over a ready cancellation.
197 Headless Full Access also refuses these forced holds.
198
199 Not done: no per-plugin process (a
200 ticket narrows a frame, it does not isolate plugins sharing the host, section
201 4.4); images and rich content from a core tool are dropped; the refusal table
202 names tools (a new mode/permission tool must be added); no `core/call` from a
203 command, a timer or activation (by design: they return a proposal); `mcp_*`
204 stays out until the MCP move.
205
206 ## As built: the tier in the handshake, method tiers and host requests (2026-10-02)
207
208 Slice A2 of the tier plan. It adds the three things A1 listed as not done that
209 need no new method. Still protocol v1; the TypeScript shapes are regenerated and
210 corpus fixtures `51`-`57` cover the new hello fields.
211
212 - **`host/hello` says what the host is.** It now carries `tier`
213 (`plugin`|`builtin`, the `--tier=` the host was started with) and
214 `builtin_modules`, one `{id, sha256}` row per built-in module source the host
215 *build* embeds, in id order. `build.mjs` builds the built-in modules first and
216 substitutes their digests into the host bundle, so the bundle states them
217 itself and stays deterministic. The core checks both the way it checks the
218 runtime name and version, in `supervisor::check_hello_identity`, and refuses
219 a mismatch before `host/initialize`: a tier other than the one in the launch
220 plan, or a module list that is not exactly the one the Rust table
221 (`tier::BUILTIN_MODULES`, carried on the launch as `builtin_modules`) pins.
222 Both fields are required (a host that omits one is a protocol violation, not
223 a legacy host: the bundle is embedded and always the same build). Today the
224 table and the list are empty. This is drift protection between the two halves
225 of one build, not authentication: a substituted host reports whatever it
226 likes, as `bundle_sha256` already allowed (§4.4, threat 1).
227 - **A tier allow-list per method.** `protocol::MethodSpec` has `tiers`, the
228 trust tiers whose host may send (host to core) or be sent (core to host) the
229 method; `row()` gives both and a reserved method is written
230 `MethodSpec { tiers: &[HostTier::Builtin], ..row(..) }`. It is enforced in both
231 directions on both sides: `admit_in` refuses a frame from a host of the wrong
232 tier like an unknown method (a protocol violation), `HostProcess::start_request`
233 refuses to send a method the host's tier may not receive (`MethodNotFound`,
234 nothing is written), and the host's `validateMessage(.., tier)` refuses both
235 what it would send and what it is sent. The generated `METHODS` table carries
236 `tiers`. No method is reserved yet (the first are the process broker, the
237 fetch proxy and the MCP client: `proc/*`, `net/*`, `mcp/*`; a test pins that
238 any method with those prefixes can never allow the plugin tier); the mechanism
239 is tested with test-only reserved rows in Rust and in the host's tests.
240 - **Host requests are tasks.** The reader no longer answers `registry/*`
241 inline. Each host request is admitted into an id table
242 (`supervisor::InboundRequests`, at most 256 in flight and no id reused in
243 flight, the same bound the host holds itself to; either is a protocol
244 violation that ends the host), runs as its own task through
245 `HostEvents::host_request` (an async trait method whose default answers the
246 registry requests exactly as before) and is answered when it finishes. It is
247 cancelled by the host's `$/cancel {id}` (the answer, if the handler still
248 produces one, is dropped; a cancel for an id not in flight is ignored), by
249 its owner's revocation (`revoke_calls_of`: the host is answered `Cancelled`)
250 and by the host's exit (nobody is answered). A handler gets a
251 `CancellationToken` it should wait on; one that ignores it is abandoned
252 500 ms (`CANCEL_GRACE`) after the cancel, so a cancelled request never holds
253 its slot. The host half: `RpcPeer.request(method, params, signal)` sends
254 `$/cancel` for its id and rejects as cancelled when the signal aborts.
255 - **Tests.** Rust: the hello identity rules (tier, missing, extra, changed and
256 repeated modules), a real host refused for a launched/reported tier mismatch
257 and for a pinned module its bundle lacks, the id table (cancel, late answer,
258 abandoned handler, revoke, exit, cap, id reuse, default registry answers), the
259 tier rule over a reserved test table, the corpus under both tiers, and the
260 generated-TypeScript drift test. JS: the corpus under both tiers, a reserved
261 test row refused to a plugin host in both directions, the hello fields, and
262 `RpcPeer` cancellation.
263
264 Not done: any reserved method (nothing needs the builtin-only tier before the
265 MCP move). The first host request that can be cancelled, `core/call`, is the
266 next section.
267
268 ## As built: trust tiers (2026-10-02)
269
270 Slice A1 of the tier plan (CURRENT_DECISIONS §26 D3, §1.5 above): the host is
271 now two processes' worth of machinery, one per trust tier, and nothing else
272 about it changed. No wire change, no new behaviour for a plugin author. What
273 exists:
274
275 - **Two tiers** (`extension_host/tier.rs`, `HostTier { Plugin, Builtin }`).
276 *Plugin* hosts reviewed third-party plugins; its owner ids are the plugin ids
277 discovery builds (`<scope>/<12 hex>/<name>`). *Builtin* (tier 0) is for
278 Codewhale's own host code and its owner ids are `host:<module>`. The id
279 spaces cannot meet: `OwnerRegistry::begin_owner` takes the tier and refuses a
280 `host:` id on the plugin tier and any other id on the builtin tier, and an
281 authority that does not fit (a plugin owner needs its reviewed plugin
282 authority, a module has none); every owner entry, tool and command
283 registration records its tier. Discovery cannot produce a `host:` id (a
284 manifest name cannot hold `:`, and an id starts with a scope name), a test
285 shows such a plugin failing validation, and `desired_owners` checks the id
286 once more before it reaches the host.
287 - **An empty production table.** `BUILTIN_MODULES` (`BuiltinModule { id,
288 source_sha256, tools: &[Tier0Tool { name, approval }] }`) is empty, so
289 nothing asks for the builtin tier and **it never spawns**; plugins behave
290 exactly as before. "Needed" currently means "has a row". A tier-0 tool's
291 approval comes only from this Rust table (`Auto` or `Required`); an unlisted
292 tool or module is `Required`, and the module's own say changes nothing. It is
293 still never read-only for plan mode. The manager holds the table
294 (`ManagerShared::builtin_modules`, the production const unless a test builds
295 the manager with `with_builtin_modules`), so a test exercises tier 0 without
296 a production row. A module's source is
297 expected at `<bundle dir>/builtin/<module>.mjs` and is activated only if its
298 SHA-256 is the pinned one (otherwise a failed owner with the reason, no host
299 started); nothing materializes such a file yet because there is no module.
300 - **Per-tier supervision.** `ManagerShared` holds two `TierRuntime`s (host
301 slot, generation, spawn count, crash and restart state), lazily spawned. The
302 owner registry, the runtime pin, the attachments and plugin settings stay
303 shared, so both hosts run on the same pinned runtime and one registry says
304 which tier an owner is in. A host's exit, restart, heartbeat and dirty
305 teardown touch only its own tier (`OwnerRegistry::host_exited(tier, ..)`).
306 A host answers `registry/*`, `log` and the like only for owners of its own
307 tier. Lock order, restated at `ManagerShared` and kept: `sync_lock`, then one
308 tier's host slot, then that tier's supervision state, then the registry; no
309 path holds both tiers' slots, and the other locks are leaves.
310 - **Supervisor.** `plan_launch` and the sandbox plan take a tier. The argv ends
311 `<bundle> --tier=plugin|builtin`. The plugin tier's data directory, working
312 directory and writable root are what they always were,
313 `extension-host/data`, so the per-plugin directories under it
314 (`data/plugins/<name>-<hex>`, unchanged and pinned by a test) keep their
315 data. The builtin tier's is **`extension-host/data-builtin`**, a sibling and
316 not `data/builtin`: a child would lie inside the plugin tier's writable root,
317 and the host sandbox has no per-subpath write deny, so plugin code could
318 then write tier-0 state. The plugin tier's read deny list names the builtin
319 directory explicitly (unit test on the path function). A built-in module's
320 own directory is `data-builtin/modules/<module>`. Under bubblewrap a builtin
321 directory that did not exist when the plugin host started cannot be masked;
322 Seatbelt denies it by name before it exists.
323 - **Host.** `--tier=` is parsed before anything else; an unknown value, a bare
324 `--tier` or a tier named twice exits with 64 before `host/hello` (no
325 `--tier` means `plugin`, the least-privileged). `ext/activate` for an owner
326 of the other tier (decided by the `host:` prefix) is refused with
327 `InvalidParams`, before anything is read or loaded. `dist/` was rebuilt.
328 - **Drift check.** `build.mjs` builds each `src/builtin/<id>.ts` to
329 `dist/builtin/<id>.mjs` and writes the SHA-256 of each to
330 `dist/builtin-modules.json` (`{"modules": {}}` today); a Rust test
331 (`tier::tests::table_matches_the_host_build`) fails when `BUILTIN_MODULES` and
332 that file disagree in either direction. A module that would bundle a
333 `node_modules` package fails the build until its licence notice is handled.
334 - **Activation policy** is untouched: v4 and its pinned digest test pass
335 without change, because tier-0 modules are not plugins and no installed
336 plugin is re-reviewed.
337 - **Tests.** Rust: owner/tier refusals and per-tier crash isolation in the
338 registry, a host answering only for its own tier, a `host:`-named manifest
339 failing validation, launch plans (argv, data directories, deny list, the
340 unchanged per-plugin path), the drift test, the table's approval lookup, a
341 tampered or missing module refused with no host started, production never
342 spawning the builtin tier, and (test table) a tier-0 host spawning apart from
343 the plugin host, activating `host:tier0-module`, its tools' approval
344 following the table, a call through it, and a plugin-host crash leaving it
345 alone. JS: refusal of bad `--tier` values, each tier refusing the other's
346 owners, `host:` activation on the builtin tier, and the dist digest file
347 matching `dist/builtin/`.
348
349 Not done, and not claimed: any real tier-0 module (the MCP move, §5, is the
350 first consumer); `host/hello` reporting a tier or module digests and a
351 per-method tier allow-list (done in slice A2, above); capability
352 tickets (landed with their first redeemer, `core/call`, in the section above); embedding or
353 materializing a module's source; a bundled tier-0 executable (D1); a demand
354 predicate that defers the builtin spawn until something needs it; the builtin
355 tier's sandbox denying the plugin tier's data directory (it can read it today);
356 `/plugin` listing the builtin host's modules and tools beyond one status line;
357 tier-0 commands or tools being offered to the model (an engine installs plugin
358 owners' tools only).
359
360 ## As built: plugin context, several entries, input validation, notices (2026-10-01)
361
362 A review of the commands slice found four defects and one gap in what an author
363 can do. This section is what changed; where it disagrees with the older "As
364 built" sections below, this one is current.
365
366 - **Licence notices.** The embedded bundle contains MIT code (cordis,
367 schemastery, cosmokit, dsh-util-values, and verbatim `dsh-tools` excerpts),
368 and its banner promised `LICENSES.txt` beside it, which nothing wrote.
369 `build.mjs` now generates `dist/LICENSES.txt` from the bundler's metafile
370 (every package that contributed an input file, each with its own LICENSE
371 file; a bundled package with none fails the build; the `dsh-tools` excerpt is
372 listed from a named table that the build checks against the source file). The
373 list was hand-kept before and named `@standard-schema/spec`, which is not
374 bundled. The existing `git diff --exit-code -- dist` check covers it. Rust
375 embeds it (`NOTICES`) and `materialize_bundle` writes it beside the bundle in
376 the same digest-named directory, by the same staging, `0400`, rename and
377 read-back as the bundle (so a symlink at its name is replaced, never written
378 through). `THIRD_PARTY_NOTICES.md` lists the packages. Tests: the directory
379 holds exactly the two files with the embedded bytes; and every
380 `node_modules/<pkg>` marker in the *embedded bundle* has a section in
381 `LICENSES.txt` and an entry in `THIRD_PARTY_NOTICES.md`, so the check does not
382 trust the generator.
383 - **Several `native` entries.** The manifest has always accepted
384 `native.paths` (up to 64), and the core sent one `ext/activate` per entry
385 under one owner token, which the host answered with "owner token already
386 active" for the second. No protocol change was needed: the host now accepts a
387 further `ext/activate` for a live owner token if the previous entry finished
388 activating, the plugin matches, and the path is new; each entry is a fiber of
389 the same owner, so deactivation, revocation and crash handling are unchanged.
390 Any failing entry fails the owner and the host disposes the earlier entries'
391 fibers (rolling back their registrations) before answering; the core already
392 drops the owner's registrations. The core merges the cumulative tool and
393 command names of the answers and skips a path the manifest lists twice. Tests
394 (JS and Rust, with `two-entries` and `two-entries-failing` fixtures): both
395 entries live under one owner, one tool callable from each, a repeated or
396 foreign entry refused, one `ext/deactivate` tearing both down, a throwing
397 second entry leaving nothing of the first.
398 - **Input is validated by the core.** `HostToolSpec` checked nothing against
399 the schema a plugin registered, so `additionalProperties: false` in the
400 example was advice (DSH's `defineTool` validates inside the plugin; a raw
401 registration did not). `registry::InputValidator` compiles the schema at
402 registration with the `jsonschema` crate (already linked for Workflow
403 `responseSchema`; it moved from `[dev-dependencies]` to `[dependencies]` of
404 `codewhale-tui`, no new crate and no lockfile change). No `$ref` resolver is
405 enabled, so a reference outside the schema fails to compile and is refused
406 at registration with the reason, as is any invalid schema. `prepare` (before
407 an approval card exists) and `execute` check each call and return
408 `ToolError::InvalidInput` naming the violations (at most five, bounded), so
409 the model can correct itself and the host sees nothing. The deferred-tool
410 first-call check (`deferred_first_call_matches_schema`) is a separate,
411 hand-written shape check of required and known field names; it leaves types
412 to the tool, so it was not the path to reuse. Known limit: the validator
413 runs on the channel's callback thread under the registry lock at
414 registration (a schema is at most 64 KiB); schema `format` assertions follow
415 the draft's own default.
416 - **Plugin context.** Core to host, three optional fields (protocol still v1;
417 an older host ignores them, the generated TypeScript was regenerated):
418 `ext/activate.data_dir`, `tool/call.workspace`, `command/run.workspace`
419 (corpus `46`-`50`). The workspace is `ToolContext::workspace` of the calling
420 session, or the workspace whose user registry loaded the command
421 (`ExtensionCommandRef::workspace`); a path that is not UTF-8 is omitted. A
422 plugin's `exec` is now frozen `{signal, callId, args, workspace?, dataDir?}`
423 and a command invocation gains the same two. `dataDir` is
424 `<home>/extension-host/data/plugins/<name>-<12 hex of sha256(plugin id)>`,
425 created by Rust (0700) before activation: inside the host's single writable
426 root, stable across generations, never deleted. It is not isolation between
427 plugins that share the process (§4.4). No home, credential or other
428 workspace path is passed, though `dataDir` and the entry path do reveal the
429 Codewhale home's location.
430 - **Plugin configuration.** There was no per-plugin config (`config` was always
431 `{}`). `[plugins."<name>".config]` in the *user's* `config.toml`
432 (`codewhale_config::extension_host::PluginSettings`, a field on `Config`; project scope reads an
433 explicit key list that excludes it) becomes the second argument of `apply`.
434 Cordis already validates it against an exported `Config` schema (a
435 schemastery `Schema`) and applies defaults, so a mismatch fails activation
436 with the field named; no host code was needed for that. Rust bounds it
437 (`plugin_config.rs`: objects of plain TOML values, 16 KiB, 16 levels, no
438 date-times) and refuses an over-limit table by failing that plugin's
439 activation with the reason, before the host is asked. Each owner records the
440 digest of the config it was activated with; reconcile treats a changed
441 digest like a changed plugin (revoke, new generation), so settings re-read
442 at `/plugin reload` re-activate exactly the plugins whose table changed. A
443 refused config is hashed from its reason, so it is neither retried every turn
444 nor stuck once fixed. `/plugin show` lists the configured keys (never the
445 values) or the refusal. The example plugin reads one setting through its own
446 `Config` schema.
447 - **Tests.** Rust: settings parse, size/depth/date-time refusal and digest
448 behaviour; the real host with `plugin-context` (settings with the plugin's
449 default filled in, per-call workspace, frozen context, a write into `dataDir`
450 inside the sandbox, a command's workspace, no churn on unchanged settings, a
451 new generation on a change, a schema-refused config, an oversize config, and
452 recovery); `/plugin show` rendering and escaping. JS: the same against the
453 fake core, and the typed example with and without its setting.
454
455 Not done: a running session does not watch `config.toml` (only `/plugin reload`
456 re-reads it); `[plugins]` is not profile-scoped; the review screen shows the
457 config keys through `/plugin show`, not the trust review itself; the `Config`
458 schema is not exported into the plugin's registered tool schema; there is still
459 no storage service beyond the directory; the Linux and Windows runs of the new
460 Rust tests did not happen on this machine.
461
462 ## As built: extension commands (2026-10-01)
463
464 Phase 2's `command/run` landed in `crates/engine/src/extension_host/command.rs`,
465 the registry, the protocol and the host's `src/shims/commands.ts`, mirroring
466 how a tool flows: `registry/register` → owned entry (plugin id + generation,
467 never-reused handle) → adapter → call → teardown.
468
469 - **Protocol (still v1).** `registry/register` takes `kind: "command"`.
470 `RegisterSpecWire` (was `ToolSpecWire`) has `name`, `description`,
471 `input_schema?` and `argument_hint?`; the generator cannot express a
472 per-kind union, so `RegisterParams::check_spec` (a tool needs `input_schema`
473 and takes no hint; a command takes no schema) runs in `parse_host_message`
474 and is mirrored in the host's `validateMessage`, and the corpus holds both
475 (`20`, `37`–`40`). New core→host request `command/run`
476 `{handle, command_id, raw_input, deadline_ms}`; `raw_input` is the argument
477 text after the name, trimmed (the core's slash parser trims; the design's
478 `agent: AgentRef` was not built, the host has no agent or session). Its
479 answer, `CommandResultWire`, is `{kind: "success", text?}`,
480 `{kind: "error", text}` or `{kind: "submit", prompt, text?}` (corpus `41`–`45`).
481 `ext/activate`'s `ok` also reports `commands` (defaulted). The protocol lint
482 (`host_protocol_never_gains_core_authority`) passes unchanged by
483 construction: `command/run` names no event, store, approval, secret,
484 credential, token, auth, turn, loop, session or prompt authority, and has a
485 reviewed row saying why. `protocol.generated.ts` is regenerated by the
486 drift test.
487 - **What a command can return.** What the user-command machinery already does:
488 text shown as a `System` transcript cell (labelled with `/name` and
489 `extension:<plugin>`; escapes stripped, cut at 64 KiB) and/or a prompt sent
490 as the user's next message through the same `SendMessage` path a markdown
491 command's template takes (visible; refused over 128 KiB, never truncated;
492 empty refused). Nothing the host returns makes the core call a tool or the
493 model itself: after a `submit` the turn and tool approval are the ordinary
494 ones.
495 - **Rust.** `OwnerRegistry` holds commands beside tools with the same owner
496 rules; one never-reused handle counter; `remove_registrations_of`,
497 `mark_failed`, `revoke_owner`, `forget_owner`, `host_exited` and
498 `revoke_all` remove an owner's commands with its tools; a stale
499 `unregister` is a no-op. Admission (`register_command`): DSH's grammar
500 (`^[a-z][a-z0-9_-]*$`, ≤ 64). If a built-in command or alias (including the
501 fixed `jihua`) answers to a plugin name, the plugin registration
502 receives a deterministic plugin-specific name; a built-in-tier collision or
503 an unavailable namespaced name is refused. Another plugin cannot take an
504 existing unscoped registration;
505 descriptions ≤ 1 KiB and hints ≤ 256 bytes, single-line; 64 per owner, 256
506 per host. Commands and tools are separate namespaces. The commands of the
507 owners an engine's workspace snapshot desires, bound to the reviewed hash,
508 are loaded by `UserCommandRegistry::load_extension_commands` into the
509 existing user registry, last, so a user, workspace or manifest markdown
510 command (or a built-in) always wins the spelling, with a load error; a
511 global `command::epoch()` bumped on every registry or attachment change
512 makes the registry reload. Entries carry the owner's reviewed authority, so
513 disabling or untrusting the plugin hides them at once, before reconcile.
514 Dispatch (`try_dispatch`) returns the new `AppAction::RunExtensionCommand`;
515 the UI loop awaits `extension_host::run_command` (like `/balance`).
516 `run` re-checks, immediately before sending, the policy flag, a running
517 host (so a dead host answers `extension host is down: <why>` at once), the
518 exact registration (handle and generation), the reviewed receipt and the
519 `Native` capability, through the same `live_host` the tool path now uses.
520 The call is bounded by `SupervisionOptions::command_run_deadline` (30 s),
521 sent as `deadline_ms`, then `$/cancel`, like every method. Capability: the
522 existing `Native`; no new one and no policy bump (§4.6).
523 - **Host.** `ctx.commands.register(definition)` returns an idempotent
524 disposer and is an effect of the calling fiber. It accepts the Codewhale
525 shape (`argumentHint`, handler may return a string, `{kind: 'submit'}`) and
526 DSH's (`input: {hint}`, `{kind: 'success' | 'error'}`, `rawInput` with its
527 leading separator; `@deepseek-ai/dsh-commands/brand`, the one value import
528 such plugins make, resolves to two identity functions in
529 `src/dsh/resolve-hooks.ts`, and the rest of that package still fails
530 loudly). `commands` moved from "not provided" to provided;
531 plugins still cannot provide it (the root provides its own shim once, frozen
532 like `tools`). `src/shims/owned.ts` holds the register/undo bookkeeping
533 both shims now share; the tool path was moved onto it. `dist/` was rebuilt.
534 - **Tests.** Host: register, each answer kind, cancel, refusal, dispose of
535 one handle versus deactivation, invalid definitions, no provide/rewrite.
536 Rust: registry rules (shadowing, caps, exact undo, revocation, crash),
537 wire shapes, end-to-end through the real host and `commands::execute`
538 (hints, per-workspace visibility, trimmed arguments, DSH `rawInput`,
539 escapes, disable), clash refusal (built-in, other plugin, markdown wins),
540 host-down, deadline cancel, and a killed host with a stale reference after
541 replay.
542
543 Not done: Esc or a keypress cancelling a running command before its deadline
544 (the UI loop awaits it); the Runtime API and GPUI cannot list or run
545 extension commands (`GET /v1/commands` omits them); a clash with a
546 markdown command is resolved at registry load, not refused at registration;
547 `/plugin show`'s localized owner line does not list commands (the `/plugin`
548 host section does); no `agent`/session handle, attachments, `list`/`find`
549 on the DSH surface or `command/run`/`command/done` session events; an
550 extension command does not reset the goal, todos or plan as a markdown command
551 does; a command's `submit` prompt is not marked as plugin-authored beyond the
552 transcript line printed before it; the Bun runtime and Windows/Linux were not
553 run for the Rust tests of this slice.
554
555 ## As built: script tools lose self-approval and shadowing (2026-09-30)
556
557 CURRENT_DECISIONS §26 D4 landed in Rust ahead of phase 4, so R1 below and
558 D9 describe the old behaviour. In `crates/engine/src/tools/plugin.rs` and
559 `ToolRegistry::apply_overrides`: a script's `# approval: auto` is ignored and
560 the tool gets the default a script with no `approval:` line gets (`Suggest`),
561 reported in the runtime log and `/plugin tools`; a `[tools.overrides]`
562 `script` / `command` entry keyed by a built-in is refused, named once in a
563 status line and in the runtime log, and the built-in stays active (`disabled` still works). D9(a) planned
564 `Required`, rememberable per tool: `Suggest` and `Required` resolve the same
565 way in `resolve_tool_permission`, and per-tool remembering was not built.
566
567 ## As built: Bun runtime (2026-09-30)
568
569 The host can run on Bun as an opt-in: `[extension_host] runtime = "node" |
570 "bun" | "auto"`, default `node`. It follows CURRENT_DECISIONS §26 (D1/D2 and
571 the 2026-09-29 update "go to bun asap") and the 2026-09-29 Bun-vs-Node spike.
572 Bun may become the default only after four gates are proven on every
573 platform, followed by an explicit, recorded cutover. The table below is the
574 record, measured on macOS 26.1 arm64 with Bun 1.4.0 and Node 22.20, 24.19 and
575 26.10; there is no Linux or Windows Bun proof, so Node stays the default and
576 the diagnosed fallback. The same embedded bundle runs on either runtime.
577
578 | Gate | How it is closed | Evidence |
579 | --- | --- | --- |
580 | 1. `--no-install` always | `supervisor::runtime_args` passes `--no-install --no-env-file --config=<null device> --no-addons` to Bun | host test against a local recording registry (a control run without the flag does contact it); Rust launch-plan test |
581 | 2. OS-enforced memory cap | Linux `RLIMIT_DATA`; Windows Job Object per-process limit; macOS + Bun: a fatal jetsam limit the host applies to itself | host test (Bun on macOS: `memory_limit_mib` reported, same pid, SIGKILL at 300 MiB); Rust `memory_cap_stops_a_{bun,node}_host` |
582 | 3. FFI policy in the loader | `src/runtime.ts` locks `bun:ffi`, `Bun.FFI`, SQLite, Workers and ShadowRealm; the host refuses to start if a lock does not hold | host test with 13 entry points; each one is reachable when the lockdown is removed |
583 | 4. `host/hello` reports the real runtime | `runtime: {name, version}` from `process.versions.bun` first; the handshake refuses a runtime or version mismatch | corpus 01/21/31–35; Rust handshake-mismatch test; host handshake test |
584
585 - **Selection** (`dependencies::resolve_extension_host_runtime`). Unset
586 means `node`, or `bun` when the table sets only a `bun` path
587 (`codewhale_config::extension_host::ExtensionHostConfig::effective_runtime`). A configured `node`/`bun` path is
588 the only candidate for its runtime and fails resolution with its reason
589 rather than falling through. Otherwise each `bun` on `PATH`, then
590 `$BUN_INSTALL/bin` or `~/.bun/bin` (or each `node` on `PATH`) is run, and
591 the first at or above the floor (Bun **1.4.0**, Node `^22.19 || >=24`) is
592 taken. A searched candidate inside a `node_modules` directory or the working
593 directory is skipped without being run (not applied when the working
594 directory contains the user's home). `auto` tries Bun first and records why
595 Bun was not used when it takes Node. `bun` and `node` try only that runtime
596 and never fall back. For Node the resolver also probes which of
597 `--no-experimental-sqlite` and `--no-experimental-ffi` the binary accepts
598 (`node <flag> --version`).
599 - **Pinned for the process.** The runtime is pinned once a host on it
600 completes the handshake. Every restart reuses it without resolving it
601 again, so a session cannot switch runtime. Under `auto`, a Bun host that
602 fails to launch or handshake before anything is pinned is reported once and
603 Node is resolved for the rest of the session. The handshake refuses a host
604 whose `host/hello` reports a different runtime, or a different version than
605 the pinned probe saw (the binary was replaced mid-session). `codewhale doctor`
606 prints the resolution (what, which version, where, the fallback reason and
607 how the memory cap is enforced). `/plugin` shows `running · pid … · bun
608 1.4.0 · …` and a `runtime:` line with the summary and memory posture.
609 - **Protocol.** `host/hello.node_version` is replaced by
610 `runtime: {name: "bun" | "node", version}`, read from `process.versions.bun`
611 first (Bun emulates `process.versions.node`), plus an optional
612 `memory_limit_mib` (below). The protocol integer stays 1: the bundle and the
613 core always ship together. Corpus: `01`, `21`, `31`–`35`.
614 - **Flags and environment** (`supervisor::runtime_args`, `runtime_env`). Node
615 keeps `--max-old-space-size=256 --disable-proto=throw --no-addons` and gets
616 whichever of `--no-experimental-sqlite --no-experimental-ffi` it accepts.
617 Bun ignores Node's heap and `__proto__` flags, so it gets `--no-install
618 --no-env-file --config=/dev/null --no-addons` and `BUN_JSC_useShadowRealm=0`.
619 Without them Bun fetches a missing package from npm while plugin code runs,
620 and loads `.env` and `bunfig.toml` (which can preload code) from the working
621 directory, which is the host's writable data dir.
622 - **Module resolution** (`src/dsh/resolve-hooks.ts`). Bun has no
623 `module.registerHooks`, and its runtime `onResolve` is not called for bare
624 package names. So the Bun branch uses `Bun.plugin` in three pieces:
625 `build.module` serves each singleton by exact name. `onResolve` classifies
626 the subpaths Bun does pass it. `onLoad` refuses any file under a
627 `node_modules` copy of a peer (a second Cordis, a shipped
628 `@deepseek-ai/dsh-*`). A peer that is not installed at all is mapped from
629 Bun's `Cannot find package` to the same ``requires `X` `` error
630 (`explainImportError`).
631 - **Native code** (`src/runtime.ts`, `denyNativeCode`). The checkpoint only
632 locked the `bun:ffi` export object. Probing found five ways around that:
633 `Bun.FFI` is a separate object with `dlopen`, `linkSymbols` and raw pointer
634 reads and writes; a Web Worker or `worker_threads` Worker is a new realm
635 with an untouched `bun:ffi`; `ShadowRealm#importValue('bun:ffi')` loads a
636 fresh copy, and a `node:vm` context hands out a working `ShadowRealm`
637 constructor even after the global is deleted; `bun:sqlite`
638 `setCustomSQLite` and SQLite extensions `dlopen` arbitrary libraries. Node
639 had gaps of its own: Node 26.10 ships `node:ffi` enabled, `--no-addons` does
640 not cover it or `node:sqlite` extension loading, and a Worker given its own
641 `execArgv` drops `--no-experimental-*`. Now, before any plugin loads:
642 `process.dlopen`, `process.execve` (which would drop the flags and the
643 macOS limit) and Worker threads are refused on both runtimes; under Bun,
644 the `bun:ffi`, `Bun.FFI`, `bun:sqlite` and `node:sqlite` exports are
645 throwing getters (for `node:sqlite`, whose ESM namespace Bun builds early,
646 every prototype method throws) and ShadowRealm is off engine-wide; under
647 Node, the two builtins are switched off by flags. The host then verifies
648 each Bun lock through a real `import()`, and checks ShadowRealm and the Node
649 builtins, and exits with an error rather than run with a lock that does not
650 hold. A process a plugin starts is outside this policy (as under Node);
651 Seatbelt stays the outer boundary on macOS. Known limit: this is a list of
652 the entry points found; one a newer runtime adds is not covered until it is
653 added.
654 - **Memory cap** (1 GiB, `supervisor::MemoryEnforcement`). Linux:
655 `RLIMIT_DATA` between fork and exec (clamped to a lower inherited hard
656 limit), so the kernel fails an allocation past it; measured once in a Linux
657 container (2026-09-29), Node 24 cannot create the watchdog Worker at
658 512 MiB and Bun 1.4 aborts at startup at 256 MiB, and both run at 1 GiB.
659 Windows: the Job Object's per-process limit (`JOB_OBJECT_LIMIT_PROCESS_MEMORY`),
660 set just after spawn when the host joins its job. Both apply to every process
661 a plugin starts as well. macOS: `setrlimit(RLIMIT_AS/RLIMIT_DATA)` below the
662 current mapping size returns `EINVAL`, and `memorystatus_control` returns
663 `EPERM`. A fatal jetsam limit set as a `posix_spawn` attribute
664 (`posix_spawnattr_setjetsam_ext`, libSystem SPI) works unprivileged, but any
665 later `exec` clears it, so the core cannot set it on `sandbox-exec`. The Bun
666 host therefore re-executes itself in place (`POSIX_SPAWN_SETEXEC`: same pid,
667 process group, stdio and Seatbelt sandbox) with the limit, before any plugin
668 loads, using `bun:ffi` before the lockdown takes it away, and reports
669 `memory_limit_mib` in `host/hello`. The core accepts only the value it asked
670 for (`CODEWHALE_HOST_MEMORY_LIMIT_MIB`). Past the limit the kernel SIGKILLs
671 the host; the exit reason reports the SIGKILL and the configured limit but
672 not a cause, since any SIGKILL looks the same. Processes the host starts are not
673 covered. A Bun host that cannot apply the requested kernel limit is refused
674 before initialization, with the reason retained in its stderr and `/plugin`
675 diagnostics. A Node host on macOS is checked at each heartbeat instead,
676 which lags by up to one interval. Node's 256 MB heap
677 flag still applies everywhere.
678 - **Tests.** The host JS suite runs under `node --test` and `bun test`
679 (`npm run test:bun`); each run spawns the host on the runtime running the
680 suite. CI adds a JS-suite Bun leg pinned to 1.4.0 on Linux and keeps the
681 Node leg. Rust covers the selection matrix and flag probe, the default and
682 config rule, the per-runtime launch flags and environment, the runtime and
683 version mismatch refusals, the `auto` fallback when Bun fails to start, a
684 Bun end-to-end run with a crash restart that stays on Bun, and the memory
685 cap: CI runs it with Node on Linux, macOS and Windows; the Bun case has run
686 on macOS only.
687
688 2026-10-02 source checkpoint: `compile-host.mjs` builds the same canonical host
689 with an explicitly supplied local Bun and no runtime download. An adjacent
690 compiled image is optional for Bun/Auto and must report this Engine's exact
691 source digest; Node remains the default. Six local compiled-image/fake-Core
692 cases pass, including both tiers, same-PID macOS jetsam, FFI/Worker refusal,
693 embedded no-install flags and zero registry traffic. This is separate from
694 Rust execution, code signing, release packaging and installed-binary proof.
695
696 Native launch now refuses an absent or failed verified OS wrapper. The pinned
697 Builtin exception remains diagnosed and ticket-bound; it does not close D9.
698 The CI source requires Node and Bun in the Rust three-OS matrix and adds
699 source/compiled-host suites, but these jobs have not run on this source. Linux
700 and Windows isolation/memory receipts, release assets and the four D2 gates
701 remain required before a Bun default cutover. The Linux `RLIMIT_DATA` path
702 clamps to a lower inherited hard limit and reports the configured cap.
703 Reviewed import closures diagnose Bun query/fragment and dynamic CommonJS
704 identity limitations explicitly rather than choosing a different module.
705
706 ## As built: phase 2a supervision (2026-09-29)
707
708 The experimental host now has bounded lifecycle supervision. It uses the same
709 Rust manager, owner registry, attachment snapshots, and approval gate:
710
711 - `host/ping` runs every 3 seconds. A ping unanswered for 3 seconds marks the
712 host **Unresponsive**; after 10 seconds the existing process-tree supervisor
713 kills it. A pong restores Ready only for that generation. Deadlines use a
714 monotonic clock; laptop suspend/resume behavior has not been qualified.
715 - Unexpected exits, protocol violations and hang kills share one crash budget.
716 Below 3 crashes in 5 minutes, the manager waits 250 ms then revalidates current
717 attachments and replays eligible owners with fresh generations and tokens.
718 The third crash stops recovery and retains the failure/stderr diagnostic.
719 Opening another engine and replaying a host never reset this budget.
720 - In-flight tool calls fail with the existing typed unavailable error; they
721 are **never replayed**. Failed/faulted receipts remain suppressed. A crash
722 during the sole activating owner's initialization is attributed to that
723 receipt, so other valid plugins can recover.
724 - Explicit plugin changes/reload clear the crash budget and retry failed
725 receipts through the existing `plugins_changed` path. Start failures also
726 permit a new engine attachment to retry once the one-minute cooldown has
727 elapsed. There is no automatic handshake/start-failure loop.
728 - Old-generation callbacks and recovery tickets cannot mutate a newer host.
729 Planned shutdown is not a crash. Native-entry, staged-byte, persisted-state,
730 approval-grant and platform sandbox rules remain unchanged.
731 - Two incomplete, leaking, malformed or failed teardowns in ten minutes request
732 one planned restart. The existing monitor waits until reconciliation and
733 all non-heartbeat requests are idle, then atomically closes request admission
734 before retiring the process tree. Current valid owners replay with fresh
735 tokens; calls are never replayed. This maintenance neither consumes nor
736 resets the unexpected-crash budget. Late old-process outcomes cannot dirty
737 the replacement.
738
739 The authoring follow-up adds an escaped `/plugin show` owner section with state,
740 live tools and up to 20 recent attributed messages from the bounded 64-entry
741 shared diagnostic ring. Regular `.mts` entries use the same reviewed-byte and
742 discovery rules as `.mjs`/`.js`; Node strips erasable types. The executable
743 [hello extension](../examples/plugins/hello-extension/hello.mts) and
744 [author guide](../EXTENSIONS.md) describe the actual services and trust loop.
745
746 `exec.cwd` remains deferred: the current execution context does not expose the
747 caller's workspace path. Hooks, MCP, `core/call`, and sandbox parity
748 also remain subsequent work (commands landed: see the 2026-10-01 section). The following phase-1 section is its historical
749 receipt, including the earlier lack of heartbeat/restart and `.mts` support.
750
751 ## As built: phase 1 (2026-09-25)
752
753 **Scope matches §8:** tools only, one host per engine process, protocol v1,
754 no `core/call`, no commands, hooks, MCP, heartbeat or auto-restart. The
755 differences from the text below:
756
757 - **An OS sandbox arrived early (§4.5 said phase 5).** On macOS the host runs
758 under Seatbelt with a workspace-write profile rooted at
759 `$CODEWHALE_HOME/extension-host/data`: no direct network, writes only there
760 and in the temp dirs, and no reads of
761 - every entry of the Codewhale homes (runtime home, `~/.codewhale`, legacy
762 `~/.deepseek`) except `extension-host/`, `plugins/` and `builtin-plugins/`.
763 Existing entries are denied by enumeration at launch, and the known stores
764 (`secrets`, `tokens`, `state`, `sessions`, `config.toml.bak`, …) are denied
765 by name even before they exist;
766 - the Codex home (`$CODEX_HOME` / `~/.codex`, holding `auth.json`) and the DSH
767 home (`$DSH_HOME` / `~/.dsh`, holding `.credentials.yaml`);
768 - the default credential-store deny-list (`sandbox::read_guard`).
769
770 **What it does not do:** other user-readable files, including project `.env`
771 files, stay readable (the `.env` filename rule has no Seatbelt subpath form),
772 and Mach services and `exec` are not restricted, so this is defense in depth,
773 not the §4.5 containment. On Linux the same policy runs under bubblewrap
774 when a launch-time probe shows bwrap works; each Codewhale home is masked
775 whole and its readable entries bound again, since bwrap cannot deny a path
776 that does not exist yet (`extension_host::supervisor` lists what that does
777 not cover). Current Native admission refuses missing or failed verified
778 wrappers, including Windows while filesystem/network isolation is absent.
779 Only the pinned Builtin exception can run unsandboxed with its diagnostic;
780 §4.5's full containment and mandatory-host cutover remain open.
781 - **Extension tool names that the approval path keys by name are refused.**
782 Approval keys (`approval_cache`), approval-card summaries and the approval /
783 auto-review category are derived from the tool name. A plugin tool named
784 `web_fetch` would otherwise share `fetch_url`'s `net:<host>` session grant.
785 `registry::core_special_case` probes those classifiers and refuses any name
786 they special-case (`web_fetch`, `exec_wait`, `task_shell_start`, `read_*`,
787 `get_*`, `list_*`, …), in addition to the §3.1 native and prefix rules.
788 - **Teardown of the whole process tree.** The host leads its own process group
789 on Unix (a Job Object on Windows). It kills that group itself at stdin EOF,
790 and a watchdog thread kills it when the host's parent process changes, even
791 while a plugin blocks the event loop. A plugin child that calls `setsid`
792 escapes the group. There is no Rust-side `host/shutdown` in production: the
793 host is shared by every engine in the process and ends with it.
794 - **Revocation on plugin changes is immediate.** `/plugin disable`, `revoke`,
795 `enable` and the runtime API's plugin actions call
796 `extension_host::plugins_changed`, which reconciles the host at once instead
797 of waiting for the next turn.
798 - **Shared-process disclosure (§4.4, threat 3).** When other plugins share the
799 host, the approval card and `/plugin` say so. The tools shim's prototype is
800 frozen, which stops one plugin rewriting `register` for the others; shared
801 globals remain, so the disclosure is the control.
802 - **Core-service refusal does not depend on the caller.** Providing a refused
803 service name through `ctx.root` fails like providing it through `ctx`.
804 - **Node resolution** skips relative `PATH` entries and probes each candidate
805 with an empty environment.
806 - **The host re-hashes only the `native` entry file** before importing it, not
807 the whole package closure (§4.4, threat 2). The rest of the staged snapshot is
808 covered by Rust's per-call receipt check.
809 - **Measured** (this machine, Node 22.20, debug build): spawn + handshake +
810 activation of the DSH fixture 78–95 ms; host RSS 61–63 MB with the watchdog
811 thread (53 MB without it). `hyperfine` was not run.
812 - **DSH references** are pinned to `refs/dsh` commit `00102833`
813 (`0.1.7-alpha.2`); the local checkout's HEAD has since moved to `0d1f50007f`.
814
815 **Phase-1 fixes (2026-09-28).**
816
817 - **Engines attach; they do not own the host.** The host and its owner
818 registry are process-wide, but each engine holds a `HostAttachment` with
819 its own workspace plugin snapshot. Reconcile activates the union of what
820 every attached snapshot desires, re-verifying each snapshot against
821 persisted plugin state (so a disable or revoke through any registry
822 revokes everywhere), and revokes only owners no attachment desires. An
823 engine installs only the tools of owners its own snapshot desires. Engines
824 without a snapshot of their own (isolated chats, the empty fallback) do not
825 attach, and dropping an attachment detaches without revoking. Before this,
826 every engine's `sync` revoked whatever *its* registry did not desire, so
827 two workspaces, or one isolated chat, cancelled each other's in-flight
828 calls. The native-name set is now additive across engines.
829 - **Session grants are bound to the reviewed build (§4.3).** Extension tools
830 key both the exact and the session-grant approval key as
831 `ext:<plugin_id>@<content_hash>:<name>:<hash(input)>`, through the
832 `ToolSpec::approval_scope` hook, so an updated plugin, or another plugin
833 that later takes the same tool name, is asked again. This only narrows
834 grants; widening them is an open decision.
835 - **The native-entry rule is checked at review time.** "One `.mjs` or `.js`
836 file" is one function (`plugins::runtime::native_entry_problem`). With the
837 flag on, discovery reports a violating entry as an error diagnostic, so
838 `/plugin validate` and the review screen fail it, and activation refuses it.
839 - **Code mode suspends extension tools for approval.** Lane 6562 landed
840 (#6583) before phase 1 (#6600), so acceptance 2's code-mode assertion is
841 "suspends for approval": an `execute_tools` call of an extension tool in a
842 main-session turn raises `<call>.<seq>` approval attributed to
843 `extension:<plugin>`, sends no `tool/call` before approval, returns the
844 result on allow and fails only that call on deny. Direct
845 `execute_tools_tool` with no gate still refuses it before any host call.
846 - **The handshake timeout is 30 s**, not the 2 s §1.4 and §8 state
847 (`supervisor::HANDSHAKE_DEADLINE`). 5 s failed on loaded Windows CI with a
848 silent host (a cold `node` start plus an antivirus scan of the freshly
849 materialized bundle), and a miss fails the host for the whole session. The
850 handshake is off the first-prompt path, so 30 s (the MCP stdio handshake
851 budget) costs nothing when the host is healthy.
852 - **A failed host is retried by a new engine, not by `/plugin enable`
853 itself.** In the TUI every plugin change respawns the engine, and
854 `Engine::new` calls `begin_session()`, which resets a failed host. On the
855 runtime-API path a plugin action retries a failed host only when it makes
856 a plugin the process has not yet seen desired; otherwise the host stays
857 failed until a new thread engine starts. Explicit retry is phase-2
858 supervision work.
859 - **`hyperfine` was never run** for acceptance 7; the flag-off guarantees
860 rest on the never-spawned test and the pinned v3 policy digest.
861
862
863 Status: **proposal**, 2026-09-25. Written for the founder direction of that date: move plugins, hooks, commands, custom tools, agent presets and MCP to TypeScript, using the same model as the DSH (DeepSeek Harness) plugin system, and make only that part of Codewhale extensible.
864
865 This stage was read-only. I changed no source, branch, tracker or checkout. The only file written is this one. **Revised the same day after an adversarial review.** §0.1 lists the 13 findings (R1–R13), and the exact phase-1 scope is in §8.
866
867 ## 0. Evidence base and corrections
868
869 | Source | What I actually read |
870 |---|---|
871 | Engine | `/private/tmp/cw-wt-6446`. **HEAD is `8a835d7c4`, not `58b1dd3dd`** as the Rust inventory states. It is two commits past `58b1dd3dd` (#6571, #6483), and neither touches plugins or MCP. Line numbers below were re-checked against `8a835d7c4`. |
872 | Code-mode lane | `feat/code-mode-mcp-6562` (`fda77b64a`, `18241e3e8`, `ebda21f02`), read with `git show` |
873 | DSH | `<refs>/dsh` at `00102833` (`0.1.7-alpha.2`), read with `git show` |
874 | Research inputs | The DSH, RUST and REFS memos embedded in the task. I re-verified the load-bearing claims listed below. |
875
876 **Checks I ran myself** (greps and `git show` only; nothing was built):
877
878 - **Lane code:**
879 - `NestedCallGate { mcp_pool, … }` is at `codemode.rs:200`. `refusal_before_gate` is at :250 and `ungated_admission` at :502. The MCP branch in `execute` is at :533–556.
880 - `gate_nested_call` plans through `plan_tool_calls(…, ToolCallSource::CodeMode)` with `<parent>.<seq>` ids (lane `turn_loop.rs`, around line 4706).
881 - **Feature flags:** `Feature` and `Stage::{Experimental, Beta, Stable}` live in `crates/runtime/src/features.rs`, with a `[features]` table in `config.example.toml:1228`.
882 - **Activation policy:** `ACTIVATION_POLICY_VERSION = 3` (`plugins/activation.rs:22`). Its capability set already has a **`Native` capability that is inventoried but inactive** (`activation.rs:93`), and a manifest field `native` with the alias `native_extension` (`manifest.rs:51`).
883 - **Built-in bundles:** `plugins/builtin.rs` embeds `crates/tui/plugins/computer-use` with `include_bytes!` and materializes it under `$CODEWHALE_HOME/builtin-plugins` as a digest-named snapshot. **This is the shipping path the host bundle will reuse.**
884 - **ToolCallSource:** `crates/tools/src/lib.rs:386` has `ToolCallSource { Direct, JsRepl }`. The lane adds a second, private `ToolCallSource { Model, CodeMode }` at `turn_loop.rs:39`.
885 - **MCP boot:** it is already lazy. `tool_selection_covers_server` drives the lazy boot and `tools_always_load` (`mcp.rs:2852`, `config.rs:4863`), `McpServerConfig.required` is at `mcp.rs:571`, and `McpPool::new` hashes the config.
886 - **DSH plugins:**
887 - They import runtime helpers by package name. My grep counted 109 `from '@deepseek-ai/dsh-tools'` imports in `packages/**/src`.
888 - `@deepseek-ai/dsh-mcp-client` spawns stdio servers **itself**, through `StdioClientTransport` from `@modelcontextprotocol/client` 2.0.0 (`transport.ts:10,34`).
889 - The DSH root requires Node `^22.19.0 || >=24.0.0`.
890 - **Local Node:** the first `node` on `PATH` on this machine (`/opt/homebrew/bin/node`, 25.8.0) **fails to start** because `libllhttp.9.3.dylib` is missing. `/usr/local/bin/node` is v22.20.0. Spawning `node -e ''` six times took **96, 23, 22, 27, 31 and 22 ms**, measured with Python `perf_counter` around `subprocess.run`. That is the only measurement in this document.
891
892 **Two facts the plan depends on:**
893 - **Node 20 reached end-of-life on 2026-04-30.** This is from my knowledge, not checked in this session. Adding a *new* runtime dependency with a floor of 20 would ship on an unsupported runtime.
894 - **The local Homebrew breakage is a real failure mode.** The host must resolve Node by *running* it, not by finding it on `PATH`. **Correction (review round 2):** `resolve_node()` (`dependencies.rs:278`) is *not* reusable as is. It runs `node --version` once, only for the first `node` on `PATH`, caches the answer in a process-wide `OnceLock`, and never parses the version. On this machine it would return `None` (Homebrew's broken node comes first), and the host would be unavailable although a working 22.20 is installed. Phase 1 adds a candidate ladder with a version floor (§8).
895
896 ### 0.1 Adversarial review, round 2 (2026-09-25)
897
898 Checked against `/private/tmp/cw-wt-6446` @ `8a835d7c4`, lane `feat/code-mode-mcp-6562` @ `ebda21f02`, and `refs/dsh` @ `00102833` (the checkout's own HEAD has moved on to `0d1f50007f`, so every DSH reference here is pinned to the commit, not to HEAD). Greps and `git show` only; nothing was built or run.
899
900 **Facts that changed the design:**
901
902 | # | Finding | Evidence | Consequence |
903 |---|---|---|---|
904 | R1 | **A second custom-tool system already ships, outside plugin trust.** Scripts in `~/.codewhale/tools/` become model-visible tools on every turn. Each declares its own approval in frontmatter (`# approval: auto`). `ToolRegistry::register` *overwrites* a built-in of the same name with only a `warn!`. `[tools.overrides]` `Script` / `Command` entries replace built-ins on purpose. | `tools/plugin.rs:1-20,111`; `tools/registry.rs:53-63,375-414`; `core/engine.rs:4910,7360-7385` | Today, a script already approves itself and shadows built-ins. The founder's "only the TS host is extensible" requires moving this, so it is added to the deletion plan (§7) and decision D9. The host must not be weaker than this path, and must not copy it either. |
905 | R2 | **Registry tools are the existing seam for extension tools; `ExternalToolDispatch` is not needed in phase 1.** The registry is rebuilt every turn (`build_turn_tool_registry_and_catalog`). Tools outside `DEFAULT_ACTIVE_NATIVE_TOOLS` are deferred by default (`tool_catalog.rs:136-149`). On main, code mode already sees registry tools and refuses the ones that need approval (`codemode.rs:233-238`). The lane gates "native, plugin, or MCP" nested calls with approval suspension (lane `codemode.rs:1-25`). | as cited | Phase-1 extension tools are `ToolSpec` adapters registered next to `configure_plugin_tools`. They get plan mode, the authority envelope, deferral, approval and code-mode gating from code that already exists. **Phase 1 does not depend on the unmerged lane.** `ExternalToolDispatch` is left as an MCP-only interface that the lane may adopt (§5.2). |
906 | R3 | **The lane is not merged.** `origin/main` has code-mode Phase 1 (`e23ce514c`, which runs Auto-only nested calls and refuses MCP). The lane is 3 commits ahead. | `git log origin/main..feat/code-mode-mcp-6562` | Phase-1 acceptance cannot require "gated identically from `execute_tools` with `<parent>.<seq>` ids". On main, the assertion is "refused as needs-approval". Once the lane lands, it is "suspends for approval". **Resolved:** the lane landed first (#6583, then #6600), and the phase-1 fixes assert "suspends for approval" (`execute_tools_gates_an_extension_tool_before_any_host_call`). |
907 | R4 | **The self-declared read-only hint is an auto-approve.** `approval_hint_for` → `TrustedReadOnly` → `ApprovalRequirement::Auto` (`mcp.rs:1265-1274`, `tool_preparation.rs:46-48`, test at `:537-540`). | as cited | If extension tools honoured `presentCall` / `kind: 'read'` (old §4.3), a plugin would switch off approval for its own tools, and those tools run arbitrary Node. **Removed.** Extension tools are always `Required` (§4.3). |
908 | R5 | **Secrets are on disk, readable by any same-user process.** The default secret backend is `~/.codewhale/secrets/` (`crates/secrets/src/lib.rs:64-69`). MCP OAuth tokens are re-read "from the on-disk credential" (`mcp/oauth.rs:749-752`). | as cited | "Tokens never enter Node" and "one gate *even if the host is compromised*" (old §4.4, §5.1) are false until the phase-5 sandbox denies those paths. They are restated as protocol properties, not containment (§4.1, §4.4). |
909 | R6 | **The protocol names a mechanism that does not exist.** No `change:tool_surface` exists anywhere in `crates/tui/src`. | grep | Removed. Per-turn rebuild plus a liveness check at dispatch time is enough (§3.3). |
910 | R7 | **Computer Use is an MCP stdio server (`mcp/server.mjs`), not host code.** `agent.mjs` is the one-shot or `--serve` *remote SSH agent* that runs on another computer. | `crates/tui/plugins/computer-use/{package.json:12, agent.mjs:1-4}` | "Computer Use runs in host #0" (old §1.5) and the phase-2 `agent.mjs` item were wrong, and both are removed. CU stays a separate process. In phase 3 it is spawned by the broker like any stdio server. |
911 | R8 | **The manifest is closed.** `CodewhalePluginExtension` is `deny_unknown_fields` (`agent_plugin.rs:627-653`, test `:1646-1652`). A new `extensions."net.codewhale".host` key makes every *older* build reject the whole plugin. The existing `native` field and `Native` capability are exactly "executable extension, hashed, inventoried, inactive" (`manifest.rs:51,254`, `activation.rs:93`). | as cited | Phase 1 **activates `native`** as the host entry instead of adding `host` and later retiring `Native` (§4.6). Older builds keep loading the plugin's other components and report native as inactive. Only one executable-extension concept ever exists. |
912 | R9 | **One host per "session runtime" multiplies memory.** Sub-agents share the parent's `McpPool` (`tools/subagent/mod.rs:2758,3204`), and the runtime API runs many threads per process. | as cited | With a fan-out of 8, a host per session would cost 8 × ≤80 MB. Changed to **one host per engine process per trust tier**, with registrations scoped per session (§1.5). |
913 | R10 | **CI does not run root `npm test`, and its JS jobs pin Node 20 or 22.** The web job runs `npm test` inside `web/`. The CU and bridge suites use explicit `cd … && npm test` steps (`ci.yml:280-307`). | as cited | "The gate runs it automatically" is true only for the local gate. Phase 1 adds an explicit CI step on Node 22 (§8). Without it, the real-bundle Rust test would skip on CI and nobody would notice. |
914 | R11 | **The phase-1 DSH plugin has no `dsh.bundle.patch`.** Its `schemastery` is a regular *dependency*, not a peer, and the repository has only `src/index.ts`. The installable artefact is the published `lib/index.js`. | `git show 00102833:packages/skill/tool-workspace-dependencies/package.json` | Phase 1 cannot rely on recognising `dsh.bundle.patch`. The fixture is a Codewhale bundle whose `native` entry is a Cordis plugin that loads the vendored DSH `lib/index.js` with literal config. The resolve hook maps `schemastery` whether it is declared as a peer or as a dependency (§6.2). |
915 | R12 | **The phase-3 grant check was a denylist.** It inspected only `tools/call`, `resources/read` and `prompts/get`, so newer MCP methods (tasks, subscriptions, completion) would pass ungated. | old §4.4 | Changed to a default-deny method allowlist, with `arguments` compared as parsed JSON values, not by hashing re-serialized bytes (§4.4). |
916 | R13 | **Phase 1 was too large for one slice.** It combined commands, heartbeat, auto-restart with replay, `dsh.bundle.patch` recognition, a 3-capability policy split, and a dependency on the lane. | old §8 | Cut to tools only. §8 lists the exact scope. |
917
918 **Claims re-verified and left unchanged:** `ACTIVATION_POLICY_VERSION = 3`, and the whole policy (supported plus inactive lists) is hashed into every receipt (`activation.rs:107-122`), so any policy change re-reviews every plugin. `builtin.rs` digest-named materialisation. `ReviewedStdioLaunch` (`mcp.rs:929`; note that on macOS a Node entry is "hash-checked here, then reopened by path"). `HookProcessTree` / `WindowsHookJob` (`hooks/executor.rs:908-990`, private to that module). `McpCatalogBudget` (`mcp.rs:1546`). `PendingAuthorityWatch` (`mcp.rs:1661`). `ToolCallDecision::Allow` no-op (`turn_loop.rs:6364`). `updated_input` re-plan (`turn_loop.rs:3238`). `execute_mcp_tool_with_pool` (`tool_execution.rs:232`). Lane `NestedCallGate` at `:200`, `refusal_before_gate` at `:250`, `ungated_admission` at `:502`, `execute` at `:530`. Lane `ToolCallSource { Model, CodeMode }` at `turn_loop.rs:39`. `crates/tools` `ToolCallSource { Direct, JsRepl }`: its only users are the tests in `crates/tools/tests/parity_tools.rs`. DSH `mcp-client` spawns through `StdioClientTransport` (`transport.ts:10,34`). DSH `engines` is `^22.19.0 || >=24.0.0`. `vendor/cordis` is `4.0.4` with `publishConfig.access: public` (publication itself is still unverified offline).
919
920 ---
921
922 ## 1. Architecture
923
924 ### 1.1 Shape
925
926 ```
927 ┌──────────────────────────── Rust core (closed, authoritative) ─────────────────────────────┐
928 model ─────▶│ turn loop ─ plan_tool_calls ─ hooks fold ─ approval ─ sandbox ─ store ─ prompt ─ credentials │
929 │ ▲ ▲ │
930 │ │ ToolRegistry (HostToolSpec, ph.1) · ExternalToolDispatch (MCP, ph.3) │
931 │ HostSupervisor ── OwnerRegistry(owner, generation, handle) ── ProcessBroker ── FetchProxy │
932 └──────┬──────────────────────────────────────────────────────────────────────────▲──────────┘
933 │ one framed channel (stdin/stdout of the child), typed, versioned │ spawn/kill,
934 ▼ │ egress
935 ┌──────────────── codewhale-extension-host (Node ≥22.19, one process) ───────────────┐ │
936 │ Cordis root ── shim services (tools, commands, skills, systemPrompt*, mcp, logger) │──┘
937 │ ├── plugin fiber A (DSH package) ├── plugin fiber B (Codewhale TS plugin) │
938 │ └── builtin:mcp (official MCP SDK clients, one fiber per server) │
939 └────────────────────────────────────────────────────────────────────────────────────┘
940 ```
941
942 **The host has no turn loop, event store, prompt authority or approval.** Everything it does is one of three things:
943 - *registers* something, which Rust admits or refuses;
944 - *answers* a Rust request (`tool/call`, `command/run`, `hook/evaluate`, `mcp/*`);
945 - *asks* Rust to act (`core/call`, `proc/*`, `net/fetch`, `prompt/propose`), and Rust gates the action exactly as it would gate a model call.
946
947 ### 1.2 Where it lives in the repo
948
949 The package goes at **`crates/engine/extension-host/`**, named `@codewhale/extension-host` with `private: true`. **It is not a root workspace member** (correction): npm ignores a member's own lockfile, and the host needs its own pinned lockfile, as `computer-use` has.
950
951 **Why not `npm/extension-host`?** The bundle has to be `include_bytes!`-embedded by `codewhale-tui`. `builtin.rs` already puts Computer Use under `crates/tui/plugins/` so that the embed path stays inside the crate, which is what `cargo package` / `cargo install` need. The host follows the same precedent.
952
953 **Root `package.json` change:** extend the `test` script the way `web` already is: `npm test --workspaces --if-present && npm --prefix crates/engine/extension-host test && npm --prefix web test`. The local gate then covers the host. **CI does not run root `npm test`** (R10). Phase 1 therefore adds an explicit step to the existing Node-22 JS job in `ci.yml`, next to the Computer Use suites: `(cd crates/engine/extension-host && npm ci && npm test && npm run build && git diff --exit-code dist)`.
954
955 **The tests run against the committed `dist/` bundle and `node:test` only, so `npm test` needs no install.** This keeps the same property the CU and bridge suites have ("npm test works without npm ci", `ci.yml:284-286`). Only the build and drift check need `npm ci`. The package keeps its own `package-lock.json` (as `computer-use` does), so the root lockfile, which carries `wrangler`, is not churned.
956
957 **Layout:**
958
959 ```
960 crates/engine/extension-host/
961 package.json engines.node "^22.19.0 || >=24.0.0"; build + test scripts
962 src/main.ts boot: framing, console rebinding, parent watchdog, crash attribution
963 src/protocol.generated.ts GENERATED from the Rust protocol types (constants, method table, params shapes, types)
964 src/protocol.ts frame codec + envelope checks over the generated shapes
965 src/root.ts Cordis root, shim services, refusal list
966 src/shims/{tools,commands,skills,system-prompt,mcp-resources,logger}.ts
967 src/dsh/{resolve-hooks,profile,dsh-tools-compat}.ts
968 src/mcp/{service,broker-stdio-transport,proxied-fetch}.ts (phase 3)
969 dist/codewhale-extension-host.mjs committed esbuild output, single file, + LICENSES.txt
970 test/*.test.mjs node --test, importing dist/ only (no type stripping, no install)
971 ```
972
973 - **Committed build.** `dist/` is committed so that `cargo build` never needs Node or npm. CI runs `npm run build -w @codewhale/extension-host && git diff --exit-code crates/engine/extension-host/dist`. This is the same guarantee Computer Use gets today by shipping plain `.mjs`.
974 - **Dependencies are bundled** into the one file:
975 - `@deepseek-ai/cordis` 4.0.x
976 - `@deepseek-ai/schemastery`
977 - `cosmokit`
978 - the loader/include pieces we use
979 - later, `@modelcontextprotocol/client` 2.0.0
980
981 They are pinned by exact version plus lockfile integrity. MIT notices go into `dist/LICENSES.txt` and `THIRD_PARTY_NOTICES.md`.
982 - **Unverified: whether `@deepseek-ai/cordis` is published to npm.** DSH depends on it as `workspace:~`, and I had no network access. If it is not published, we vendor `refs/dsh/vendor/{cordis,loader,include}` at `00102833` under `extension-host/vendor/`, keeping the MIT notices and DSH's `vendor/README.md` modification list. Phase 1 has to settle this first.
983
984 ### 1.3 How it ships in every distribution channel
985
986 The host bundle ships the same way as Computer Use. It rides **inside the Rust binary**, so the npm, tarball, `cargo install`, brew, AUR, winget, FreeBSD, nix and Docker channels need no changes.
987
988 At first use, `extension_host::materialize()`:
989 - writes the bundle to `$CODEWHALE_HOME/extension-host/<sha256>/codewhale-extension-host.mjs` (read-only, digest-named, and never overwritten across builds, as `builtin.rs` already does);
990 - launches it with the reviewed-launch discipline from `ReviewedStdioLaunch`: the digest is re-checked on the opened file before exec.
991
992 **Node is the only new external requirement**, and only for users who enable a host plugin or, after phase 3, any MCP server. Per channel:
993
994 | Channel | Node situation | What we do |
995 |---|---|---|
996 | npm (`npm/codewhale`) | Node is present, but its `engines` floor is `>=18` | The host checks its own floor; the npm package floor is unchanged |
997 | brew / tarball / cargo / AUR / winget / FreeBSD | Node is often absent | `codewhale doctor` and `/plugin` report "extension host needs Node ≥22.19 (found: none / 20.x / broken)". Setting `[extension_host] node = "/path/to/node"` overrides discovery |
998 | nix | `packaging/nix/package.nix` | Phases 1–2: nothing, because the host is opt-in. Phase 3: add `nodejs_22` to the wrapper's `PATH`, since MCP then needs it. Do not add a runtime closure dependency for an experimental flag |
999 | Docker (`packaging/docker`, `Dockerfile`) | — | Phase 3: install Node 22 in the image |
1000 | `cargo install --git` / `--path` | Builds from a checkout | `include_bytes!` reads the committed `dist/`, so no Node is needed to *build*. `codewhale-tui` is not published to crates.io (no `cargo publish` in the release workflows), so there is no crate-size limit to plan around |
1001 | Termux / Android | Node 22 is available as a Termux package; unverified on our targets | Doctor diagnostic only |
1002
1003 **The founder must decide (§9, D1):** whether MCP-only users get a bundled Node runtime or a diagnostic. My recommendation is a diagnostic in phases 1–3, then revisit with install telemetry before MCP is moved by default. That is phase 3's exit gate.
1004
1005 ### 1.4 Process lifecycle and supervision
1006
1007 **Lazy spawn.** The host process starts only when one of these first happens:
1008 - an enabled, reviewed plugin declares a `native` (host code) entry and the flag is on;
1009 - (phase 3+) an MCP connect is needed.
1010
1011 This follows VS Code's `lazyCreateExtensionHostManager`. The host never blocks the first prompt:
1012 - **Phase 1:** the host is spawned at session start, in the background, when an enabled plugin has a `native` entry. Tools it registers join the registry at the next turn's rebuild, deferred, so they are reachable through `execute_tools` or `tool_search`. The first prompt never waits, and nothing is cached.
1013 - **Phase 3:** MCP tools are advertised from the Rust-side catalog cache (§5.4).
1014 - Either way, tools that arrive late enter through the deferred catalog / `tool_search` or `execute_tools`, so the pinned prefix is never rebuilt.
1015
1016 **Node resolution** (new in phase 1, `dependencies.rs`). `resolve_node_at_least(22, 19)` tries candidates in order:
1017 1. `[extension_host] node`;
1018 2. every `node` / `node.exe` found by scanning `PATH` in order, not only the first;
1019 3. stop at the first candidate whose `--version` both runs and parses at or above the floor.
1020
1021 The result is cached per process, together with the rejected candidates and why each was rejected, for `/plugin` and `codewhale doctor`.
1022
1023 **Spawn.** Rust spawns `node --max-old-space-size=256 --disable-proto=throw --no-addons <bundle>`. `--disable-proto=throw` stays only if the phase-1 fixtures run under it: DSH writes `__proto__` keys through `defineProperty` (`dsh-tools` `schema.ts:242`), which it allows, but other packages are unverified.
1024 - `--no-addons` follows decision D6, which recommends refusing native modules in v1. If D6 goes the other way, the flag is dropped for the trust tier that allows them.
1025 - The process is placed in its own process group (Unix) or job object (Windows), reusing the hooks' `HookProcessTree` / `WindowsHookJob`.
1026 - The environment is scrubbed like MCP's `child_env`. **No credentials enter it.**
1027 - `CODEWHALE_HOST_PARENT_PID` carries the parent PID.
1028
1029 **Handshake:** `host/hello` (host → core), then `host/initialize` (core → host), then `host/ready`, all within 2 s. A version mismatch makes the host exit with code 78 (EX_CONFIG) and puts a diagnostic in `/plugin`.
1030
1031 **Watchdogs:**
1032
1033 - **In the host:**
1034 - It exits on **EOF of stdin**, which is the protocol channel. The pipe closes when the core dies for any reason, so this is exact and immune to PID reuse. (Corrected: an earlier draft polled the parent PID every 1 s.) `CODEWHALE_HOST_PARENT_PID` is kept only for diagnostics.
1035 - Global `uncaughtException` / `unhandledRejection` handlers attribute the error to the owning fiber, using Cordis fiber context or an async-context tag set around each invocation. They report `ext/faulted {owner}` and dispose that fiber. The process survives.
1036 - `process.exit` and `process.abort` are replaced with a thrower. This guards against plugin *bugs* that would kill the host. It is not a security control, since `process.kill(process.pid)` still works.
1037 - **In Rust (phase 2; phase 1 relies on per-call deadlines and process exit only):**
1038 - Heartbeat `host/ping` every 3 s. A missed 3 s window marks the host **unresponsive**, which the status line shows. After 10 s the host is killed and restarted.
1039 - Crash tracker: 3 crashes in 5 min stops restarts. The host is then shown as failed with its last stderr. Nothing restarts silently after that.
1040 - **Phase 1 has no auto-restart.** When the host exits, the generation bump below runs, the host is marked *failed* with its stderr tail in `/plugin`, and it respawns only on the next session or on an explicit `/plugin enable`. That is the whole crash story for phase 1, and it cannot loop.
1041
1042 **Restart = generation bump.** When the host dies, Rust does the following, synchronously:
1043 1. Drops every registration the host owned (§3).
1044 2. Fails in-flight `tool/call` / `command/run` / `hook/evaluate` / `mcp/*` with a typed `ToolError::not_available("extension host restarted")`.
1045 3. Kills brokered children.
1046 4. Emits a core status event. The host itself never emits session events.
1047
1048 Rust then respawns the host and replays activations from its own record of which plugins are enabled. Replaying registrations is the plugin's job: its `apply` runs again. Rust keeps no replay log of the host's calls.
1049
1050 **Shutdown.** `host/shutdown` has a 2 s budget; this matches omp's `session_shutdown` cap, so Ctrl-C is never held hostage. After that comes SIGTERM, then SIGKILL of the process group at 3 s.
1051
1052 **Stdout discipline.** The protocol runs on the child's stdin/stdout.
1053 - Before any plugin loads, `main.ts` rebinds `console.*` and replaces `process.stdout.write` with a writer to a log channel on stderr, which Rust tails into its tracing with owner attribution.
1054 - A plugin that writes raw bytes to fd 1 corrupts framing. Rust detects this through bad magic or length, kills the host, and restarts it (counted as a crash).
1055 - I rejected fd 3: Rust's `std::process` cannot pass extra handles on Windows, and the task prefers one transport everywhere.
1056
1057 ### 1.5 Isolation units
1058
1059 - **One process means one trust domain.** Plugins in the same host share a V8 isolate and can monkey-patch each other's globals (§4.4).
1060 - **Default: one host per engine *process* per trust tier**, shared by every session, thread and sub-agent in that process. Registrations carry `RegScope::{Global, Session(id), Agent(id)}`. (Corrected from "one host per session runtime": sub-agents already share the parent's `McpPool` (R9), and a host per session would multiply ≤80 MB by the fan-out.)
1061 - host #0, builtin: only `builtin:mcp` (phase 3) and other first-party host code. **Computer Use is not host code** (R7). It remains an MCP stdio server process that the broker spawns;
1062 - host #1: reviewed third-party plugins.
1063 - Phase 1 runs host #1 only, because no builtin host code exists yet.
1064 - **Phase-3 entry gate:** `builtin:mcp` never shares a process with third-party code. The tier split has to exist before MCP moves.
1065 - **A later option is per-plugin `isolation: "process"`**, the DSH `isolate` analogue for processes, for plugins whose declared capabilities differ sharply from the rest. The supervisor already supports N hosts, because a host is keyed by `HostId`.
1066 - **Cost:** about +40 MB RSS per extra host (estimated, not measured).
1067
1068 ---
1069
1070 ## 2. Protocol
1071
1072 ### 2.1 Transport and framing
1073
1074 - **Framing.** Each frame is a 4-byte magic `CWX1`, then a u32 LE length, then UTF-8 JSON.
1075 - `MAX_FRAME = 32 MiB`, enough for Computer Use screenshots after base64. Anything larger is refused with a typed error, never truncated.
1076 - A length prefix is used rather than NDJSON. Framing errors are detectable, which matters because plugins share the process with the channel (§1.4). It also follows the precedent in Codex `code-mode-protocol/src/host/codec.rs`.
1077 - **Envelope.** JSON-RPC 2.0 (`id`, `method`, `params` / `result` / `error`). It is familiar, and in phase 3 relayed MCP frames sit inside `params` as opaque strings.
1078 - **Limits:**
1079 - At most 256 requests in flight per direction.
1080 - Outgoing queue bounded at 128. When it is full, the host awaits; Rust never blocks the turn loop on the host.
1081 - Request IDs are deduplicated over a window of 4096.
1082
1083 These copy the Codex code-mode-host limits.
1084
1085 ### 2.2 Types and versioning
1086
1087 - **Rust serde types are the source of truth.** They go in `crates/engine/src/extension_host/protocol.rs`, not `crates/protocol`, because the host protocol is private to the engine process and the app-server has no reason to see it.
1088 - Host → core types use `#[serde(deny_unknown_fields, tag = "kind")]`, because host output is untrusted input.
1089 - Core → host types are tolerant.
1090 - **Generated TypeScript.** `schemars` (already a `crates/engine` dependency, derived on the wire types under `cfg(test)`) reads each type's serde shape, and a Rust test (`crates/engine/src/extension_host/protocol/tests.rs`) renders `src/protocol.generated.ts` from it and from the Rust method table (`protocol::METHODS`): constants, error codes, the method table, every params shape the host validates, and the wire types. The file is committed and the test fails on drift (re-record with `CODEWHALE_CONFORMANCE_UPDATE=1`, then rebuild `dist/`); no npm generator is involved. Both sides still parse and round-trip the shared JSON fixture corpus (`crates/engine/tests/fixtures/extension_host/protocol/*.json`).
1091 - **Handshake:**
1092
1093 ```
1094 host → core host/hello {protocol: {min: 1, max: 1}, host_version, bundle_sha256, runtime: {name, version},
1095 tier, builtin_modules: [{id, sha256}], (memory_limit_mib)}
1096 core → host host/initialize {protocol: 1, session_runtime_id, workspace_roots, caps_granted: [...],
1097 limits: {max_frame, max_inflight, hook_deadline_ms, dispose_deadline_ms}}
1098 host → core host/ready {}
1099 ```
1100
1101 - **The bundle digest must equal the one Rust materialized.** On a mismatch the host is refused. This catches a stale or corrupted bundle. It is **not** anti-substitution: a substituted host would simply report the expected digest. The real control is that Rust chooses what to exec (§4.4, threat 1).
1102 - **Capability versioning.** Adding a method means adding an optional capability, so the protocol integer does not change. Changing semantics means `protocol + 1`. The core supports `[n-1, n]` for one release.
1103
1104 ### 2.3 Message catalogue
1105
1106 **Core → host (requests unless noted)**
1107
1108 | Method | Params → Result | Notes |
1109 |---|---|---|
1110 | `host/initialize` | above | |
1111 | `ext/activate` | `{owner: OwnerRef, entry: StagedEntry, config, scope}` → `{ok} \| {failed, diagnostic}` | `OwnerRef = {plugin_id, generation, owner_token}`. `StagedEntry` is the reviewed, hash-bound path. The host re-hashes it before `import()` |
1112 | `ext/deactivate` | `{owner}` → `{disposed, leaked: [..]}` | Returns only after the fiber is quiescent (Cordis `quiesceFiber`) or the deadline passes |
1113 | `tool/call` | `{handle, call_id, parent_call_id, input, deadline_ms, origin}` → `ToolResultWire` | Only for handles Rust registered. The call has **already passed the gate** |
1114 | `command/run` | `{handle, command_id, raw_input, agent: AgentRef}` → `CommandResultWire` | |
1115 | `hook/evaluate` (phase 4) | `{handle, event, payload, deadline_ms}` → `abstain \| deny{reason} \| ask{reason} \| annotate{text} \| revise{input}` | **No `allow` in the type** |
1116 | `mcp/connect`, `mcp/disconnect`, `mcp/list`, `mcp/call`, `mcp/readResource`, `mcp/getPrompt` (phase 3) | §5 | `mcp/call` carries a `grant` |
1117 | `proc/data`, `proc/exit` (notifications) | `{proc, stream, bytes_b64 \| code}` | Broker → host bytes for relayed stdio |
1118 | `$/cancel` (notification) | `{id}` | Cancels any request; the host fires the invocation's `AbortSignal` |
1119 | `host/ping`, `host/shutdown` | | |
1120
1121 **Host → core**
1122
1123 | Method | Params → Result | Notes |
1124 |---|---|---|
1125 | `registry/register` | `{owner, kind, spec}` → `{handle} \| {refused, reason}` | `kind` ∈ `tool, command, skillRoot, promptSection, hook, preset, mcpServer`. Rust checks the owner's reviewed capabilities, name collisions and schema caps |
1126 | `registry/unregister` | `{owner, handle}` → `{}` | Idempotent. A stale handle is a no-op (§3.2) |
1127 | `core/call` | `{owner, invocation_id?, name, input}` → `ToolResultWire \| refused` | Runs a tool **through `plan_tool_calls` + approval**, with `ToolCallSource::Extension` (§4.2) |
1128 | `proc/spawn`, `proc/write`, `proc/closeStdin`, `proc/kill` | | Process broker (phase 3). A spawn needs a Rust-issued `launch_ticket`; the host cannot name arbitrary argv |
1129 | `net/fetch` | `{ticket, method, url, headers, body_b64}` → streamed response | Fetch proxy (phase 3). Rust applies network policy and injects auth |
1130 | `prompt/propose` | `{owner, section_id, text}` → `{accepted \| deferred \| refused}` | Rust decides inclusion and timing: new sessions only, or through a recorded transition |
1131 | `storage/get`, `storage/set` | owner-scoped key/value in the core store | Phase 2+ |
1132 | `ext/faulted` (notification) | `{owner, error}` | |
1133 | `log` (notification) | `{owner?, level, msg}` | |
1134 | `$/progress` (notification) | `{call_id, progress, total?, message?}` | Streaming progress for `tool/call` and `mcp/call`. It resets the Rust-side idle deadline, like opencode's `resetTimeoutOnProgress` |
1135
1136 ### 2.4 Streaming and cancellation
1137
1138 **Streaming.**
1139 - Long results use `$/progress` notifications. The final result is a single frame.
1140 - Streamed `net/fetch` responses (SSE and Streamable HTTP) arrive as `net/chunk {stream, bytes_b64}` notifications, then `net/end`.
1141 - The host applies backpressure with `net/credit {stream, n}`, so Rust never buffers without limit.
1142
1143 **Cancellation is bidirectional and always a notification.**
1144 - **Rust cancels a host call** (turn interrupt, deadline, or revocation within `PendingAuthorityWatch`'s ~50 ms) by sending `$/cancel {id}`. The host aborts the `AbortSignal` passed as `exec.signal` (DSH `ToolExecution.signal`) or `invocation.signal`.
1145 - **Grace period.** Rust waits 500 ms for a response. After that it **resolves the call as cancelled on its own side regardless**, so the turn is never held by the host. A late response is dropped and logged.
1146 - **The host cancels its own `core/call`** with `$/cancel`, and Rust cancels the planned call the way it cancels an interrupted tool.
1147
1148 ---
1149
1150 ## 3. Owned registrations and coordinated async teardown
1151
1152 ### 3.1 Ownership model (Rust side is the authority)
1153
1154 ```rust
1155 struct OwnerKey { plugin_id: PluginId, generation: u64 } // generation bumps on every (re)activation and host restart
1156 struct Registration { handle: RegHandle /* u64, never reused */, owner: OwnerKey, kind: RegKind,
1157 public_name: String, scope: RegScope /* Global | Session(id) | Agent(id) */ }
1158 struct OwnerRegistry { by_handle: HashMap<RegHandle, Registration>, by_owner: HashMap<OwnerKey, BTreeSet<RegHandle>>,
1159 by_name: HashMap<(RegKind, String, RegScope), RegHandle> }
1160 ```
1161
1162 - **Admission.** Each `registry/register` is checked against the owner's **reviewed capability receipt** (`verify_plugin_authority`, which is re-hashed on every dispatch per #6209).
1163 - Phase 1: any registration needs the owner's `Native` capability to be reviewed and supported, via `verify_plugin_component_authority(…, Native)`, and only `kind = "tool"` exists. Later phases add finer capabilities only as they start enforcing them (§4.6). A `mcpServer` registration always needs `McpStdio` / `McpRemote`.
1164 - An unknown capability is refused with a diagnostic, and the row FAILS in the host.
1165 - **Names.**
1166 - A name that collides with a native tool, an MCP tool, another owner's tool or a reserved prefix (`mcp_`, `ext_`, `execute_tools`, `tool_search`, …) is **refused**, never shadowed. omp lets an extension replace built-ins; we do not.
1167 - **This is enforced twice.** Once at `registry/register`, against the static native set. Again at turn build, where the `HostToolSpec` adapters are added *after* natives and `~/.codewhale/tools` scripts, and any name already in the registry is skipped with a diagnostic. The second check is needed because `ToolRegistry::register` silently overwrites a same-name tool (R1).
1168 - Within one owner, re-registering the same name returns a new handle and retires the old one. This matches DSH's `NamedEntries` semantics.
1169 - **Schema caps.** Tool input schemas must be ≤ 64 KiB and description text ≤ 4 KiB. An owner may hold at most 128 tools, and a host at most 1,024. These reuse `McpCatalogBudget` numbers where they exist.
1170
1171 ### 3.2 Exact-entry undo (from DSH `NamedEntries` / `AnonymousEntries`)
1172
1173 - `unregister(handle)` removes exactly one entry. If a newer registration has taken the name, the old handle no longer matches `by_name`. Removing it only deletes its own `by_handle` row and never touches the newer entry.
1174 - In the host, each shim returns a disposer `() => void` that is idempotent and closes over its handle. Cordis runs these disposers in reverse order, either when the fiber unloads or when the plugin calls the disposer early.
1175
1176 ### 3.3 Teardown protocol (Rust revokes first, then asks the host to drain)
1177
1178 When a plugin is disabled, a trust receipt changes, the plugin is uninstalled or updated, or the session ends for session scope:
1179
1180 1. **Rust revokes synchronously.**
1181 - Remove every registration of `OwnerKey` from the catalog.
1182 - Future dispatches fail with `not_available`. `HostToolSpec::execute` re-checks that its handle and generation are still admitted before sending `tool/call`, which covers a revocation in the middle of a turn.
1183 - In-flight calls get `$/cancel` and resolve as cancelled after 500 ms.
1184 - The next turn's registry rebuild simply leaves the tool out. The tool was deferred, so the pinned prefix does not move. (Corrected: the earlier `change:tool_surface` event does not exist (R6), and none is needed.)
1185
1186 **Revocation never waits for the host.**
1187 2. **Rust sends `ext/deactivate {owner}`.** The host runs the fiber's memoised `dispose()`. Racing callers await the same promise; this is DSH `createScope().dispose` with `disposing ??= quiesceFiber(fiber)`. Disposers run in reverse order. Async disposers are awaited, e.g. `tool-workspace-dependencies` awaits its in-flight preparation (`index.ts` ~l.243).
1188 3. **Bounded wait.** The deadline is 2 s, or 5 s for MCP servers so that a transport close can finish.
1189 4. **The host acks `{disposed, leaked}`.** Leak detection counts the fiber's remaining effects, open managed timers and brokered processes after quiescence.
1190 - A leak, or a timeout, marks the host **dirty**.
1191 - Rust has already removed everything from its own view, so correctness does not depend on the ack.
1192 - Two dirty events in 10 minutes schedule a host restart at the next idle point (no turn in flight). The restart replays the remaining activations.
1193 5. **Rust kills brokered processes** still owned by `OwnerKey`, as a whole process group.
1194
1195 **Activation is all-or-nothing.** If `apply` throws, or an async `apply` rejects, or activation exceeds 5 s, the host disposes the partial fiber, which rolls back every registration made so far. It then reports `{failed}`. Rust also sweeps `by_owner` for that generation, so nothing half-registered survives on either side. **MCP tool lists get the same rule:** a refresh replaces the whole generation or keeps the previous one (DSH `mcp-client` all-or-nothing sync).
1196
1197 **Timers and child processes.**
1198 - The host exposes Cordis `ctx.setTimeout` / `ctx.setInterval`. They are `unref`'d, owned by the fiber and cleared at dispose (the omp `managed-timers` lesson).
1199 - Raw `setInterval` still works, since this is Node, but it is detected as a leak at dispose.
1200 - Child processes are expected to go through `ctx.subprocess`, which is the broker. A direct `child_process` call is outside our control until the host is OS-sandboxed (§4.5).
1201
1202 ---
1203
1204 ## 4. Trust and approvals
1205
1206 ### 4.1 The invariant, stated narrowly
1207
1208 **The claim:** every action the host asks **the core** to perform (a tool call, shell, file write through the core, process spawn, network fetch, prompt section, store write) goes through the same Rust gate as a model-originated action, and the host has no protocol method that expresses approval.
1209
1210 **What the claim does not cover:** ambient Node code (`node:fs`, `node:net`, `child_process`). The RUST memo §1.1 says the same. Until §4.5 lands, a **trusted host plugin runs with the user's privileges**. The review UI must say exactly that. This is no weaker than today's MCP stdio servers (`mcp.rs:753-756`: "not an OS sandbox") or today's `~/.codewhale/tools` scripts (R1).
1211
1212 **Concretely, "user privileges" includes the secret store** (R5). The default backend is `~/.codewhale/secrets/`, which also holds MCP OAuth tokens, and provider keys may sit in `config.toml`. The host process gets a scrubbed environment and never receives a credential over the protocol. But an unsandboxed plugin can `readFile` those paths. So everywhere this document says that secrets or tokens "never enter Node", it means **never through the protocol**, which rules out accidental leaks, logs and crash dumps. It does **not** mean a malicious plugin is contained. Containment arrives with the §4.5 sandbox, whose profile must explicitly deny `$CODEWHALE_HOME/{secrets,config.toml,auth*}` and keychain access.
1213
1214 ### 4.2 Extension-originated tool calls reuse code mode's gate
1215
1216 **Phase 1 needs none of this section.** A phase-1 extension tool is a `ToolSpec` adapter (`HostToolSpec`) in the per-turn registry (R2). When the model calls it, the call goes through `plan_tool_calls`, then hooks, then approval, then execution, exactly as a script tool's call does. When `execute_tools` calls it, main refuses it as needs-approval and the lane suspends it for approval. The host *cannot* ask the core to do anything in phase 1: `core/call` is not in the phase-1 protocol.
1217
1218 The rest of this section is phase 2, when `core/call` arrives. Lane 6562 already built what it needs. `gate_nested_call` plans one call through `plan_tool_calls(…, ToolCallSource::CodeMode)`, raises `ApprovalRequired` with a `<parent>.<seq>` id, suspends the program while it waits, and records receipts. The proposal:
1219
1220 - **Generalize `NestedCallGate` into a `CallGate`.** The turn loop serves it for any executor that runs *inside a tool call*: `execute_tools` programs and extension tool executions.
1221 - While `tool/call` for extension tool `T` is in flight, the host's `core/call` requests carrying that `invocation_id` go into `T`'s `CallGate`.
1222 - They are planned with `ToolCallSource::Extension { owner }` and receive ids `<T.call_id>.<seq>`.
1223 - Approval cards say "requested by extension `<plugin>` (inside `<T>`)". **Rust composes the card text.** The host cannot supply approval text.
1224 - **Attribution spoofing.** In a shared host, plugin B can read A's in-flight `invocation_id` and send `core/call` under it. The card would then blame A. Rust rejects a `core/call` whose `owner_token` differs from the invocation's owner, which catches bugs. Because the token is readable inside the process (§4.4, threat 3), the card for a multi-plugin host also shows "host with N plugins". **The gate itself still holds:** B's request still needs the user's approval, and a spoofed id buys a misleading label, not an approval.
1225 - **Out-of-turn actions have no gate.** Command handlers, event listeners, timers and activation code get `ungated_admission` semantics, the same as code mode without a turn: only read-only, `ApprovalRequirement::Auto` tools pass `enforce_tool_authority`, and everything else is refused with "no session permission gate; return a proposal instead".
1226 - Commands return `{kind: 'submit', prompt}`. Rust submits that as a visible user turn, so anything the model then does is gated normally.
1227 - **`ToolCallSource` hygiene.** Merge or rename before adding the third variant. `crates/tools` `ToolCallSource { Direct, JsRepl }` and the lane's private `turn_loop.rs` `ToolCallSource { Model, CodeMode }` are unrelated enums with the same name. Rename the tools-crate one to `ToolInvocationChannel`, then add `Extension { owner: OwnerKey }` to the engine one.
1228
1229 ### 4.3 What an extension can and cannot express
1230
1231 | DSH surface | Codewhale host | Why |
1232 |---|---|---|
1233 | `ctx.approval.request`, `approval/request` answerers | **Refused.** The row FAILS with a diagnostic | No self-approval |
1234 | `tools/pre-execute` returning `{kind: 'allow'}` | **Not expressible.** The shim maps allow to `abstain` and logs it once per owner | Matches DSH's own `hooks-claude-code` rule (a `PreToolUse` `allow` does not pre-approve) and Codewhale's `ToolCallDecision::Allow` no-op (`turn_loop.rs:6364`) |
1235 | `tools/pre-execute` deny / ask / revise | `hook/evaluate` verdict, folded in Rust as `deny > ask > abstain` | A `revise{input}` is **re-planned through the gate**, as `updated_input` is today (`turn_loop.rs:3238`). A hook error or timeout counts as **deny** (fail closed, as in omp `wrapper.ts:240`) |
1236 | `tools/execute` around-wrappers | **Refused** in v1 | They could rewrite results or arguments after the gate |
1237 | Providing a core service name (`agents`, `sessions`, `approval`, `llm`, `sandboxPolicy`, `credentials`, `fs`, `subprocess`, `systemPrompt`, `tools`, `commands`, `skills`) | **Refused** at `ctx.reflect.provide` time. The row FAILS | One authority per concern |
1238 | `presentCall` / annotations such as `kind: 'read'` | **Display only; never changes approval.** Extension tools are always `ApprovalRequirement::Required`, and the user can remember the approval per tool (bound to the plugin's receipt hash, so an update re-asks). They are never read-only for plan mode | (Corrected, R4.) Under `approval_hint_for`, a read-only hint becomes `Auto`, which would let a plugin turn off approval for its own tool, and that tool body runs arbitrary Node. That is self-approval. MCP servers keep today's rule unchanged; extension tools do not inherit it |
1239
1240 ### 4.4 Anti-spoofing
1241
1242 The threats, from the outside in:
1243
1244 1. **Host substitution.** A different JS file is launched as the host. Rust launches only the digest-named bundle it materialized, and re-checks the digest on an open descriptor before exec (the `ReviewedStdioLaunch` pattern). **Scope:** on macOS, `ReviewedStdioLaunch` itself hash-checks a Node entry and then *reopens it by path* (`mcp.rs:937-939`). A same-user process could still swap the file in that window, and the bundle lives in the user's own home directory. This control defeats corruption and stale builds. It does not stop an attacker who already runs as the user, who would own the machine anyway. `host/hello.bundle_sha256` is self-reported and serves only as a consistency check.
1245 2. **Plugin substitution after review.** `ext/activate.entry` is the staged, hash-bound copy from `plugins/install/stage.rs`. The host re-hashes the **whole package closure** before `import()`: every file under the package root, including any `node_modules` shipped inside the tarball. A mismatch fails activation and Rust marks the receipt `ContentChanged`.
1246 3. **Stale or cross-owner calls (confused deputy).**
1247 - Every host→core frame carries `owner_token`. This is 128 random bits minted by Rust per `(plugin_id, generation)` and handed over only in `ext/activate`.
1248 - Rust rejects a frame whose token does not match its handle's owner or whose generation is stale.
1249 - This stops bugs and stale fibers. **It does not stop a malicious plugin inside the same process**, which can monkey-patch the shared transport and read other owners' tokens.
1250 - The honest statement: **the effective authority of a host process is the union of its plugins' reviewed capabilities.** That is why hosts are split by trust tier (§1.5), and why the review UI for a plugin in the shared third-party host says "runs alongside N other plugins".
1251 4. **Impersonation toward the user or the model.**
1252 - Extension tool names cannot collide with or shadow existing names (§3.1).
1253 - `tool_search` output and approval cards always show the origin, `extension:<plugin>`.
1254 - Extension prompt sections are wrapped in an attributed, bounded envelope (`prompt/propose`), the same treatment MCP server instructions get. The host cannot write raw system-prompt text.
1255 5. **Bypassing the gate to reach MCP servers directly** (phase 3). A plugin could grab the host's SDK `Client` objects and call `tools/call` without Rust.
1256 - Stdio bytes flow through the Rust broker, and HTTP flows through the Rust fetch proxy. So Rust **parses the top-level `method` of every outbound JSON-RPC message** and applies a **default-deny** method policy (corrected from a three-method denylist, R12):
1257 - **Ungated allowlist:** `initialize`, `notifications/initialized`, `ping`, `notifications/cancelled`, `notifications/progress`, `*/list` (with pagination), `logging/setLevel`, and responses to server-initiated requests. Responses are admitted only if Rust forwarded the matching server request.
1258 - **Needs a grant:** `tools/call`, `resources/read`, `prompts/get`.
1259 - **Everything else is dropped**, including `resources/subscribe`, `completion/complete`, `tasks/*` and any method added in a future spec revision, until someone classifies it on purpose.
1260 - A grant is single-use, minted by the gate when it plans the call, and bound to `(server, generation, params.name or uri, call_id)`. It also requires `params.arguments` to **equal the planned input as a parsed JSON value** (`serde_json::Value` equality). The SDK re-serializes arguments, so a hash over bytes would reject honest calls.
1261 - A request with no grant is dropped: the broker answers the server-side request with a JSON-RPC error. The event is logged as `extension_host.gate_bypass_attempt`.
1262 - **What this buys** (corrected, R5): a host bug, or a plugin that reaches the host's SDK `Client` objects, cannot call an MCP tool without the gate, *over the brokered channel*. It does **not** survive a malicious unsandboxed plugin, which can read the on-disk OAuth token and open its own connection, or `spawn` the stdio server itself. Until §4.5, "one gate" holds for every path Codewhale provides, not against same-user code. That is the same boundary as today's MCP stdio servers.
1263
1264 ### 4.5 Sandboxing the host (phase 5, required before third-party host plugins leave experimental)
1265
1266 - Launch the host under `crates/sandbox/` (seatbelt or bwrap), with a profile that:
1267 - denies network except the loopback control socket;
1268 - denies writes outside `$CODEWHALE_HOME/extension-host/data/<plugin>/` and the OS temp dir;
1269 - allows reading the workspace and plugin roots;
1270 - **explicitly denies reading `$CODEWHALE_HOME/secrets/`, `config.toml`, auth and session stores, and keychain services**, even where the workspace allow rule would cover them (R5);
1271 - denies `exec` except `node` itself.
1272 - Once MCP egress goes through `net/fetch` and stdio spawns go through `proc/spawn`, legitimate plugin paths need no ambient network or exec. The sandbox then turns §4.1's narrow claim into the broad one.
1273 - DSH plugins that use `node:child_process` or `node:net` directly fail under the sandbox and are reported "needs unsandboxed host". That is decision D5.
1274
1275 ### 4.6 Plugin trust and review
1276
1277 - **Phase 1 activates the existing `Native` capability; it does not add a new one** (corrected, R8). `native` (alias `native_extension`) is already a hashed, inventoried and *inactive* "executable extension" component, in both `plugin.toml` and `extensions."net.codewhale"`. Under the flag it moves from `inactive` to `supported`, and each `native` path is one host entry module (an ESM Cordis plugin).
1278 - **Why not a new `host` key?** `CodewhalePluginExtension` is `deny_unknown_fields`, so every older build would reject the whole plugin. With `native`, an older build loads the plugin's skills and MCP servers and reports native as inactive.
1279 - **Why not new capabilities?** A second executable concept would need retiring later.
1280 - **Display:** `native` is shown as "host code (JavaScript)".
1281 - **Finer capabilities come later, and each is a policy bump.** Candidates are `HostCommands`, `HostHooks`, `HostNetwork` and `HostSubprocess`, the last two once the sandbox exists. Every policy change re-reviews every plugin, because the whole policy is hashed into each receipt (`activation.rs:107-122`). So add a capability only in the phase that first enforces it.
1282 - **To avoid invalidating every user's receipts for an experiment**, the policy is selected by the flag:
1283 - With `extension_host` off, it returns v3 byte-for-byte. Existing receipts, including Computer Use's, stay valid.
1284 - With it on, it returns v4 (`Native` supported). Receipts fail closed as `CapabilitiesChanged`, which triggers re-review; that is intended. **Toggling the flag in either direction re-reviews everything.** Say so in the flag's description.
1285 - **Mechanics:** `current()` is a `const fn` called at 6 production sites with no `Features` in reach (`types.rs:239`, `registry.rs:2218`, `manifest.rs:268,284,292,1676`). It becomes a read of a process-wide `OnceLock<PluginActivationPolicy>`, set once at boot from config. A config reload never flips it mid-process, and it defaults to v3 when unset, which also covers tests.
1286 - When the flag graduates, v4 becomes the only policy and everyone re-reviews once. Put that in the release notes.
1287 - **Review screen for a host plugin:**
1288 - package name and version, the full-closure content hash and file count;
1289 - declared capabilities (the `native` entries in `plugin.json`, or, from phase 5, inferred for DSH from `inject` plus the patch rows by the static Rust reviewer, §6.3);
1290 - whether it has install scripts (always refused in v1);
1291 - "Runs JavaScript on your computer with your user permissions".
1292
1293 The last line is removed only when the sandbox is on.
1294 - **Installation stays in Rust:** `plugins/install/{stage, place, tarball}` with exact-hash review. In v1, installs are from a path or a tarball only: **no npm registry fetch and no install scripts**. Dependencies must be bundled in the tarball or be host-provided peers (§6.2). A pnpm-based install with approval of build scripts is a Tier C item.
1295
1296 ---
1297
1298 ## 5. MCP on the host
1299
1300 ### 5.1 Recommended split (founder's option B, hardened)
1301
1302 | Concern | Owner | Mechanism |
1303 |---|---|---|
1304 | Which servers exist, merge and scope (global, project, plugin), project-config trust, `/mcp add`, `required` / `enabled` / `enabled_tools` / `disabled_tools`, `execute_timeout` | **Rust** (unchanged: `mcp.rs` config half, 1–1300 and 5245–6468) | Sent to the host as `mcp/connect {server, generation, transport: {stdio: {launch_ticket}} \| {http: {fetch_ticket, url}}, timeouts}` |
1305 | stdio **spawn / kill** | **Rust ProcessBroker** | Merges `ReviewedStdioLaunch` (fd-bound exec of the hashed entry), the `mcp/stdio.rs` spawn, `child_env` scrubbing plus credential injection, and hook `HookProcessTree` / `WindowsHookJob`. Bytes move over `proc/*`. Each whole process group is killed on disconnect |
1306 | HTTP / SSE / Streamable HTTP egress | **Rust FetchProxy** | The SDK transports are given `fetch: proxiedFetch`. Rust applies `NetworkPolicyDecider`, `reviewed_redirect_matches_origin`, `configured_mcp_proxy` and **injects the OAuth bearer**. Tokens never cross the protocol into Node. They are still readable on disk by unsandboxed code (§4.1) |
1307 | OAuth sign-in, token store, needs-auth state, synthetic `mcp_<s>_authenticate` | **Rust** (`mcp/oauth.rs` unchanged) | A 401 seen by FetchProxy sets needs-auth, which yields the existing `mcp_catalog_changed` metadata contract |
1308 | JSON-RPC session: initialize and version negotiation (2026-07-28 with legacy fallback), pagination, `list_changed`, reconnect with backoff, stale-session retry, resources, prompts, progress, cancellation | **Host** (`builtin:mcp` fiber per server, official SDK `@modelcontextprotocol/client` 2.0.0) | One SDK `Client` per server generation. The code is forked or adapted from DSH `mcp-client` (MIT, ~1,209 lines, effect-scoped teardown, all-or-nothing tool generations) |
1309 | Catalog admission | **Rust** | Host-reported lists are **untrusted**. They pass `McpCatalogBudget` page, item and byte caps plus name and schema validation |
1310 | Model-facing names | **Rust** | `mcp_<server>_<tool>` is unchanged; it lives in session history and the cached prefix. The host reports `(server, raw_name, annotations)` |
1311 | Approval hints, disallowed tools, ask rules | **Rust** | `McpToolApprovalHint` and `authorize_call` are unchanged. Annotations are trusted only for reviewed plugin servers |
1312 | Status for TUI, GPUI and runtime API | **Rust** | A `HostMcpClient` produces the existing `McpManagerSnapshot`, `McpRecoveryKind` and `needs_auth_generation`, so `tui/views/extensions.rs`, `runtime_api.rs:1429-1458` and the GPUI app do not change |
1313 | Server-initiated sampling and elicitation | **Rust** | The host forwards `mcp/serverRequest` to Rust, whose UI answers or refuses. Default: refuse, the same as today. **Never auto-resolved in the host** |
1314
1315 **Why not the VS Code split (option A, Rust keeps the JSON-RPC client)?** It is lower risk, but it keeps the hand-rolled Rust session code (~3,100 lines) that the founder wants gone, and it forgoes the SDK's protocol tracking (SHA-6628). Option B with brokered transports keeps every *authority* concern in Rust and moves only the protocol state machine.
1316
1317 **The cost of option B is IPC hops.** A stdio tool call crosses the channel four times: `mcp/call`, then `proc/write`, then `proc/data`, then the `mcp/call` result. Today it crosses twice. JSON results are also serialized twice.
1318 - For Computer Use screenshots (hundreds of KB to MBs of base64) this is the risk to measure. Phase 3's gate: p95 added latency ≤ 5 ms for a 1 MB result on the CU `screenshot` tool.
1319 - **Fallback if the gate fails:** a `direct_stdio` launch mode for **builtin, reviewed** servers only. The host spawns the process itself from a Rust-issued ticket that holds the exact argv and scrubbed env. That places secrets in host memory, so it is allowed only in the builtin host #0.
1320 - **Computer Use in particular.** Its `screenshot` results are the largest payloads. Today they are Rust↔CU. In phase 3 they would be CU → broker → host → Rust, parsed twice. Code mode drops image blocks from nested results anyway (lane `codemode.rs` "Known limitations"), so the extra cost falls only on direct calls. Measure it before choosing.
1321
1322 ### 5.2 Code mode reaches MCP through the one gate: the seam for lane 6562
1323
1324 **Scope (corrected, R2/R3).** This seam is for **MCP only**. Extension tools do not need it: they are registry `ToolSpec`s, which the lane already gates as "plugin" nested calls. The lane is unmerged and in flight, so this is an **offer** to that lane, not a phase-1 dependency:
1325 - If the lane adopts it before merging, `codemode.rs` does not change again in phase 3.
1326 - If it does not, phase 3 makes exactly the edits listed under "Lane changes" below. That is about 5 call sites in `codemode.rs` plus `tool_execution.rs:232`.
1327
1328 It merges the DSH and RUST memo proposals.
1329
1330 ```rust
1331 /// Tools served outside the native registry: MCP servers (Rust pool today, host in phase 3).
1332 /// Extension tools are NOT served here; they are registry ToolSpecs (HostToolSpec).
1333 /// Planning (plan_tool_calls → hooks fold → approval) happens BEFORE `call`; implementors never gate.
1334 #[async_trait]
1335 pub(crate) trait ExternalToolDispatch: Send + Sync {
1336 /// Catalog lookup by model-facing name. None = not an external tool.
1337 fn describe(&self, model_name: &str) -> Option<ExternalToolDescriptor>;
1338 async fn call(&self, model_name: &str, input: serde_json::Value, cx: ExternalCallCx)
1339 -> Result<RichToolResult, ToolError>;
1340 }
1341
1342 pub(crate) struct ExternalToolDescriptor {
1343 pub origin: ExternalOrigin, // Mcp { server, plugin: Option<PluginId> }
1344 pub generation: u64, // catalog generation; call_tool rejects stale
1345 pub starts_sign_in: bool, // replaces the `_authenticate` suffix test
1346 pub read_only_hint: bool, pub destructive_hint: bool, // already filtered by approval_hint_for
1347 }
1348
1349 pub(crate) struct ExternalCallCx {
1350 pub call_id: String, pub parent_call_id: Option<String>,
1351 pub source: ToolCallSource, // Model | CodeMode | Extension{owner}
1352 pub tx_event: mpsc::Sender<Event>,
1353 pub disallowed_tools: Arc<[String]>,
1354 pub cancel: CancellationToken, // turn interrupt + PendingAuthorityWatch revocation
1355 pub deadline: Option<Instant>,
1356 pub grant: GateGrant, // minted by the gate; opaque to McpPool today, enforced by the broker in phase 3
1357 }
1358 ```
1359
1360 **Lane changes (small; the lane's to take or leave, otherwise phase 3's):**
1361 - `NestedCallGate.mcp_pool: Option<Arc<AsyncMutex<McpPool>>>` becomes `external: Option<Arc<dyn ExternalToolDispatch>>`.
1362 - `CodemodeInvoker::execute` becomes `if let Some(d) = external.describe(name) { external.call(..) }`.
1363 - `refusal_before_gate` becomes `describe(name).is_some_and(|d| d.starts_sign_in)`.
1364 - `ungated_admission` becomes `describe(name).is_some()`, which yields "external tool; needs a session gate".
1365 - The direct path's `execute_mcp_tool_with_pool` call sites (`tool_execution.rs:232` and its callers) go through the same trait, so direct and nested calls share one dispatcher.
1366 - `McpPool::is_mcp_tool` (about 30 static-prefix call sites) becomes `external_tool_kind(name)` where the question is "is this external?", and stays name-based where it really is about the `mcp_` naming scheme.
1367
1368 **Implementations:**
1369 1. `McpPoolDispatch`, whenever the lane or phase 3 wants it: a thin wrapper that locks the pool and calls `authorize_call` then `call_tool`.
1370 2. `HostMcpDispatch`, phase 3: `mcp/call` with the grant.
1371
1372 There is no `CompositeDispatch` and no `HostExtensionDispatch` (removed). Only one implementation is live at a time, and it is swapped when the pool is deleted. The parity harness (§9.3) is the one place both exist.
1373
1374 ### 5.3 Migrating pool, deferral, always_load and auth
1375
1376 | Today (`mcp.rs`) | After phase 3 |
1377 |---|---|
1378 | `McpPool::new(config)` + `hash_mcp_config` | `HostMcpClient::new(config)`. The same hash keys the Rust catalog cache |
1379 | Lazy boot pass, `tool_selection_covers_server`, `tools_always_load`, per-turn explicit-connect wait (#6033) | **Unchanged Rust logic.** It now decides *when to send* `mcp/connect` rather than when to connect a Rust `McpConnection` |
1380 | `required: true` servers block boot / report failure | Unchanged semantics. A required server forces host spawn at boot, in parallel with provider warmup |
1381 | Deferred MCP tools via `tool_search` / `defer_loading` | Unchanged. The tool surface policy is Rust's |
1382 | `McpConnection` / transport trait / `stdio.rs`, `sse.rs`, `streamable_http.rs`, `http.rs`, `wire.rs` | **Deleted.** The SDK plus brokered transports replace them |
1383 | Reconnect / backoff (`mcp.rs:~2845`), stale-session retry | Host, per server fiber. Rust observes state via `mcp/state` notifications |
1384 | OAuth (`mcp/oauth.rs`), needs-auth transition, `_authenticate` tool | Unchanged Rust. The trigger moves from the transport to FetchProxy's 401 |
1385 | MCP prompts and resources | Host SDK, exposed through the existing Rust tools (`mcp_read_resource`, …) |
1386 | `crates/mcp` `McpManager` / `ChildProcessMcpClient` | **Deleted independently in phase 0** (dead in production per the RUST memo §1.3) |
1387 | `mcp_server.rs` (Codewhale *as* an MCP server) | Unchanged. It is a Rust server over the core gate |
1388 | `runtime_mcp.rs`, `mcp_registry.rs` (model-started servers) | Unchanged authority (`ApprovalRequirement::Required`). They now end in `mcp/connect` |
1389
1390 ### 5.4 Startup: advertise from cache, connect on demand
1391
1392 - **A persistent catalog cache in Rust.** Keyed by `(server, config_hash, server_version)`, it lives in the core store with a 30-day TTL. This follows VS Code's nonce cache, omp's SHA-256 tool cache and Codex's `LazyWhenCached`.
1393 - **Advertising.** A server with a cached catalog is advertised without starting the host or the server. The first call starts both.
1394 - **Uncached eager servers.** A server that must start eagerly and has no cache races a 250 ms window (omp's `STARTUP_TIMEOUT_MS`). Slower servers join through the deferred catalog.
1395 - **When the host is late or has died,** the cache keeps the tool array, and therefore the KV-cache prefix, stable.
1396
1397 ---
1398
1399 ## 6. DSH compatibility level
1400
1401 ### 6.1 Matrix
1402
1403 | DSH artefact | Status | Mechanism |
1404 |---|---|---|
1405 | `apply(ctx, config)` plugins and `Service` subclasses using `tools`, `commands`, `logger`, `timer`, `schemastery` `Config` | **Runs natively** (`tools`, `logger`, `timer`, `Config` in phase 1; `commands` in phase 2) | Real Cordis fibers under the host root. Shims provide `tools` (phase 1) and `commands` (phase 2). In phase 1, a plugin that injects `commands` FAILS activation with "requires `commands`, not yet provided" |
1406 | `ctx.effect`, `ctx.on` teardown, async `apply`, `internal/plugin` unload during startup | **Native** | Real Cordis semantics, with the DSH-hardened fiber (vendor mod #6) |
1407 | `skills` (roots or providers) | **Native** (phase 2) | `register.skillRoot`. Rust discovers and audits. Skills stay Markdown plus files |
1408 | `systemPrompt` sections | **Shimmed** (phase 2) | `prompt/propose`. Rust decides inclusion and timing |
1409 | `mcpResources` | **Shimmed** (phase 3) | Onto the host MCP service |
1410 | `dsh-mcp-client` rows | **Native config, Codewhale runtime** (phase 3) | Rows are translated into Rust MCP server configs (Rust stays the authority for which servers exist) and run by `builtin:mcp`. The DSH `mcp-client` *code* does not run as-is, because it spawns `StdioClientTransport` itself (`transport.ts:34`), which would bypass the broker. Names map `mcp__s__t` ↔ `mcp_s_t` for imported permission rules |
1411 | `dsh-skill-filesystem` rows | **Native config** | `register.skillRoot` |
1412 | Bundle composition: `dsh.bundle.patch` (string or list), `insert`, override-by-id, groups, disabled ancestry | **Native** (phase 2 literal rows, phase 5 full) | DSH's own `applyEntryPatches` (`vendor/include`), so it cannot drift. **Phase 1 has no patch recognition** (R11). A DSH plugin is loaded by a Codewhale bundle whose `native` entry is a Cordis plugin calling `ctx.plugin(dshPlugin, literalConfig)`. That is the same semantics as a single literal patch row, with no new parser |
1413 | `!!js` in config and `disabled` | **Native for trusted, enabled plugins** (phase 5) | Evaluated in the host against the row's ctx, as in DSH. For credential-shaped expressions (`process.env.X` in MCP `env` or `headers`), the static reviewer rewrites them to a Rust `CredentialRef(X)` so the secret never passes through Node |
1414 | `inject`, `intercept`, `isolate` | **Native** within the host root. `isolate` gives a private realm per service | |
1415 | `tools/pre-execute`, `tools/post-execute`, `agent/pre-step`, `agent/turn-stopping` listeners | **Shimmed, monotonic** (phase 4) | `hook/evaluate`. No allow. Revisions are re-gated |
1416 | `hooks-claude-code` / `hooks-codex` rows | **Mapped** (phase 4) | Onto the one hook runtime, which in phase 4 is the host's shell-hook executor, folded in Rust |
1417 | `agents`, `sessions`, `sessionProjections` | **Read-only projections** (phase 5) | Snapshots plus subscriptions to Rust core events |
1418 | `fs`, `subprocess`, `sandboxPolicy` consumers | **Gated shim** (phase 5) | `core/call` or `proc/spawn` through the gate or the broker |
1419 | Agent-preset rows (`dsh-agent-preset`) | **Translated** (phase 5) | Codewhale agent profiles at the roster's Plugin layer, capped to reviewed capabilities. The preset's `plugins` become per-agent host scopes with pinned revisions |
1420 | `llm` consumers | **Skipped** in v1 | Provider routing and billing are core. Revisit with a budgeted `core/llm` |
1421 | `approval` answerers, `allow` from pre-execute, `tools/execute` wrappers | **Refused by design** | §4.3 |
1422 | Rows providing `agent-loop`, `session-*`, `system-prompt`, persistence, `tools` / `commands` services | **Refused by design** | One loop, one store, one prompt |
1423 | `dsh.client` web modules, `slots` / `locale` / `ui*` / `remote` | **Skipped and reported** | The GPUI app is the product client |
1424 | pnpm install with build-script approval | **Tier C** | v1 accepts path and tarball only, with no scripts |
1425 | Rebuilding a retired preset revision after restart | Out (DSH does not do it either) | |
1426
1427 **Sizing** (from the DSH memo's approximate grep): about 13–21 of the ~90 parsed `inject`-declaring packages are headless and within reach by phase 5. About 69 need DSH UI or internal services and stay skipped. This is a planning estimate. Accepted Native source now reviews closed compositions and exact preset entries; unsupported service or prompt-replacement rows remain visibly broken. Complete stock-bundle acceptance must be established from actual installed Engine fixtures before claiming that every config bundle runs. UI and loop-replacing plugins remain outside the shared Engine boundary.
1428
1429 ### 6.2 Module resolution: what "natively" requires
1430
1431 DSH packages declare `@deepseek-ai/cordis` and `@deepseek-ai/dsh-tools` as **peers**. `@deepseek-ai/schemastery` is sometimes a plain **dependency**: it is one in the phase-1 plugin (R11). There must be **one** Cordis instance and one schemastery instance, or `instanceof`, symbols and services break. So the resolve hook maps these specifiers **however the package declares them**, and ignores a bundled copy under the package's own `node_modules`. So:
1432
1433 - The host installs Node **synchronous module hooks** (`module.registerHooks`, available on Node ≥ 22.15 and within the 22.19 floor). They resolve these specifiers to host-provided singletons:
1434 - `@deepseek-ai/cordis`, `@deepseek-ai/schemastery`, `cosmokit` resolve to the bundled real packages.
1435 - `@deepseek-ai/dsh-tools` resolves to a **compat module**. It exports `defineTool` plus the error classes and constants that DSH plugins use at runtime. Its types match DSH `0.1.7-alpha.2`. **It does not export `ToolRuntime` as a provider.**
1436 - Any other `@deepseek-ai/dsh-*` peer fails the row with "requires `<pkg>`, which the Codewhale host does not provide". The failure is never silent.
1437 - **Measure in phase 1:** whether bundling the real `@deepseek-ai/dsh-tools` helper subset is cheaper than maintaining the compat module. It has 109 import sites across DSH, so the compat surface should be generated from actual usage.
1438
1439 ### 6.3 What `install/dsh.rs` becomes
1440
1441 It becomes the **static reviewer**: parse `package.json`, compose the patch rows without executing anything, infer declared capabilities from `inject` and rows, hash the whole closure, and produce the review screen. It no longer *converts* anything.
1442
1443 Its module doc ("arbitrary DSH TypeScript execution is outside this compatibility scope") and `DSH-PLUGIN-ADOPTION-20260922.md` §"Compatibility boundary" **must be updated in the phase that lands native loading.** They currently disagree with the founder's direction, and under AGENTS.md that disagreement is itself a defect.
1444
1445 ---
1446
1447 ## 7. What Rust gets deleted, in order
1448
1449 This follows "migrate the last consumer or do not start". Every phase's exit criterion includes its deletion, and a phase does not count as done while both paths exist outside the feature flag. The estimates are the RUST memo's reading-based numbers, not measured diffs.
1450
1451 | Order | Deleted | ≈ prod lines | Consumers that must migrate first |
1452 |---|---|---|---|
1453 | **0** | `crates/mcp` client pool, `InMemoryMcpClient`, `ChildProcessMcpClient` and legacy CLI aggregation proxy | Removed in the 0.10.1 completion source | The earlier "no production caller" premise was false: the CLI proxy spawned registered child clients. Under the recorded founder D5 decision, that proxy is removed and `mcp-server` delegates to existing native `serve --mcp`. The unused Core/App-server pool and `/mcp/startup` route/docs were removed together. The small shared bounded instruction sanitizer remains; saved legacy definitions are preserved without a new reader/writer. Hosted and package acceptance are separate pending receipts. |
1454 | **1** (no deletion) | Nothing. Phase 1 adds the host behind the flag and deletes nothing, because no consumer has moved yet. The `ExternalToolDispatch` seam is the lane's option or phase 3's work (§5.2) | 0 | — |
1455 | **3** (MCP move) | `McpConnection`, transport trait, discovery, pool connect / supervise / backoff / reconnect / stale retry / route (`mcp.rs` ~1466–2660 and most of 2709–5240); `mcp/{sse, streamable_http, http, http_client, wire, headers}.rs`; stdio framing (spawn moves to the broker); about half of `mcp/tests.rs` | ~4,700 | `core/engine.rs`, `turn_loop.rs`, `tool_execution.rs`, `tool_preparation.rs`, `dispatch.rs`, `runtime_api.rs`, `hooks/executor.rs`, `tools/subagent/mod.rs`, `tools/runtime_mcp.rs`, `tools/registry.rs`, `codemode.rs`, `lib.rs`, `tui/views/extensions.rs`, `tui/command_palette.rs`, `tui/setup/tools_mcp.rs`. Current adoption supersedes this estimate: callers retain `McpPool`/`McpConnection` as the sole Rust authority and use the selected SDK transport. Only native protocol/client orchestration is deleted after the one-release default window; shared ProcessBroker, guarded HTTP/OAuth, framing bounds and catalogue/session policy remain |
1456 | **0** | Legacy `run_stdio_server` aggregating proxy | Removed with its last CLI consumer | Founder D5 drops the proxy. The CLI spelling remains an alias of the native server and introduces no SDK proxy or second client pool. |
1457 | **4** (hooks) | `hooks/executor.rs` orchestration: matching, env building, sync and background runs, observers, message-submit transform; part of `hooks/config.rs` validation | ~2,450 | Turn-loop fire points (kept), `tui/ui/observer_hooks.rs`, `exec_agent`. **Kept in Rust:** the verdict fold, `authority.rs` project-hook receipts, output sanitizers, and the process tree (moved into the broker) |
1458 | **4** (script tools, new row, R1) | `tools/plugin.rs` (`ScriptPluginTool`, `CommandPluginTool`, frontmatter parser; 893 lines incl. tests), `ToolRegistry::load_plugins`, the non-`Disabled` arms of `apply_overrides`, `configure_plugin_tools` (`core/engine.rs:7360-7400`) | ~700 | Users' `~/.codewhale/tools/*` scripts and `[tools.overrides]` `Script` / `Command` entries. They become one `builtin:script-tools` host plugin: each script is registered as an extension tool, spawned through the broker (the same executor as shell hooks, which is why this lands with phase 4). **Two user-visible changes are decision D9:** `# approval: auto` is no longer honoured (Required, rememberable), and a script can no longer replace a built-in. `[tools.overrides] X = "disabled"` stays in Rust: it is configuration, not extensibility |
1459 | **5** (DSH native) | The conversion half of `install/dsh.rs` and `commands/groups/plugins/dsh_import.rs`, `dsh_tests.rs`; the DSH dialects of `scripts/dsh-plugin-acceptance/convert-plugin.py` (the OpenCode dialect stays) | ~2,010 + ~200 py | `/plugin import dsh` and `POST /v1/apps/plugins/import/dsh/preview` become install-and-review of a host package |
1460 | — | (Removed row.) `Native` is no longer retired. Phase 1 makes it the host capability (§4.6, R8) | 0 | — |
1461 | optional | `integrations/dsh/*` external DSH launcher | ~2,850 | **Founder call** once DSH plugins run natively |
1462
1463 **Committed net: about −9,850 prod lines removed (including the script-tools row), +2,800 Rust added**
1464 - The +2,800: supervisor and client (~600), protocol (~500), OwnerRegistry (~500), tool adapter and MCP dispatch (~300), broker glue (~300), FetchProxy (~400), catalog admission and cache (~200).
1465 - That leaves **about −7,050 net**, plus about 5–8k lines of TypeScript. These remain reading-based estimates, not measured diffs.
1466
1467 **Stop rule.** The accepted anchor is the Phase 1 exit gate, not the September 26 host merge. If Phase 3 has not landed within six weeks of that gate, delete the host rather than retain another extension runtime behind a flag. Phase 1 exit is not yet achieved, so that clock has not started. The October 1 plan proposes a later anchor; no founder adoption of that change is recorded. `CURRENT_DECISIONS.md` §26 is the accepted decision.
1468
1469 ---
1470
1471 ## 8. Phase plan
1472
1473 ### Phase 0: independent cleanups (can run in parallel with phase 1)
1474
1475 - Delete the dead `crates/mcp` client stack (§7, row 0), **together with its live readers** (`/mcp/startup`, the `crates/core` mapping and `docs/RUNTIME_API.md`).
1476 - Re-scope **SHA-6628** (rmcp MCP 2026-07-28 client in Rust). It plans the Rust client this design removes. Its spec-convergence acceptance moves to phase 3, and the rmcp implementation is dropped. Done in Linear, not here.
1477 - *Offer* the `ExternalToolDispatch` seam to lane 6562 (§5.2). This is optional, and phase 1 does not wait for it.
1478
1479 ### Phase 1: host + protocol + extension tools + one real DSH plugin, behind a flag
1480
1481 **One PR, tools only** (cut from the earlier draft, R13). Commands, heartbeat, auto-restart, patch recognition and `core/call` all move to phase 2. What remains is the smallest slice that proves every load-bearing claim:
1482 - a TS host starts lazily;
1483 - a real DSH plugin runs unmodified;
1484 - its tool goes through the one Rust gate;
1485 - teardown is coordinated;
1486 - flag-off is byte-identical.
1487
1488 **Flag.** `Feature::ExtensionHost`, `Stage::Experimental`, `default_enabled: false`. Config key `[features] extension_host = true`. With the flag off, the host is never spawned, the activation policy is v3 byte-for-byte, and no registry, catalog or turn-loop path changes.
1489
1490 **Why tools, not hooks or commands, first?**
1491 - **Tools** land as `ToolSpec` adapters in the *existing* per-turn registry, beside `~/.codewhale/tools` scripts (R2). Every existing gate applies to them unchanged: plan mode, authority envelope, deferral, hooks, approval, and code mode. Nothing new is built on the core side of the gate.
1492 - **Hooks** would give Codewhale two hook executors (Rust shell, host JS) until the whole executor moves. So hooks wait for phase 4, where they move in one piece.
1493 - **Commands** need a new executable entry kind in `UserCommandRegistry` plus the `submit` round trip. Useful, but not load-bearing for any claim, so they are phase 2.
1494
1495 **Exact phase-1 scope: Rust** (`crates/engine/src/extension_host/`, ~900 lines estimated):
1496
1497 | File | Contents |
1498 |---|---|
1499 | `protocol.rs` | Frame codec (`CWX1` + u32 LE + JSON, 32 MiB max, typed refusal over that). Host→core types use `deny_unknown_fields`. Method subset: `host/{hello, initialize, ready, shutdown}`, `ext/{activate, deactivate, faulted}`, `registry/{register, unregister}` with `kind = "tool"` only, `tool/call`, `$/cancel`, `log`. Nothing else is accepted. |
1500 | `supervisor.rs` | Lazy spawn when an enabled, reviewed plugin has a `native` entry and the flag is on. `resolve_node_at_least(22,19)` candidate ladder (§1.4) with the `[extension_host] node` override. Digest-named materialisation reusing `builtin.rs` helpers. Scrubbed env via `child_env`. Process group / job object: move `HookProcessTree` / `WindowsHookJob` out of `hooks/executor.rs` into a shared module; it is a move, not a copy. 2 s handshake. Bounded shutdown: 2 s, then SIGTERM, then SIGKILL at 3 s. **On exit:** revoke everything, fail in-flight calls with a typed error, mark the host failed with its stderr tail. **No auto-restart.** One host per engine process. |
1501 | `registry.rs` | `OwnerRegistry` (§3.1–3.3): owner tokens, exact-handle undo, synchronous revocation, name refusal against the native set and reserved prefixes, schema caps (64 KiB schema, 4 KiB description, 128 tools per owner). |
1502 | `tool.rs` | `HostToolSpec: ToolSpec`: always `ApprovalRequirement::Required`; `capabilities = [ExecutesCode, RequiresApproval]` (as script tools); not read-only; `registration_origin = "extension:<plugin>"`; deferred by default (not in `DEFAULT_ACTIVE_NATIVE_TOOLS`). `execute` re-checks liveness, sends `tool/call`, and on drop sends `$/cancel`. The result is resolved as cancelled 500 ms after cancel whatever the host does. |
1503 | `core/engine.rs` | About 10 lines at `configure_plugin_tools`: after scripts and overrides, add the admitted `HostToolSpec`s, skipping any name already present (with a diagnostic). |
1504 | `core/engine/dispatch.rs` | Approval-card description: "Extension tool `<name>` from plugin `<plugin>` (runs JavaScript with your permissions)". |
1505 | `plugins/activation.rs` | Policy from a boot-time `OnceLock`. The v4 policy moves `Native` to `supported`, only with the flag on. |
1506 | `plugins/*` display strings | `native` is shown as "host code (JavaScript)"; the review screen shows the closure hash and file count. No new manifest key (R8). |
1507 | `features.rs`, `config.example.toml` | The flag, and the `[extension_host] node` key. |
1508 | `dependencies.rs` | `resolve_node_at_least`. `resolve_node()` is left untouched. |
1509
1510 **Exact phase-1 scope: TypeScript** (`crates/engine/extension-host/`, ~600 lines estimated plus vendored deps):
1511
1512 | File | Contents |
1513 |---|---|
1514 | `src/main.ts` | Framing; console and `process.stdout.write` rebinding to stderr before any plugin loads; stdin-EOF exit; `process.exit` guard; per-owner fault attribution via `AsyncLocalStorage`. |
1515 | `src/root.ts` | Cordis root; refusal list for core service names (`approval`, `agents`, `sessions`, `llm`, `sandboxPolicy`, `credentials`, `fs`, `subprocess`, `systemPrompt`, `tools`, `commands`, `skills`); a `tools` shim (`register` → `registry/register`, `tool/call` → `execute` with an `AbortSignal`, `output.render` applied host-side); a `logger` shim. A plugin injecting any service the root does not provide FAILS with the name of that service. |
1516 | `src/dsh/resolve-hooks.ts` | `module.registerHooks` singletons for `@deepseek-ai/{cordis, schemastery}` and `cosmokit`, whether declared as peers or as dependencies. A `@deepseek-ai/dsh-tools` compat module exporting only what the fixture uses (`defineTool` and its error types). Any other `@deepseek-ai/dsh-*` fails loudly. |
1517 | Vendored deps | `@deepseek-ai/{cordis, schemastery}` and `cosmokit`, from npm if published, otherwise vendored from `refs/dsh@00102833/vendor` with MIT notices. **This is the first task of the PR**, because everything else builds on it. |
1518 | `dist/codewhale-extension-host.mjs` | Committed, plus `LICENSES.txt`. |
1519 | `test/*.test.mjs` | Framing, the refusal list, the resolve hooks, owner teardown (reverse-order disposers, awaited async disposer). Tests run against `dist/`. |
1520
1521 **Fixtures:**
1522 - `crates/engine/tests/fixtures/extension_host/dsh-workspace-deps/`: a `plugin.json` whose `extensions."net.codewhale".native` names `index.mjs`, a Cordis plugin that does `ctx.plugin(await import('./vendor/dsh-tool-workspace-dependencies/lib/index.js'), {source: './payload/runtime.json'})`. Alongside it, the published `lib/index.js` of `@deepseek-ai/dsh-tool-workspace-dependencies@0.1.7-alpha.2` (MIT) and a small payload. The plugin injects only `tools`, registers `load_workspace_dependencies`, and has an **async `ctx.effect` disposer** that awaits in-flight work (`src/index.ts:245-248`). With no `root` config it is read-only.
1523 - `crates/engine/tests/fixtures/extension_host/refuses-approval/`: `ctx.plugin` providing `approval`. It must FAIL activation.
1524 - The protocol conformance corpus (`*.json`), which both sides parse and round-trip.
1525
1526 **CI** (`.github/workflows/ci.yml`):
1527 - In the existing Node-22 JS job: `cd crates/engine/extension-host && npm test`, then `npm ci && npm run build && git diff --exit-code dist`.
1528 - In the Rust test job that runs the new integration test: `actions/setup-node` pinned to 22, so the real-bundle test **runs** on CI. It skips, with a printed reason, only when `CODEWHALE_EXT_HOST_TESTS` is unset *and* no suitable Node is found, which is the local case.
1529
1530 **Acceptance (all run, with pass/fail counts in the commit message):**
1531 1. `npm test` passes (it now includes `npm --prefix crates/engine/extension-host test`), and `npm run check:web` passes.
1532 2. A Rust integration test spawns the real bundle under Node ≥22.19, installs the DSH fixture through the existing reviewed installer (`plugins/install`), reviews it, enables it, and drives one model-path call of `load_workspace_dependencies`. It asserts:
1533 - the tool is **deferred** and reachable through `tool_search`;
1534 - the approval request is raised (`Required`), and its text names `extension:dsh-workspace-deps`;
1535 - after approval, the result JSON comes from the fixture payload;
1536 - the same call from `execute_tools` in a main-session turn suspends for approval with a `<parent>.<seq>` id attributed to `extension:<plugin>`, and no host `tool/call` is sent before approval; allow returns the result to the program and deny fails only that nested call. (Lane 6562 landed first, as #6583; the assertion was updated in the phase-1 fixes. Without a gate, `execute_tools` still refuses it as needs-approval.)
1537 3. Disabling the plugin mid-call: Rust's registry drops the handle at once; the in-flight call resolves as cancelled within 500 ms; the host acks `disposed` only after the async disposer settles, and `leaked` is empty.
1538 4. `kill -9` on the host: the in-flight call fails with the typed `not_available("extension host exited")`; `/plugin` shows *failed* with the stderr tail; nothing respawns until the next session or `/plugin enable`.
1539 5. The `refuses-approval` fixture FAILS activation with a diagnostic, and no registration survives on either side.
1540 6. An extension tool registered with a native name (`read_file`) is refused at `registry/register`. A second one named like an existing `~/.codewhale/tools` script is skipped at turn build with a diagnostic, and the script tool is unaffected.
1541 7. With the flag off: the host is never spawned (asserted by test); `PluginActivationPolicy` hashes equal v3 (a unit test pins the digest); and `hyperfine 'codewhale --version'` shows no change. With the flag on and no `native` plugin enabled, the host is never spawned.
1542 8. The protocol conformance corpus round-trips on both sides.
1543
1544 **Explicitly not in phase 1:** commands, `core/call` and the generalised `CallGate`, heartbeat and auto-restart, `dsh.bundle.patch` recognition, `!!js`, prompt sections, skills, MCP, hooks, script-tool migration, sandbox, registry installs, and multiple hosts or trust tiers. **Trust note for phase 1:** a single third-party host is acceptable only because the flag is Experimental and nothing builtin shares it.
1545
1546 ### Phase 2: commands, restart, `core/call`, patch rows, skills, prompt sections
1547
1548 - `command/run`, with owner-bound entries in `UserCommandRegistry`. `{kind: 'submit'}` becomes a visible user turn. This needs a policy bump only if commands get their own capability (§4.6).
1549 - Heartbeat, crash tracker, and auto-restart with activation replay (§1.4).
1550 - `core/call` plus the generalised `CallGate` (§4.2), with `ToolCallSource::Extension`. This requires lane 6562 merged, because the suspension machinery is the lane's.
1551 - `dsh.bundle.patch` with literal rows (§6.1).
1552 - Generated protocol (`schemars` → TS, with a drift check).
1553 - `register.skillRoot`, `prompt/propose` and `storage/*`.
1554 - The trust-tier split: host #0 builtin, host #1 third-party. This is **required before phase 3**.
1555 - (Removed: running Computer Use's `agent.mjs` as a host plugin. It is a remote SSH agent, not host code, R7.)
1556
1557 ### Phase 3: MCP protocol orchestration moves to the host
1558
1559 **Entry gates:**
1560 - the phase-2 tier split exists, so `builtin:mcp` runs in host #0 only;
1561 - decision D1 is ratified in Ops CURRENT_DECISIONS §26: system Node with a doctor diagnostic;
1562 - the `ExternalToolDispatch` seam exists, landed by the lane or at the start of this phase.
1563
1564 **Work:**
1565 - ProcessBroker (merged spawn path) and FetchProxy with auth injection.
1566 - `builtin:mcp`, the SDK client adapted from DSH `mcp-client`.
1567 - The actual pinned SDK transport under the existing `McpConnection`/`McpPool`
1568 Rust authority facade: catalogue/session/permission/provenance and credential
1569 state stay in Rust. `mcp_backend = "host"` demand starts the Builtin tier
1570 independently of optional Native activation; harness/third-party activation
1571 continues to require the actual Native policy, including after restart.
1572 - Grant enforcement at the broker and proxy with the default-deny method policy (§4.4, threat 5).
1573
1574 **Exit gates:**
1575 - Every existing `mcp/tests.rs` behaviour test, not the transport internals, passes against the host through a Rust↔host conformance harness that reuses the MCP fixture servers.
1576 - The CU screenshot latency gate (§5.1).
1577 - Code mode's nested MCP calls pass the lane's MCP tests unchanged through `HostMcpDispatch`.
1578 - The unchanged recorded corpus and real HTTP/OAuth/Computer Use/broker tests
1579 pass; platform isolation and the measured Phase 3 gates pass before a mandatory
1580 default. D9 forbids making tier 0 mandatory before Linux/Windows host sandboxes.
1581 - Ops CURRENT_DECISIONS §26 orders the default flip for one release, then
1582 deletion of the native protocol/client adapters after their last selected
1583 consumers migrate. The Rust pool's authority/cache stays. Optional Native
1584 activation is not made mandatory by MCP. An MCP user without supported Node
1585 gets the existing doctor diagnostic, per ratified D1; no Rust fallback.
1586
1587 ### Phase 4: hooks and script tools move to the host
1588
1589 - A shell-script executor is added as `builtin:hooks` in the host, spawning through the broker.
1590 - DSH `tools/pre-execute` and related listeners, plus `hooks-claude-code` and `hooks-codex` rows.
1591 - `builtin:script-tools` registers `~/.codewhale/tools` scripts and `[tools.overrides]` `Script` / `Command` entries as extension tools (R1, D9).
1592 - The fold, sanitizers and authority stay in Rust.
1593 - Deletion rows 4 (hooks) and 4 (script tools) land.
1594
1595 ### Phase 5: full native DSH loading and host sandbox
1596
1597 - Complete patch composition, `!!js` for trusted plugins, `inject` / `intercept` / `isolate`, read-only `agents` and `sessions` projections, the gated `fs` and `subprocess` shims, and agent-preset translation.
1598 - The OS sandbox for the host, including the secret-path denials (§4.5).
1599 - `install/dsh.rs` shrinks to the reviewer.
1600 - Deletion row 5 lands. The docs listed in §6.3 are reconciled.
1601 - Decide `integrations/dsh`.
1602
1603 ---
1604
1605 ## 9. Risks, budgets, tests, open decisions
1606
1607 ### 9.1 Risks
1608
1609 | Risk | Likelihood / impact | Mitigation |
1610 |---|---|---|
1611 | Node becomes mandatory for MCP (brew, cargo, Termux users) | High / high | D1. A doctor diagnostic with an exact fix. The catalog cache still advertises tools, which fail with a clear "needs Node" error. Phase 3 does not graduate without the decision |
1612 | Broken or old Node on `PATH` (observed on this machine) | Medium / medium | `resolve_node_at_least`: try `[extension_host] node`, then every `node` on `PATH` in order, keep the first that runs and meets the version floor, and report the rejected candidates. (Not `resolve_node()`, which probes only the first `node` on `PATH`) |
1613 | Same-process plugins can borrow each other's authority | Certain / medium | Trust-tier hosts (§1.5), union-of-capabilities disclosure, broker-level grants for MCP, and the sandbox in phase 5 |
1614 | IPC cost for large MCP results | Medium / medium | Phase 3 latency gate; `direct_stdio` for builtins as a fallback |
1615 | Cordis not published on npm; vendoring churn from DSH | Medium / low | Vendor at a recorded commit with a modification list, as DSH itself does |
1616 | DSH peer-API drift (`dsh-tools` compat) | High / low | Generate the compat surface from DSH usage. Unknown exports fail loudly per row |
1617 | Two hook executors or two MCP stacks living too long | Medium / high | Phase exit criteria include the deletions; stop rule (§7) |
1618 | Trust-receipt churn when v4 becomes default | Certain / low | Flag-scoped policy until graduation; release note |
1619 | A plugin writes to stdout and corrupts framing | Medium / low | Console rebinding. Framing detection leads to host exit (phase 1: marked failed) or a restart counted as a crash (phase 2) |
1620 | Existing script tools self-approve (`# approval: auto`) and shadow built-ins (R1) | Certain (shipping today) / medium | Out of the host's scope until phase 4. The host never copies the behaviour (always `Required`; refuse or skip on collision). D9 decides the migration |
1621 | Unsandboxed host plugin reads on-disk secrets (R5) | Possible / high | Honest review text; the flag stays Experimental; third-party host plugins do not leave Experimental before the §4.5 sandbox, whose profile denies the secret paths |
1622 | Phase 1 couples to the unmerged code-mode lane | Was certain in the old draft / medium | Removed: phase 1 uses registry `ToolSpec`s, which work on main and under the lane (R2, R3) |
1623 | Memory multiplies with sub-agents and runtime-API threads | Was likely in the old draft / medium | One host per engine process per trust tier (R9) |
1624 | Out-of-date sources (SHA-6628; DSH-ADOPTION doc; `dsh.rs` module doc) | Certain / low | Reconcile in the phases named in §6.3 and §8, phase 0 |
1625
1626 ### 9.2 Budgets
1627
1628 | Metric | Budget | Basis |
1629 |---|---|---|
1630 | Added startup with no host plugins or MCP | **0 ms**: the host is not spawned | Lazy spawn |
1631 | Added startup with host plugins (phase 1) | **0 ms on the first-prompt path.** The spawn and handshake run in the background, and tools join at the next turn | Design rule; verify with the acceptance test |
1632 | Added startup for MCP users (phase 3) | 0 ms with a cached catalog. With an uncached `required` server, the host spawn (≤400 ms cold) overlaps provider warmup | Target |
1633 | Node process start | 22–31 ms warm, 96 ms first cold | Measured here: Node 22.20, `node -e ''`, 6 runs |
1634 | `hello → ready` with a bundle ≤ 2 MB | ≤ 150 ms p50 warm, ≤ 400 ms cold | Target; measure in phase 1 with `hyperfine` |
1635 | Per-plugin activation | ≤ 50 ms p50. The hard timeout is 5 s, after which the plugin FAILS | Target |
1636 | First prompt | Never waits on the host. Required MCP servers are the only eager case, and they start in parallel with provider warmup | Design rule |
1637 | Host RSS, idle, no MCP | ≤ 80 MB **per engine process per trust tier** (not per session or sub-agent). V8 heap capped with `--max-old-space-size=256` | Target; not measured |
1638 | Per MCP server in the host | ≤ 5 MB beyond the server process itself | Target |
1639 | Bundle size | ≤ 2 MB phase 1, ≤ 4 MB with the SDK | Embedded in the binary |
1640 | Hook deadline (phase 4) | 2 s default, 30 s max. The clock pauses while waiting on the user | omp `runner.ts` precedent |
1641 | Shutdown | 2 s drain, then SIGTERM, SIGKILL at 3 s | omp precedent |
1642
1643 ### 9.3 Test strategy
1644
1645 This follows the evidence rules in AGENTS.md: match the evidence to the surface.
1646 - **TS unit tests** (`node --test` against `dist/`, run by root `npm test` through `npm --prefix`, and by an explicit Node-22 CI step): framing, shims, refusal list, the `dsh-tools` compat module, fiber teardown and leak detection.
1647 - **Protocol conformance corpus.** JSON fixtures that Rust `serde` and TS both parse and round-trip. Generated types plus the drift check arrive in phase 2.
1648 - **Rust integration tests** that spawn the **real bundle** under a real Node. **CI installs Node 22 for this job, so they run there.** Locally they skip with a visible reason when no Node ≥22.19 is found. They cover admission, gating (direct, and code mode as refused on main or suspended once the lane lands), revocation, crash, and anti-spoofing: a stale token, a cross-owner handle, a name collision against natives and against scripts, and a refused `provide`. Restart and replay join in phase 2.
1649 - **MCP parity harness** (phase 3): the existing MCP fixture servers are driven through both `McpPoolDispatch` and `HostMcpDispatch` with the same assertions, until the native protocol adapters retire after the one-release default window. The Rust pool's authority/cache remains. Transport-internal Rust tests are deleted with the code they test; security guards and behaviour tests are re-targeted to the actual SDK/broker consumers.
1650 - **The DSH corpus** reuses the 41 `test_convert_plugin.py` cases as *install and review* cases (phase 5), plus the pinned real packages:
1651 - `tool-workspace-dependencies` in phase 1;
1652 - `dsh-mcp-client` rows in phase 3;
1653 - `hooks-claude-code` rows in phase 4.
1654 - **Performance:** `hyperfine` on startup with the flag on and off, and the CU screenshot latency gate in phase 3.
1655 - **Not claimed by any of the above:** hosted CI, a real provider call, or a customer run. Each is a separate level of evidence.
1656
1657 ### 9.4 Decisions and remaining choices
1658
1659 Ops CURRENT_DECISIONS §26 is the current decision authority; older alternatives
1660 below are historical proposals unless that table leaves the choice open.
1661
1662 - **D1. Node for MCP users — ratified.** System Node ≥22.19 with the existing
1663 doctor diagnostic for the initial 0.10.1 host. The September 29 founder
1664 follow-up makes Bun the target runtime and bundled executable after the four
1665 measured D2 gates; Node remains a diagnosed fallback while that work lands.
1666 Selected Host failures never silently fall back to the Rust adapter.
1667 - **D2. Node floor.** `^22.19 || >=24` for the host, matching DSH. I recommend it: Node 20 is end-of-life, and `module.registerHooks` needs ≥22.15. Computer Use is a separate MCP server process (R7) and keeps its own `>=20` floor. Several CI jobs still pin Node 20 (`ci.yml` version-drift and conversion jobs, release workflows), and none of them run host code.
1668 - **D3. Stdio secrets.** Relayed broker, which I recommend; or a `direct_stdio` ticket for builtin servers only if the phase-3 latency gate fails.
1669 - **D4. Legacy stdio proxy:** resolved by Ops CURRENT_DECISIONS §26 D5: drop it. The native `serve --mcp` server remains.
1670 - **D5. Third-party host plugins that need ambient network or exec** under the phase-5 sandbox: refuse them, or offer an explicit "unsandboxed host" tier with its own warning.
1671 - **D6. Native addons (`.node`) in host packages.** Refuse them in v1, which I recommend: they defeat the closure hash and the sandbox story.
1672 - **D7. `integrations/dsh` external launcher:** keep it or delete it once native loading lands.
1673 - **D9. Script tools** (`~/.codewhale/tools`, `[tools.overrides]` `Script` / `Command`; R1). Moving them into the host in phase 4 is required by "only the host is extensible", and it changes two behaviours:
1674 - (a) `# approval: auto` is ignored and scripts become `Required`, rememberable per tool;
1675 - (b) a script can no longer replace a built-in.
1676
1677 **Recommended: accept both, and ship them with a release note.** Today's behaviour is exactly the self-approval and shadowing the host refuses. The alternative, keeping script tools in Rust as a second extension path, contradicts the founder direction.
1678 - **D8. Tracker.** Link SHA-6521, SHA-6628 and #6562 to the host epic. Filing goes to the Codewhale team, which is public. This design contains no inference or business details, so it is safe to file there.
1679
1680 ## 10. File index
1681
1682 **Engine** (`/private/tmp/cw-wt-6446` @ `8a835d7c4`):
1683 - `crates/tui/src/plugins/{activation.rs:22,26-37,80-100, manifest.rs:35-59,254, agent_plugin.rs:649, builtin.rs:1-30, install/{dsh.rs,stage.rs}}`
1684 - `crates/runtime/src/features.rs`
1685 - `config.example.toml:1228`
1686 - `crates/engine/src/mcp.rs:536-575,753-756,2852-2865`
1687 - `crates/dependencies/src/lib.rs:54-85,278-297` (`probe_executable`, single-probe `resolve_node`)
1688 - `crates/engine/src/tools/{plugin.rs:1-20,57-172, registry.rs:53-63,360-440, spec.rs:1436-1550, codemode.rs:193-238}` (main)
1689 - `crates/engine/src/core/engine.rs:4672,4895-4915,7360-7400`; `core/engine/{tool_catalog.rs:136-155, tool_preparation.rs:40-60, dispatch.rs:870-886}`
1690 - `crates/engine/src/mcp.rs:929-1000` (`ReviewedStdioLaunch`), `:1265-1274` (`approval_hint_for`); `mcp/oauth.rs:700-760`
1691 - `crates/tui/src/plugins/{agent_plugin.rs:627-672,1646-1652, registry.rs:2205-2225, types.rs:230-240, manifest.rs:160-180,245-262,1676-1690}`
1692 - `crates/secrets/src/lib.rs:60-70`
1693 - `crates/core/src/lib.rs:24,902,914,1278-1285,2460`; `crates/app-server/src/lib.rs:376,394`; `docs/RUNTIME_API.md:55`
1694 - `crates/workflow-js/{Cargo.toml, src/lib.rs}` (code mode runs in-process QuickJS, which is untrusted model code and a separate runtime from the host by design)
1695 - `.github/workflows/{ci.yml:186-307, web.yml:13-40}`; `crates/tui/plugins/computer-use/{package.json, agent.mjs}`; `crates/engine/src/tools/subagent/mod.rs:2758,3204`
1696 - `crates/engine/src/hooks/{config.rs:27, executor.rs}`
1697 - `crates/tui/src/commands/{user_commands.rs, user_registry.rs:97}`
1698 - `crates/tools/src/lib.rs:386`
1699 - `crates/tui/plugins/computer-use/{package.json, plugin.json}`
1700 - `package.json` (workspaces)
1701 - `npm/{codewhale, runtime-sdk}/package.json`
1702
1703 **Lane** (`feat/code-mode-mcp-6562`):
1704 - `crates/engine/src/tools/codemode.rs:200-243,250-282,502-556,1175`
1705 - `crates/engine/src/core/engine/turn_loop.rs:39,~4706-4790`
1706
1707 **DSH** (`refs/dsh` @ `00102833`):
1708 - `packages/skill/tool-workspace-dependencies/{package.json, src/index.ts:237-277}`
1709 - `packages/mcp/mcp-client/{package.json, src/transport.ts, src/index.ts}`
1710 - `packages/core/tools/{package.json, src/index.ts}`
1711 - `docs/subsystems/commands.md`
1712 - `packages/feedback/command-feedback/src/index.ts`
1713 - `packages/preset/agent-preset/skills/cordis-plugin-development/references/host-plugin.md`
1714 - `package.json` (engines)
1715
1715 lines MARKDOWN