返回 CodeWhale
EXTENSIONS.md
根目录 / docs / EXTENSIONS.md
1 # Writing a plugin tool or command
2
3 The experimental TypeScript plugin host runs reviewed plugin code in a
4 shared Node process (or, as an opt-in, Bun). Rust still owns sessions, tool admission, approval and
5 execution. Plugins currently contribute tools and slash commands; they
6 cannot provide an approval service, run a second agent loop or replace
7 built-in tools or commands.
8
9 ## Quick start
10
11 Start with [hello-extension](examples/plugins/hello-extension/hello.mts) and its
12 [plugin.json](examples/plugins/hello-extension/plugin.json). The example is
13 executed unchanged by the host tests. It returns a greeting and does not read
14 files or use the network.
15
16 1. Explicitly enable `[features] extension_host = true` in your configuration,
17 or start Codewhale with `codewhale --enable extension_host` (the flag goes
18 before any subcommand).
19 2. Install the example's directory using `/plugin install <local-directory>`.
20 3. Run `/plugin validate hello-extension`, then `/plugin show hello-extension`.
21 4. Run `/plugin enable hello-extension` to open its content/capability review.
22 Read the review and personally run its exact `/plugin trust <token>` command,
23 then enable the plugin. Trust alone does not execute the code.
24 5. Ask Codewhale to use `hello_greet`. The tool follows the normal approval gate.
25 6. Run `/hello-greet Codewhale`. The command runs when you type it, and shows
26 its answer in the transcript with its origin, `extension:hello-extension`.
27 7. In the shared browser client, open **Customize → Plugins → Hello Extension**.
28 The detail panel shows the greeting command. Its [package manifest](examples/plugins/hello-extension/package.json)
29 exports [client.js](examples/plugins/hello-extension/client.js), which registers
30 `customize.plugins.detail` using the host’s React and needs no additional grants.
31
32 An authoring agent should stop after installation and validation and present
33 the review to the person, unless it runs in Full Access and the plugin is one
34 it wrote and installed from a folder in its project: then it may trust and
35 enable it for that project with `codewhale plugins trust` and `enable`. Those
36 shell commands go through the session's approval like any other: Ask asks the
37 person, Auto-Review's reviewer judges, and Full Access runs them.
38
39 ## Locations, installation and trust
40
41 User bundles live under `~/.codewhale/plugins/`; workspace bundles live under
42 `<workspace>/.codewhale/plugins/`. New bundles use Agent Plugins v1.0.0
43 `plugin.json`. Declare `extensions["net.codewhale"].native.path` as one regular
44 `.mjs`, `.js` or `.mts` file inside the bundle. Directories and other extensions
45 fail validation when the host is enabled. With the flag off, native entries
46 remain inventory-only.
47
48 A plugin may split its code across several entries with `native.paths` (up to
49 64, alone or beside `path`). They are activated in the order declared, as the
50 fibers of one plugin: they share one owner, so one disable, review change or
51 crash tears all of them down together. Each entry is a separate module with its
52 own `apply`, and tool and command names must be unique across them. If an entry
53 fails to activate (throws, requires a service the host does not provide, or has
54 a registration refused), only that entry is withdrawn: entries that already
55 activated stay registered, later entries still activate, and the plugin fails
56 only when no entry activates. Listing the same file twice is one entry.
57
58 ## Runtime
59
60 `[extension_host] runtime` selects what runs the host. Node is the default.
61 Bun is an opt-in: it is qualified on macOS only, and becomes the default only
62 after an explicit, recorded cutover.
63
64 ```toml
65 [extension_host]
66 runtime = "node" # default: Node only
67 # runtime = "bun" # Bun only; fails rather than falling back to Node
68 # runtime = "auto" # Bun >= 1.4.0 if one is found and starts, otherwise Node
69 # bun = "~/.bun/bin/bun" # the only Bun tried when set
70 # node = "/opt/homebrew/bin/node" # the only Node tried when set
71 # mcp_backend = "rust" # temporary opt-out; default is "host"
72 ```
73
74 The default `mcp_backend = "host"` uses the pinned MCP SDK independently of
75 `[features] extension_host`, which controls optional Native plugins. Existing
76 stdio and HTTP servers use modern discovery when supported; explicitly configured
77 legacy SSE servers use their legacy handshake. Rust retains process and network
78 authority, credential resolution, catalog admission, tool approval and cancellation.
79 The SDK receives opaque session selectors and exact operation grants. Modern
80 requests carry Rust-approved protocol metadata and headers without a session id.
81
82 A typed discovery refusal can admit a legacy handshake. Only an explicit HTTP
83 transport refusal during that handshake can admit legacy SSE with a fresh exact
84 Rust grant. Legacy HTTP retains its GET preflight and bounded OAuth refresh;
85 modern HTTP does not inherit those session or resend behaviors. Incomplete result
86 flows are reported without automatically repeating the operation. Credentials,
87 configured URLs, OAuth browser/login operations and Computer Use decision keys
88 stay in Rust.
89
90 Both backends share recorded semantic MCP goldens and retain separate transport
91 goldens, including discovery, authentication and session evidence. The Host default
92 requires those fixtures and the actual broker acceptance checks, plus the platform
93 isolation and measured gates in Ops CURRENT_DECISIONS §26. An explicit
94 `mcp_backend = "rust"` remains available for one release after the qualified default
95 flip, before the native protocol adapters retire. Missing or unsupported Node uses
96 the existing doctor runtime diagnostic. Host failures never select Rust automatically.
97
98 The stock data and speech adapters have independent experimental flags:
99 `[features] data_host = true` and `speech_host = true`.
100 Each defaults to Rust. Speech preparation is shared by CLI `speech`/`tts` and
101 the model tools; clone samples, provider requests and output writes stay in Rust.
102 Selecting either uses the pinned Builtin harness and its existing operation
103 broker, even when Native plugins are disabled. Rust retains network/file
104 access, parsing diagnostics and permissions. A selected Host failure is reported;
105 it never silently switches to the Rust adapter.
106
107 Node must satisfy `^22.19 || >=24`; Bun must be 1.4.0 or newer. Leaving
108 `runtime` unset means `node`, except that a table which sets only `bun` means
109 `bun`. A configured `node` or `bun` path is the only candidate for that
110 runtime: if it does not run or is below the floor, the host fails with that
111 reason instead of searching `PATH`. Without one, every `node` (or `bun`, then
112 `$BUN_INSTALL/bin`, default `~/.bun/bin`) on `PATH` is tried in order, and one
113 inside a `node_modules` directory or the working directory is skipped without
114 being run; set the path explicitly to use such a runtime. The working-directory
115 check does not apply when Codewhale starts in a directory that contains your
116 home directory, such as `~` or `/`.
117
118 Under `auto`, if the Bun it found fails to start the host, `/plugin` reports
119 why once and Node runs the host for the rest of the session. The runtime is
120 pinned once a host on it completes its handshake, and restarts reuse it. A
121 runtime binary replaced at that path mid-session is refused; restart Codewhale
122 to use it. `codewhale doctor --full` and `/plugin` show which runtime runs the host,
123 its version and path, how its memory cap is enforced, and, when `auto` used
124 Node, why Bun was not used.
125
126 When the host cannot take a call, `/plugin` and the failing plugin tool
127 call give the same reason: not started, starting, unresponsive, restarting
128 after a crash (with how it exited), failed to start or out of crash budget
129 (with the reason; change or reload a plugin to retry), or disabled by config.
130 Every call into the host has a deadline, 120 s for a tool call; past it
131 Codewhale cancels the call, reports a timeout, and the host keeps serving
132 other calls. A plugin that ignores cancellation keeps running inside the host
133 until the host is torn down.
134
135 Write plugins for both runtimes. Use Node's APIs (Bun implements them) and
136 only erasable TypeScript in `.mts`. Enums, decorators and syntax that needs
137 transformation require a separate author build to JavaScript. Bun would accept
138 more, but Node would not. Node never reads a `tsconfig.json` for the host. Bun
139 does: a `tsconfig.json` next to or above a plugin's files applies its
140 `paths`, `baseUrl` and JSX settings to that plugin's imports, so an import
141 that resolves under Bun can fail under Node. Do not rely on it. Known limit:
142 that includes a `tsconfig.json` in a directory above the reviewed bundle,
143 which is not part of what you reviewed. See
144 [Node's TypeScript rules](https://nodejs.org/docs/latest-v22.x/api/typescript.html).
145 Under Bun the host runs with `--no-install`: a missing package fails the import;
146 it is never downloaded.
147
148 Reviewed DSH compositions admit every local module against its recorded path
149 and SHA-256 before importing it. Node checks runtime resolution; Bun prepares
150 the reviewed JavaScript syntax and checks computed imports before they run.
151 Unreviewed files and ambient package imports are refused. Bun currently cannot
152 preserve query/fragment module identity, and computed CommonJS resolution also
153 requires Node. These cases stop with a diagnostic: select
154 `[extension_host] runtime = "node"` for that composition. Ordinary UTF-8 source
155 and reviewed computed file/JSON imports work on both runtimes.
156
157 Plugins cannot run native code inside the host. On both runtimes
158 `process.dlopen`, `process.execve` and Worker threads are unavailable (a Worker
159 is a new JavaScript realm that would start without these restrictions). Under
160 Bun, `bun:ffi`, `Bun.FFI`, `bun:sqlite`, `node:sqlite` and `ShadowRealm` are
161 unavailable too; under Node, `node:sqlite` and `node:ffi` are switched off
162 (SQLite extensions and FFI load native libraries). The host refuses to start
163 when one of these restrictions does not hold on the installed runtime. Known
164 limit: these are the native-code entry points found so far (Bun 1.4, Node 22
165 and 26); one a newer runtime adds is not covered until it is added. A
166 process a plugin starts is outside this policy; on macOS and Linux it runs
167 under the same sandbox as the host.
168 Include local imports in the bundle; trust stages reviewed content, and the
169 entry is rehashed before import. Changes to reviewed bytes or capabilities
170 require another review. See [bundle rules](PLUGIN_BUNDLES.md).
171
172 ## Imports and services
173
174 Export a Cordis plugin function or an object with `apply`. The host supplies
175 one shared Cordis and the supported DSH compatibility services. The example's
176 `inject = ['tools', 'commands']` asks for the tool and command registries. The
177 supplied service names are `tools`, `commands`, `prompt`, `storage`, `skills`, `shellHooks`, `avatars`, `mcp`, `logger`,
178 `events`, `reflect` and `registry`. `ctx.avatars.registerPack({path})` registers a
179 reviewed bundle-relative avatar pack; see
180 [the whale-avatar example](examples/plugins/whale-avatar/README.md). Since
181 0.10.5 the terminal's whale view no longer draws registered packs; the
182 registration and the Runtime API that lists packs are unchanged. A tool can ask the core to run a core tool through
183 `exec.core` (see [Asking the core to run a tool](#asking-the-core-to-run-a-tool));
184 Reviewed Native entries can propose MCP definitions through `ctx.mcp` as
185 described below. Programmable pre-execute listeners use `ctx.on` as described below. A required
186 service that is unavailable fails activation with a diagnostic.
187
188 Package runtime dependencies and local imports within the reviewed bundle.
189 Do not install packages or fetch code during activation. Register cleanup
190 through `ctx.effect`; asynchronous disposers are awaited with a deadline.
191
192 `ctx.prompt.registerSection({ id, text })` contributes an attributed plain-text
193 section and returns its disposer. Rust delivers the complete current snapshot
194 as a user-role runtime message; changes replace earlier snapshots and an empty
195 snapshot explicitly withdraws earlier sections. Rust admits
196 sections only for the caller's live reviewed owners, sorts them by owner/id,
197 and withdraws them on unregister, disable, revoke or host exit. Each section
198 is limited to 4 KiB UTF-8 text, each owner to 32 KiB and 128 sections, and the
199 host to 128 KiB and 1,024 sections. The final attributed prompt has the same
200 128 KiB limit. IDs use lower-case letters, digits, `_` and `-`, start with a
201 letter, and contain at most 64 characters. Duplicate owner-local IDs require
202 disposing the earlier section first. The author cannot replace the core
203 system prompt or select another session's sections.
204
205 To interpolate Core's accepted turn facts, register
206 `{id, text, interpolate: 'model-cwd'}`. Only `{{model}}` and `{{cwd}}` are
207 supported; Rust expands them once when it captures the turn's prompt. Literal
208 sections retain braces unchanged. Both source and expanded text must fit the
209 section and snapshot limits. Scoped contributions keep their exact selected
210 entry identity through capture and withdrawal. The fixed DSH persona bridge
211 uses this path for additive prefix/suffix text; complete prompt replacement and
212 runtime-context suppression are refused.
213
214 Reviewed DSH compositions can register Claude Code and Codex command hooks
215 through `shellHooks`. Codewhale's sixteen firepoints use the same
216 pinned Builtin runner and Rust-owned process driver when the host feature is
217 enabled. Rust retains hook approval, process environment and final verdicts;
218 ShellEnv values remain in Rust. Forced continuation, observer steering,
219 noncommand hooks and asynchronous dialect commands are unsupported and
220 reported explicitly. A Native hook's `allow` cannot approve a tool.
221
222 `ctx.storage.get(key)`, `set(key, json)` and `delete(key)` persist owner-local
223 JSON under the `dataDir` Rust assigned. The API refuses access once owner
224 disposal begins, symlinked storage, corrupt data and writes that exceed its
225 bounded key/value/owner limits. It does not expose session history or secrets.
226 Tool and command invocations also expose frozen `sessionId`, `agentId` and
227 `originTurnId` strings when Rust supplies them for that particular call. Tool invocations
228 with an authoritative session and workspace also expose frozen `exec.agent.id`
229 and `exec.agent.session.header.cwd`; root identity uses the session id and a
230 child uses its supplied agent id. The projection has no methods and retaining it
231 grants no operations after the invocation ends.
232
233 An entry injecting `sessions` can call `ctx.sessions.flush(exec.agent.session)`
234 while its directly invoked root tool holds an Engine checkpoint ticket. The
235 argument must be that invocation's exact session object. The Engine captures
236 its committed prefix and waits for the owning Runtime, terminal, or exec store
237 to acknowledge persistence. Runtime retains its existing receipt-secret
238 redaction policy; success describes that persisted projection. It does not
239 include the running tool's future result or the plugin's separate journal.
240 Runtime recovery retains later tool results without replaying the tool.
241 Checkpoint-bearing Runtime turns require schema version 5; older readers
242 refuse them rather than silently reconstructing incomplete history.
243
244 `false` is reserved for a deliberately ephemeral host with no persistence
245 backend. Missing authority, foreign or expired handles, child checkpoints,
246 superseded writes, storage failure, cancellation and unavailable consumers
247 reject. Cancellation can race a disk write, so a rejected call does not prove
248 nothing was written. Other `sessions` methods remain unsupported.
249
250 An entry injecting `subagents` can start one independent child agent from its
251 directly invoked root tool. `ctx.subagents.getProvider('spawn')` describes the
252 only provider: a fresh child with no inherited conversation.
253 `ctx.subagents.startActivation({ provider: 'spawn', childId, request: { parent:
254 exec.agent, prompt, agentOptions: { model } }, signal, delivery })` runs the
255 entry's own `agent/created` listeners first. There the child's
256 `ctx.systemPrompt.section({ name: PERSONA_PREFIX_SECTION, ... })` sets a persona
257 of at most 32 KiB, appended to that child's own system prompt and recorded in
258 its launch manifest. `ctx.tools.restrict({ deny })` adds to the tools the child
259 may not use. Then the Engine starts the child as an ordinary `agent` start
260 through this turn's approval gate. The plugin's call needs its own approval and
261 never reuses the model's grants. The child runs in Codewhale's existing
262 sub-agent manager inside the parent's permission and budget limits. The
263 returned activation resolves once the child accepted its first message.
264 `result` waits for the child to finish and returns its text output and stop
265 reason. `dispose()` stops that exact child and its own descendants.
266 `delivery: 'caller'` hands the result only to the plugin, not to the parent
267 model. A child the plugin never disposes is stopped when the invocation ends.
268 `ctx.tools.get(name, exec.agent)` reports whether the calling agent has a tool.
269 Prompts are text only. Only the `model` agent option is accepted. The service
270 is unavailable inside a child agent's own tool calls. Non-text output and the
271 other DSH agent APIs are not supported, and
272 `agents` and root-level `systemPrompt` offer no methods.
273
274 ## MCP definitions
275
276 `ctx.mcp.registerServer({ serverName, server })` returns an idempotent disposer
277 and proposes a literal MCP definition to the existing Rust catalog. Include
278 `mcp` in the entry's `inject` list. Rust owns transport connections, tool
279 admission, permissions and authentication; this service does not expose
280 credentials or grant plugins direct process or network access.
281
282 Definitions retain their exact reviewed, selected Native entry receipt.
283 The limits are 64 servers per owner, 256 per host and 64 KiB per definition.
284 Literal stdio, streamable HTTP and SSE definitions are supported by the bridge;
285 credential values, endpoint query data and unsupported startup/reconnect
286 controls are refused. Disposing an entry, changing its caller selection,
287 disabling its plugin or changing reviewed bytes withdraws its definitions and
288 cancels affected calls. An uncertain write is never replayed.
289
290 The raw DSH skill-filesystem bridge uses the same reviewed skill-root service
291 below. Its configuration must explicitly set `includeDefaultRoots: false` and
292 `watch: false`, and list bundle-relative `customSkillDirs`. Ambient filesystem
293 roots and independent watchers remain unsupported.
294
295 ## Skill roots
296
297 `ctx.skills.registerRoot({ path: 'profiles/review-skills' })` returns an
298 idempotent disposer and contributes reviewed instructions to Rust's existing
299 skill catalog. Include `skills` in the entry's `inject` list. For example:
300
301 ```js
302 export const inject = ['skills']
303 export function apply(ctx) {
304 ctx.skills.registerRoot({ path: 'profiles/review-skills' })
305 }
306 ```
307
308 Place each skill in a child package directory such as
309 `profiles/review-skills/quick-check/SKILL.md`. Paths are bundle-relative,
310 at most 512 UTF-8 bytes, with normal slash-separated components. Absolute
311 paths, links, empty components, `.` and `..` are refused. Rust parses only
312 files covered by the reviewed bundle inventory, through the existing
313 [frontmatter and invocation contract](SKILLS.md#invocation-and-alias-metadata).
314 The existing nesting rules apply: hidden child directories are skipped, and
315 a package containing `SKILL.md` claims its nested examples. An invalid skill
316 or an empty root refuses admission. Native review covers this registration;
317 the entry does not need a separate declarative Skills component.
318
319 Pending and admitted roots count toward the host shim's limits: 8 roots per
320 owner and 64 per host. Rust stops each root proposal at 128 candidate
321 `SKILL.md` files or 4 MiB of raw input. Retained instruction fields are also
322 limited to 128 skills / 4 MiB per owner and 1,024 skills / 32 MiB per host.
323 These are logical catalog limits. Duplicate owner-local root paths require
324 disposing the earlier root first.
325
326 Disposal, disable, revocation and host exit remove the root from later
327 discovery. Loading a selected skill rechecks the reviewed Native receipt and
328 the live registration. Queued selections also recheck it; selections saved
329 before a process or host restart require selecting the skill again. Completed
330 session history remains the record of instructions already used. Roots have
331 no watcher, companion-file access or tool permission grant; core approval and
332 sandbox policy continue to apply.
333
334 ## Tool rules
335
336 Register a unique name with `ctx.tools.register`, a description, a JSON object
337 input schema and an `execute(input, exec)` function. Names start with a letter,
338 contain only letters, digits, `_` and `-`, and are at most 64 characters. Use a
339 plugin-specific prefix, such as `hello_greet`. Core names, core approval-name
340 families, and `mcp_`/`ext_` prefixes are reserved. Refusals explain the rule.
341
342 Every plugin tool is `Required` and never treated as read-only based on a
343 plugin's claim. Full Access, Bypass or an exact session grant for the reviewed
344 plugin receipt may satisfy that requirement without another prompt. Tools are
345 deferred by default; `[tools].always_load` can pin a tool through the normal
346 tool configuration. Registration never grants permission to execute it.
347
348 The core checks every call's input against that schema (JSON Schema, draft
349 2020-12 unless the schema names another) before it asks for approval and again
350 before anything is sent to the host, so `additionalProperties: false`,
351 `required`, types and bounds hold even when `execute` does not check them. A
352 call that fails is returned to the model as an invalid-input error naming what to
353 correct, and the host never sees it. A schema that cannot be compiled (an
354 invalid keyword value, or a `$ref` to anything outside the schema itself;
355 nothing is fetched) is refused at registration, which fails activation with the
356 reason. Declare the narrowest schema you can: it is both what the model sees
357 and what is enforced.
358
359 Return a JSON value or text; the host renders it into ordinary tool output.
360 Avoid secrets in descriptions, logs and results. An approval card's wording
361 and identity come from Rust, never from plugin-supplied labels.
362
363 For DSH definitions with `output`, declare both `output.schema` and
364 `output.render`. The host validates the canonical JSON result before rendering
365 it. This adapter currently accepts plain text blocks only; unsupported rich
366 content or extra block fields produce an explicit error instead of disappearing.
367 A boolean `deferLoading` is accepted as a presentation hint; the Engine
368 keeps its existing tool-loading policy. Non-boolean values are refused.
369 Nonempty registration options, `when`, `projectContent`, `finalizeContent`
370 and `timeoutMs` remain unsupported and are refused. The shared
371 [`compatibility.json`](../crates/engine/extension-host/src/dsh/compatibility.json)
372 pins the definition API to DSH 0.2.2-rc.1 and records service, row-bridge and
373 module mappings. Its bytes participate in Native content and capability review,
374 so changing the compatibility contract invalidates prior trust.
375
376 Successful and soft-failure tool results carry Rust-stamped `extension`
377 metadata identifying the plugin, reviewed content, entry, generation, caller
378 selection, handle and process boot. Plugin-supplied output cannot choose this
379 identity.
380
381 ## Command rules
382
383 Register a slash command with `ctx.commands.register`, which returns an
384 idempotent disposer (the registration is also removed when the plugin unloads):
385
386 ```ts
387 ctx.commands.register({
388 name: 'hello-greet', // /hello-greet
389 description: 'Greet someone.', // one line, shown in the palette and /help
390 argumentHint: '[name]', // optional; a command with a hint waits in
391 // the composer for arguments
392 handler({ args, signal }) {
393 return { kind: 'success', text: `Hello, ${args || 'world'}!` }
394 },
395 })
396 ```
397
398 Names are lower case, start with a letter and use only `a-z`, `0-9`, `_` and
399 `-` (at most 64 characters). A command can never take the name of a built-in
400 command (or one of its aliases) or of another plugin's command: the
401 registration is refused, activation fails, and the reason is in `/plugin`.
402 A user, workspace or plugin-manifest markdown command with the same name wins
403 the spelling and the plugin command is left out of the registry. Descriptions
404 (1 KiB) and hints (256 bytes) are single-line text.
405
406 A handler runs only when the **user** types the command; invoking it is the
407 user's own action and needs no approval. It can only return an answer:
408
409 - a string, or `{ kind: 'success', text? }`: shown in the transcript;
410 - `{ kind: 'error', text }` or a thrown error: shown as a failure;
411 - `{ kind: 'submit', prompt, text? }`: `prompt` enters the ordinary turn with
412 Runtime provenance and visible plugin attribution. Every model tool call
413 is gated as usual. `text` is shown beside the prompt.
414
415 The handler cannot call the model, a tool or approval. Output is stripped of
416 terminal escape sequences and cut at 64 KiB; a prompt over 128 KiB is refused,
417 not truncated. A command has 30 seconds: past it Codewhale cancels the call
418 (`signal` aborts) and reports a timeout. If the host is down, the command
419 fails at once with why.
420
421 `args` is what follows the command name, trimmed. The invocation also carries
422 `signal`, a `commandId` and an empty `attachments`. DSH plugins using
423 `ctx.commands.register({ name, description, input: { hint }, handler })` and
424 returning `{ kind: 'success' | 'error', text }` run unchanged, including
425 `import { CommandDefinitionId } from '@deepseek-ai/dsh-commands/brand'` (the
426 only `dsh-commands` import the host resolves; `definitionId` is accepted and
427 ignored). DSH's `rawInput` is provided (it keeps the leading separator,
428 `' name'`). When Rust supplies the caller session, `invocation.agent` exposes
429 its read-only id and `followup(message)`. A handler may capture exactly one
430 JSON user message with a bounded id, a source containing only `kind`, and one
431 plain text content block. Successful completion converts it to the same Submit
432 result; an error result, cancellation or exception never submits it. Explicit
433 Submit plus followup, multiple messages, attachments, empty text and text above
434 128 KiB are refused. The handle closes when the invocation settles. Core owns
435 the resulting turn identity and provenance; this is not a general agent service
436 or persistence of the supplied DSH message identity. Missing caller context
437 refuses access.
438
439 Not provided: attachments (`input.attachments: true` fails activation), a `list`/`find`/
440 `execute` surface, and DSH command lifecycle events. The Runtime API records
441 Codewhale command admission, completion and cancellation in its existing event
442 store.
443
444 Thread snapshots also include bounded `command_receipts` for the most recent
445 100 terminal commands that did not submit a turn. Each receipt has a stable
446 identity, completion time, status, text and plugin attribution. This is a
447 projection of the existing event log; reopening a native App conversation can
448 display the result without rerunning a command or adding it to model history.
449
450 ### Runtime API and native App
451
452 Read `GET /v1/commands?thread_id=<id>` to discover commands for that thread's
453 workspace and plugin selection. Plugin entries have `kind` and `binding`
454 set to `extension`, an `origin` and an opaque `registration_id`. A listing
455 without a thread has no invocable registration identity.
456
457 Submit `name`, `args`, `registration_id`, `operation_key` and
458 `expected_workspace` to `POST /v1/threads/<id>/commands`. Reuse the same
459 operation key only for the exact same request. A completed retry returns the
460 stored outcome; a pending or uncertain invocation is never executed again.
461 `GET /v1/threads/<id>/commands/<operation_key>` reads the result. If a recorded
462 invocation has lost its worker, lookup settles an explicit uncertain outcome
463 and recovers any admitted turn without rerunning the callback. `DELETE`
464 requests cancellation, including cancellation before admission and interruption
465 of an associated active turn. A stale
466 registration or changed workspace requires discovering and selecting again.
467
468 The Engine admits a returned prompt through its ordinary turn lifecycle with
469 Runtime provenance. TUI and App present it as attributed plugin input and exclude
470 it from ordinary human recall, edit and retry. Clients must not resubmit that prompt. Results include the
471 accepted turn when present and the exact plugin receipt. The native App
472 uses these routes for its command palette and slash input, preserves edited
473 drafts and refreshes the catalog after plugin changes and reconnects.
474
475 ## Execution context
476
477 A tool's `execute(input, exec)` gets, in `exec`:
478
479 - `signal`, the call's cancellation signal; check it and propagate it to
480 asynchronous operations;
481 - `callId`, which identifies the call, and `args`, its input (also the first
482 argument);
483 - `workspace`, the root path of the workspace of the session that made the
484 call, and no other (it is absent only if that path is not valid UTF-8);
485 - `dataDir`, the plugin's own directory;
486 - `core`, only while the call runs under the turn's permission gate:
487 [`exec.core.call`](#asking-the-core-to-run-a-tool).
488
489 A command's handler gets `workspace` (where the user ran it) and `dataDir` in
490 its invocation beside `args`, `signal` and `commandId`. All of these are
491 read-only strings (`exec` and the invocation are frozen). Nothing else about the
492 machine is passed: no home directory, no other workspace, no credential path.
493 A call id or plugin trust grants no new privileges.
494
495 The workspace is where the *call* comes from, so read it per call: one host
496 serves every session in the Codewhale process, and a tool called from another
497 workspace sees that one. The host process's working directory is its data
498 directory, not the caller's workspace; do not use `process.chdir` in this
499 shared process, and resolve relative paths against `exec.workspace` yourself.
500 Reading a workspace file is your code's own filesystem access, under the host's
501 sandbox, not something the core checks per file.
502
503 `dataDir` is `~/.codewhale/extension-host/data/plugins/<name>-<id>` for plugins you reviewed,
504 or `~/.codewhale/extension-host/data-agent/<digest>/plugins/<name>-<id>` for plugins the agent approved
505 (where `<digest>` is a 128-bit hex digest of the normalized project path), created by
506 Codewhale (mode 0700 on Unix) before the plugin activates, and the same
507 directory for every generation and every entry of that plugin, so it keeps
508 files across restarts and updates. It sits inside the host's one writable
509 root, which is where the sandbox allows writes. It is not a boundary between
510 plugins in the same host: they share a process, and one can write into another's directory.
511 Codewhale never deletes it, including on uninstall.
512
513 ## Configuration
514
515 A user configures a plugin in their own `config.toml`, keyed by the plugin's
516 manifest name:
517
518 ```toml
519 [plugins."hello-extension".config]
520 greeting = "Howdy"
521 ```
522
523 That table is delivered as the second argument of `apply(ctx, config)`
524 (`{}` when there is none). If the entry module exports a `Config` schema
525 (`import Schema from '@deepseek-ai/schemastery'`; `export const Config =
526 Schema.object({ ... })`), the host validates the table against it before
527 `apply` runs, applies its defaults, and a mismatch fails activation with the
528 reason, so the plugin only ever sees a config its own schema accepts. Every
529 entry of a multi-entry plugin gets the same table and checks it against its own
530 `Config`. [hello.mts](examples/plugins/hello-extension/hello.mts) reads one
531 such setting.
532
533 - It is the user's data, not part of what was reviewed: the user can change
534 it without a new trust review, which is why only the user's config can set it
535 (a project's `.codewhale/config.toml` cannot).
536 - Plain TOML values only (a date-time is refused), at most 16 KiB serialized
537 and 16 levels deep. A table over a limit fails that plugin's activation with
538 the reason, in `/plugin show`; it is never delivered cut short.
539 - `/plugin show <name>` lists the configured keys (not the values) and says
540 when the config is refused. Do not put a secret in it: the plugin's code
541 reads every value, and so does any other plugin in the shared process.
542 - Codewhale reads `[plugins]` at start, and again at `/plugin reload` (or any
543 plugin command that changes plugins). A plugin whose table changed is revoked
544 and activated again as a new generation, with the new values; one whose table
545 did not change is left alone. A file that cannot be read keeps the previous
546 settings.
547
548 ## Programmable tool admission
549
550 A reviewed native mod may register `ctx.on('tools/pre-execute', async (exec, next) => ...)`. The frozen call view carries `name`, `callId`, `arguments`, `signal`, `workspace`, `mode`, and `model`. It has no session, agent, tool, or approval handle. `next()` returns an abstention; Rust evaluates the remaining listeners and gates.
551
552 Return `{kind:'deny', reason}`, `{kind:'ask', reason?}`, `{kind:'revise', input}` (a JSON object), `{kind:'annotate', text}`, or `{kind:'abstain'}`. `undefined` also abstains. DSH-shaped `allow` is an abstention and logs a warning once per owner. A malformed answer, thrown error, timeout, or withdrawn owner fails the call closed. The listener batch has a five-second deadline and observes cancellation through `exec.signal`.
553
554 Native hooks run first, then mod listeners in core registration order. Denial always wins; the last accepted input revision wins. Rust re-prepares revised arguments and reruns the existing authority, policy, and approval checks. Input revisions use the existing 32 KiB hook limit; context and reasons use the existing sanitizers. Unloading a fiber removes its listener, and disabling or revoking an owner retires its admitted handles before host teardown. Other workspaces do not receive the call.
555
556 This bridge runs on Engine sessions, including model tools, gated code-mode calls, and `exec.core` calls. Sessions an editor drives over ACP (`codewhale serve --acp`) get the same plugin host, under the same `[features]` flags (`extension_host`, `mcp`): reviewed plugin tools (TypeScript and DSH) and the MCP servers configured in Codewhale appear as ACP tool calls and ask through the session's permission setting; Plan stays read-only. When a plugin tool asks the core to run a tool that needs approval (`exec.core`), the editor's permission request is shown on the plugin tool's call and names the nested tool and its input. The ACP server's capabilities say so (`agentCapabilities._meta.codewhale`). Servers an ACP client passes in `mcpServers` and configured shell hooks are not attached. Prepend/global listener ordering, DSH runtime/agent handles, around-execution wrappers, and post-result rewriting are not provided. Native `tool_call_after` remains an observer contract.
557
558 ## Asking the core to run a tool
559
560 A tool can ask the core to run one of the core's tools for it:
561
562 ```ts
563 async execute({ path }, exec) {
564 if (!exec.core) return { error: 'not run under the turn gate' }
565 try {
566 const { content, isError, structured } = await exec.core.call('read', { path })
567 return { content, isError }
568 } catch (error) {
569 // error.name === 'CoreCallError'; error.code is 'refused' | 'denied' |
570 // 'cancelled' | 'unavailable' | 'failed'
571 return { error: error.code, message: error.message }
572 }
573 }
574 ```
575
576 The call is planned and approved exactly like a call the model makes: the
577 allow and deny lists, hooks, Auto-Review, repo law, the worker authority
578 envelope and the approval card all apply. **You never decide any of that.**
579 There is no way to approve, to supply a card's text, an argv, a URL or a
580 ticket. Rust composes the card ("Requested by `extension:<plugin>` from inside
581 its tool `<tool>`") and decides whether one is shown.
582
583 **When `exec.core` exists.** Only when the model called your tool directly and
584 the turn loop is serving its permission gate for that call. It is absent for a
585 command, a timer, activation code, and a tool run from inside
586 `execute_tools` (code mode gives nested tools no gate); the core refuses
587 a `core/call` from any of them. It also ends with the call: when your `execute`
588 returns, fails, times out or is cancelled, or your plugin is disabled, or the
589 host exits, pending core calls are cancelled and a waiting approval card is
590 withdrawn (recorded as cancelled; an answer given afterwards changes nothing).
591 Cancelling your `exec.signal` cancels them too, and `call(name, input, {signal})`
592 can cancel one.
593
594 **Refused outright** (`error.code === 'refused'`, nothing runs, no card): every
595 tool code mode refuses (`execute_tools`, the interpreters, `agent`, `workflow`,
596 `rlm`, `request_user_input`, interactive shells, sandbox escalation, Computer
597 Use consent and scripts, MCP sign-in); any plugin tool, yours included (no
598 recursion); tool search and tool-result retrieval; the memory writer
599 (`remember`) and tools that change what the session may do or schedule work
600 (`request_plugin_install`, goals, automations, `send_later`, starting MCP
601 servers); and **every MCP tool, Computer Use included** (not in v1). Names match
602 case-insensitively and after the core resolves aliases and after any hook
603 rewrites the call.
604
605 **What prompts.** Every call needs approval except a read-only, workspace-local
606 tool from a short list (`read`, `read_file`, `list_dir`, `file_search`,
607 `grep_files`) when nothing else asks for one. Your plugin's own approvals are separate: the user approved your
608 tool, not what it asks the core to do. Approval keys are scoped to your plugin
609 build: a grant the user gave the model for a tool never covers your call of it,
610 and a grant for your call never covers the model's. **Shell and network calls
611 force a prompt**: a session grant is not consulted. Ask and Full Access
612 both ask the user every time; explicit session denials still refuse the call.
613 Under Auto-Review, held plugin calls (whether from `core/call`, broker acts,
614 or plugin host tools) route to the Auto-Review reviewer with the plugin's
615 host-minted plugin identity and cannot bypass review via routine tiers,
616 `auto_review.allow` rules, or typed `allow` rules, while independent typed
617 `deny`/`ask` rules, hook holds, and safety-floor blocks still apply. Never
618 refuses them without opening a card. In Full Access every
619 other call a plugin makes is auto-approved, as it is for the model.
620 `error.code === 'denied'` is the user's "no": do not retry it.
621
622 **Limits**, per invocation: 50 core calls in all, 4 at once, and one approval
623 card at a time; per host, 256 requests in flight. A host that presents invalid
624 tickets in a burst is ended as a protocol violation. Your `tool/call` deadline
625 (120 s) stops while a core call waits on an approval card. The result is the
626 tool's text (`content`) and, when it was JSON, the parsed value
627 (`structured`); a long one is cut with a note, and images are dropped. What your
628 tool asked the core to run is recorded (bounded) in your tool result's
629 `core_calls` metadata, with each call's decision and outcome.
630
631 ## Host services
632
633 A host service is something the core does for a plugin beyond running a
634 core tool: workspace files and commands, the model provider, network requests,
635 settings, the plugin catalog, terminal sessions and remote pairing. Each is
636 served by the core, never by the host process, and each is off until a review
637 grants it. This version of Codewhale offers every service except attachments.
638 The core serves one only during a live tool call by a plugin whose review
639 granted it, so no service is available while a plugin activates.
640
641 **Asking.** Name the services in the manifest. A name outside this list fails
642 validation.
643
644 ```toml
645 [capabilities]
646 host_services = ["network"]
647 ```
648
649 (In a `plugin.json` bundle: `extensions["net.codewhale"].capabilities.host_services`.)
650 For an imported DeepSeek Harness package the importer writes this list from the
651 package's own `inject` declarations. What a bundle asks for is part of its
652 capability hash, so changing the list needs a new review.
653
654 **Granting.** Only a review grants a service, and only when the review showed
655 it: the review lists each service in plain words, the reviewed plugins that
656 already hold it, and any plugin that is turned on without it. Approval is bound
657 to exactly that list. If it changed between showing and approving, the approval
658 is refused and nothing is recorded. A review that did not show the services
659 (`/plugin trust` today) records trust and grants none. A review recorded before
660 this feature holds no grant.
661
662 **Who approved.** Every review records its approver, and every place that shows
663 a plugin's trust shows it:
664
665 | Approver | How it happens | Reach |
666 | --- | --- | --- |
667 | You | the Plugins page, `/plugin trust`, an approval card, or the prompt of `codewhale plugins trust` in your terminal | every project |
668 | The agent, in Full Access or Auto-Review | the agent's plugin tool, bound to the token of the review composed for that call and to the thread, turn and tool call that made it | only the project named in the record |
669 | The agent, from a shell command | `codewhale plugins trust … --yes` run by a process that carries the agent's mark | only the project named in the record |
670 | The command line | `codewhale plugins trust … --yes` without the mark: no review was shown there, so it grants no service | every project |
671
672 The agent's mark is `CODEWHALE_AGENT_PROJECT`, which Codewhale sets to the
673 session's project on every command the agent runs (shell, persistent terminal,
674 verifier and test runs, the Python kernel, MCP servers it starts), whatever the sandbox or
675 permission mode; under Auto-Review, shell and verifier runs also set
676 `CODEWHALE_AGENT_POSTURE=auto_review` together with `CODEWHALE_AGENT_THREAD_ID`,
677 `CODEWHALE_AGENT_TURN_ID`, and `CODEWHALE_AGENT_TOOL_CALL_ID` so `plugins trust`
678 and `plugins enable` record the agent in Auto-Review rather than `CommandLine`.
679 Hooks, MCP servers from your configuration and the terminal
680 app's `/plugin trust` carry no mark. With it, the command records the agent, even for a prompt
681 answered through a terminal, and trusts only a plugin installed from a folder
682 inside that project (the bundle's `.installed-from` record). It is a label, not
683 a lock: in Full Access the agent could remove it, and the record then says "the
684 command line". The `--review-token` that the command
685 takes is the bundle review token (`<content-hash>.<capability-hash>`), not the
686 host-service review token: an unmarked trust passes no host-service token, and
687 a marked one passes the token of the review composed for the agent.
688 A plugin the agent approved is active only in the project its record names,
689 and runs in an agent host process of its own for that project, apart from the
690 plugins you reviewed. When you review it, it moves into the reviewed host process
691 and its data folder moves with it; if a data folder for it is already there, the
692 move is refused and the plugin stays off until you resolve it. Your own review
693 replaces the agent's record. Who
694 turned a plugin on is recorded the same way, separately from who approved it.
695 The agent never approves a built-in plugin, never replaces a review that holds
696 for every project (yours, the command line's, or one from an earlier version)
697 or one the agent of another project made, and never approves a project plugin
698 whose folder resolves outside the project.
699 It turns on only a plugin whose record it made for this project. Everything
700 else is left to you.
701
702 **One process, one rule.** Plugins in the same host process cannot be
703 isolated from each other inside it. Plugins you reviewed share one host process;
704 plugins the agent approved share a separate host process per project. A service
705 is therefore given to a tool call only while every plugin loaded in that cohort's
706 process holds the same grant. The rule, and the list of plugins a review says a
707 service is shared with, cover only plugins in the same cohort: the plugins you
708 reviewed are counted together, and plugins in an agent cohort are counted only
709 within their project's host. If one
710 does not, the service is off for all of them, and the host diagnostics name the
711 plugin without it. Code that was loaded cannot be unloaded, so after a
712 plugin is turned off, changed or fails, every service stays off until the
713 host process has restarted, which Codewhale does by itself once the host is
714 idle.
715
716 **Using a service.** A grant says a plugin may ask; the session's permission
717 mode decides each act, like any other action the agent takes. An act that
718 changes something or reaches outside the session is asked through the normal
719 approval card in Ask and Accept Edits, judged by the reviewer model in
720 Auto-Review, run in Full Access, denied in Never, and refused in Plan. In a
721 sub-agent such an act is never delegated with the sub-agent's file writes: it
722 needs that same decision, and the sub-agent's shell permission, plus write
723 permission for a change or network permission for a reach. A read runs without
724 a card. Acts a service makes through a core tool (a file read, a terminal
725 command) pass that tool's own gate instead. When the tool call ends, every act,
726 allowed or not, is recorded in the result's `core_calls` metadata under
727 `broker_acts` (the first 50, with the total). A tool call that fails after
728 making an act returns a failed result with the error text and that record. Acts
729 count toward the tool call's one limit of 50 nested calls, shared with its
730 `core/call`s, and at most four wait on the gate at once; a further act waits
731 for a slot. The `plugins` service is never granted by a review: only
732 Codewhale's own built-in creator module holds it, and only for the session's
733 own agent, not a sub-agent.
734
735 **What a refused call receives.** `REFUSED` with `data.dsh_refusal`:
736 `not_granted` (the same answer whether your own review lacks the service or
737 another plugin's does), `limit` (this tool call used up its calls to that
738 service), `ticket_refused`, `cancelled`, or the service's own typed refusal.
739 Turning a plugin off, revoking it or reviewing it again withdraws its grant
740 at once: a call already running is dropped and its answer withheld.
741
742 Known limits: a grant is all of what the review showed or none of it; there is
743 no per-service choice inside one review. The review record is protected by its
744 private directory, not by a signature: another program running as you, outside
745 the sandbox, can write it, as it can write trust itself. A change made by
746 another Codewhale process reaches a running call within about 50 ms; a side
747 effect a service completes inside that window is not undone.
748
749 ## Lifecycle, diagnostics and restarts
750
751 Use `/plugin show <name>` for that plugin's owner state, live tool names and
752 up to 20 recent retained diagnostic messages. The host retains a bounded 64-entry
753 shared diagnostic ring; this view is not a persistent per-plugin log. Warnings,
754 errors, activation/refusal/fault messages and teardown outcomes are attributed
755 to the plugin when known. Display text is escaped. `/plugin list` includes
756 overall host health and bounded diagnostics.
757
758 Do not block the event loop. Heartbeats mark an unanswered host Unresponsive
759 after 3 seconds and kill it after 10 seconds. Unexpected exits restart with a
760 short backoff; the third crash within 5 minutes stops automatic recovery.
761 Opening another engine does not reset that budget. Explicit plugin changes or
762 reload retry deliberately. Launch failures also allow a newly attached engine
763 to retry after a one-minute cooldown.
764
765 Recovery verifies current attachments and persisted trust again, then creates
766 fresh owner tokens and tool handles. Outstanding calls fail and are never
767 replayed; failed/faulted receipts remain suppressed until explicit retry or
768 changed authority. Two dirty teardowns within 10 minutes request maintenance
769 when active calls finish. This restart preserves the unexpected-crash budget.
770 Dispose within 2 seconds and avoid leaving background work behind.
771
772 ## Sandbox
773
774 Trust is not a complete security boundary. Native plugins reviewed by a person
775 share one process and data-access cohort, while agent-approved plugins run in their
776 own host process per project with data isolated under `data-agent/<digest>`.
777 Plugins within the same host process can interfere with each other; owner labels and
778 JavaScript method locks do not isolate mutually untrusted plugins in the same process.
779
780 Native hosts use a positive filesystem-read policy on macOS Seatbelt and
781 Linux bubblewrap (`/usr/bin/bwrap`). Grants cover the selected runtime and
782 required system files, the host bundle, Core-managed reviewed snapshot stores,
783 and the Native data/private temporary directories. Ordinary workspace files,
784 including project `.env` files, are outside those grants. Child processes
785 inherit the same boundary. Direct network access is denied; writes stay in
786 the Native data and private temporary directories. The general shell profile's
787 Cargo, npm and Darwin cache write grants do not apply to this Native profile.
788
789 Snapshot-store grants include other reviewed snapshots in the shared Native
790 cohort, not just the currently selected entry. They do not grant repository
791 access. A plugin that directly runs `git` over the user's project therefore
792 needs a separately scoped operation bridge before it can work in this profile.
793
794 Native plugins require a verified OS wrapper at each launch. On Linux,
795 missing bwrap or a failed namespace probe refuses Native activation and reports
796 the concrete error. Windows uses the existing LPAC filesystem/network wrapper
797 and refuses Native activation when that wrapper cannot be established. Source
798 support is not evidence of platform or bundled-artifact qualification. The pinned Builtin tier retains
799 an explicitly diagnosed unsandboxed exception; every effect still requires
800 Rust operation tickets. That exception does not qualify Native plugins or
801 the mandatory-host/default-runtime cutover. Planning creates the sibling
802 Builtin data directory before masking it for Native launch. Review the
803 [current design limits](design/TS_EXTENSION_HOST.md) before enabling
804 third-party code.
805
806 ## Limits
807
808 The host process has a 1 GiB memory cap. On Linux it is `RLIMIT_DATA` (or a
809 lower hard limit Codewhale itself inherited) and on Windows the Job Object's
810 per-process limit, so an allocation past it fails; both also apply to each
811 process a plugin starts. Those two have been tested with a Node host only.
812 On macOS the Bun host applies a jetsam limit to itself before any plugin
813 loads, and the kernel kills it past the cap; processes it starts are not
814 covered. A Node host on macOS has no kernel limit: Codewhale checks its
815 resident size at each 3-second heartbeat and kills it past the cap. Under Node
816 the JavaScript heap is also limited to 256 MiB. The host has a
817 32 MiB frame limit, 256 in-flight request
818 limit (plus a reserved heartbeat), 128 tools per owner and 1024 per host, and
819 64 commands per owner and 256 per host. One tool call may make 50 core tool
820 calls in all, counting those a host service makes for it, and 50 calls to each
821 host service. Eight invalid tickets in a minute end the host process for every
822 plugin in it; a ticket whose tool call ended in the last 10 seconds is
823 refused without counting. Tool
824 descriptions are at most 4 KiB and schemas 64 KiB. Tool calls have a 120-second
825 deadline and commands a 30-second one. The feature stays Experimental and off by default; local fixture
826 tests do not establish sandbox parity, provider behavior or release readiness.
827
827 lines MARKDOWN