返回 CodeWhale
CONFIGURATION.md
根目录 / docs / CONFIGURATION.md
1 # Configuration
2
3 codewhale reads configuration from a TOML file plus environment variables.
4 At process startup it may also load literal built-in-provider credentials from
5 a workspace-local `.env` file. Use the tracked `.env.example` as the template;
6 copy it to `.env`, then add only credential values.
7
8 A workspace is not configuration authority. Codewhale therefore ignores
9 config/profile/home paths, provider/model/base-URL routing, MCP/plugin state,
10 approval/sandbox/shell posture, executable paths, runtime settings, and every
11 other non-credential `.env` entry. Variable expansion is rejected so a
12 repository cannot substitute an ambient secret into a credential value. Use
13 `config.toml`, CLI flags, or values exported by the launching shell for those
14 explicit control-plane settings. `.env` is read from a stable regular-file
15 handle, is capped at 1 MiB, and symbolic links, reparse points, and multiply
16 linked files are rejected.
17
18 ## Reading and checking configuration from the CLI
19
20 `codewhale config get <key>` reads scalar keys, whole tables such as `tools`,
21 and nested paths such as `tools.user_input_timeout_seconds`. Displayed tables
22 and nested values apply the same recursive credential redaction as `config dump`.
23
24 `config set` supports its named scalar keys and the provider, route, and
25 notification commands. It refuses a key that nothing reads and suggests the
26 nearest real key (`config set calm_mod on` names `calm_mode`). A settings.toml
27 key such as `calm_mode` or `tool_collapse` is validated and written to the
28 selected profile's settings file. `config get` reads it back from that file
29 and `config unset` removes the preference there. Use `config edit` to remove
30 an obsolete copy from config.toml. Settings keys have no project
31 scope, so `--project` refuses them. A config.toml key is checked against the
32 type its reader expects and stored as a TOML boolean or number where the
33 reader needs one (`yolo = true`, `max_subagents = 4`); `reasoning_effort`
34 accepts the same aliases as `/effort` (#6563). Other dotted writes fail before
35 modifying the file and name the TOML table to edit. For example, set a tools
36 timeout in the file as:
37
38 ```toml
39 [tools]
40 user_input_timeout_seconds = 0
41 ```
42
43 `codewhale config doctor` checks credential presence and endpoint shape, and
44 warns about each config.toml root key that nothing reads: a settings.toml key
45 left in config.toml is named as misplaced, and any other unread key gets a
46 did-you-mean. Keys read by any runtime reader are not reported. The warnings do
47 not fail the check, and a clean result does not validate every runtime setting's
48 value (#6083, #6563).
49
50 ## Usage and execution statistics
51
52 `codewhale stats` is an alias of `codewhale metrics`; both use the same local,
53 read-only backend. Use `--json` for the structured `stats` report. For example:
54
55 ```sh
56 codewhale stats --days 7 --models 10 --tools 20 --roles 10
57 codewhale metrics --project /path/to/workspace --json
58 ```
59
60 `--days N` accepts a positive number of days and conflicts with `--since`.
61 `--since 24h` and the existing duration syntax remain available. `--models N`,
62 `--tools N` and `--roles N` select the top positive N rows by known tokens,
63 identified tool executions and recorded Fleet tasks respectively. These limits
64 only shorten the display; they do not remove stored receipts.
65
66 The report separates saved-document and Runtime views, frozen native-source
67 money and token subtotals by actual model, retained tool-result history
68 estimates and outcomes, completed compaction observations, and recorded Fleet
69 roles. USD and CNY stay separate. A cumulative correction replaces its proven
70 predecessor; copied Session/Runtime receipts and inherited Runtime fork rows
71 are not added as new provider work. Conflicting source versions are shown
72 separately and excluded from the subtotal. Saved legacy display totals remain
73 visible as document projections without being charged again globally.
74 Each model line in the text report also shows cache read, cache write and
75 reasoning tokens, and the cache hit rate over the sources that report cache
76 usage; a figure no source reports reads `unknown`.
77
78 Coverage is explicit. A missing quote, usage receipt, tool outcome, output
79 shape or recovery link is unknown, not zero. New terminal sessions save an
80 explicit success or failure flag on tool results. A missing or invalid flag
81 leaves the outcome unknown unless a Runtime receipt identifies the same
82 execution and records its outcome. A failed result is assigned a best-effort
83 failure category anchored to its failure line, or `unknown` when no known
84 pattern matches. The per-tool failure rate is computed over calls with a
85 known outcome only. Empty scalar usage from older transport records cannot prove
86 a reported zero. Token counts describe known reported data; tool history tokens
87 are estimates of retained text, not bytes proven to have been replayed on a
88 provider request. A Fleet role's usage and cost come from the saved session
89 its worker's receipt links and are shown as `usage from N of M tasks`. Each
90 source counts once, as the revision the per-model rows select; a session named
91 by two tasks stays with the first task visited. Tasks without a linked session
92 add nothing, and a currency without an authoritative price for every source
93 prints `unknown`. Latest prepared-request
94 components and source-linked compaction economics are unavailable where they
95 were not captured. The report does not infer provider invoices or prove
96 complete historical coverage.
97
98 `--project WORKSPACE` filters current saved/thread/Fleet views. Original source
99 workspace is not yet captured, so native money and model subtotals are
100 unavailable for that filter, and Fleet role usage and cost stay unset; mutable
101 current metadata is not used to assign a charge. Older receipt projections without reliable workspace scope are also
102 unavailable under this filter. Without it, those legacy receipt views remain
103 separate from native subtotals and may overlap one another.
104
105 Inspection uses the existing session-size bound (16 MiB per record/frame and
106 for each retained query index). Date and workspace filters are applied before
107 parsing session bodies where possible. Unreadable, linked, oversized or
108 incomplete records create visible gaps; hitting the 16 MiB retained index cap
109 stops admitting further records without evicting collected evidence and returns
110 a labelled partial report (`inspection_cap_reached: true`). Use a narrower time
111 window or `--project` filter where possible. Reading statistics does not create
112 a store, repair history, refresh pricing, start a model call or retire
113 accounting receipts. Existing state-root overrides remain the read boundary.
114
115 `/cache calls [count]` shows recent retained native source receipts in the TUI;
116 it defaults to 10 and displays at most 50. A source correction updates its row.
117 The view keeps frozen USD/CNY estimates and known subtotals separate from missing
118 usage or prices; absent or contradictory cache classes show unknown. The header
119 counts retained sources, not physical requests or complete historical calls.
120 The command does not issue a model request or remove accounting receipts.
121
122 Published prices are frozen for DeepSeek's root, `/v1`, `/beta` and Anthropic
123 endpoint variants, and for other providers' default endpoints. Each quote stays
124 bound to the exact endpoint, identity, model and dispatch time when saved or replayed.
125 Operator endpoint overrides do not become published pricing authorities, and
126 subscription or token-plan routes remain outside money coverage. Signed cloud
127 facts keep their separate route-scoping rules. Recognition as an official
128 credential endpoint alone does not authorize sharing prices across regions or plans.
129
130 Missing request outcomes, omitted provider usage, unverified legacy usage and
131 usage corrections have distinct cost reasons. Known limitation: saved receipts
132 without a frozen price are not repriced from today's catalog; their complete
133 cost remains unknown even after updating the binary.
134
135 ## Constitution, project instructions, and repo authority
136
137 Codewhale has several instruction surfaces. They are deliberately separate so a
138 personal constitution, repo policy, project instructions, and runtime security
139 controls do not blur together.
140
141 - **Bundled global Constitution** — the compiled base law in the binary. It is
142 the default floor for every session.
143 - **User-global constitution** — the normal guided setup output. Manage it with
144 `/constitution` or `/setup`; Codewhale stores structured data at
145 `$CODEWHALE_HOME/constitution.json` (default `~/.codewhale/constitution.json`)
146 and renders it into a separate `<codewhale_user_constitution>` prose block.
147 This can express preferences and stop conditions, but it does not change
148 runtime approval policy, sandbox, shell, network, trust, or MCP permissions.
149 - **Repo-local constitution** — optional project policy in
150 `.codewhale/constitution.json`, described below.
151 - **`AGENTS.md`** — cross-agent **project instructions** (prose). This is the
152 canonical file for "how should an agent work in this repo." Run `/init` to
153 scaffold one. Instruction files written for other tools (`CLAUDE.md`,
154 `.claude/instructions.md`, `.cursorrules`, `.github/copilot-instructions.md`
155 and similar) are read only when you opt in with the top-level
156 `project_instruction_imports` key, for example `["claude"]`, `["cursor"]` or
157 `["all"]` (see `config.example.toml`); Codewhale warns when it finds one it
158 did not load.
159
160 Codewhale reads one instruction file per directory, from the repository
161 root down to the workspace, and puts your global instruction file (such as
162 `~/.codewhale/AGENTS.md`) in front of them. The nearest scope reads last
163 and wins: the workspace file overrides its parents, and project files
164 override the global file. Global and project instructions are budgeted
165 separately in estimated tokens (see [Instruction budget](#instruction-budget-instruction_budget-6526)
166 below): a scope over its budget drops whole files from the broadest end
167 first, and a single file larger than the remaining budget keeps its head
168 with a marker that names the bytes and tokens dropped. A file keeps at most
169 its first 100 KiB, and a file larger than `file_max_bytes` (8 MiB, lowerable
170 only) is skipped with a notice. Every loss — trimmed, skipped, or refused —
171 reaches the model and `/context report`.
172 - **Memory and handoffs** — recalled state. Useful, but lower authority than
173 constitutions and project instructions.
174
175 ### Managing the user-global constitution (`/setup` and `/constitution`)
176
177 The bundled **working agreement** is the safe default and no longer adds a
178 required first-run screen. Customize it later through `/constitution` or the
179 progressive `/setup` guide. Provider/model readiness, workspace trust, and
180 runtime posture stay separate from this guidance.
181
182 On the **Working agreement** (constitution) step:
183
184 - **`1`–`6`** tune the guided draft. **`G`** previews it, and **`G`** again
185 ratifies and saves a fresh structured `constitution.json`.
186 - **`A`** (shown only when a provider is configured) asks your first configured
187 model to draft the constitution. Drafting is **not** saving: the draft is
188 rendered through the same preview and you still press **`G`** to ratify
189 before anything persists.
190 - **`K`** keeps your existing loaded constitution unchanged (shown only when a
191 valid file is already present).
192 - **`U`** (or `/constitution bundled`) records the bundled/default law.
193
194 `/constitution` (alias `/law`) is the primary management surface once you are
195 set up. Subcommands: `status` (the default), `preview`, `review`, `repo` (the
196 repo-local law block), `explain`, `base`, `suggestions`, `ratify <id>`,
197 `migrate`, `rollback`, `edit`/`guided`, `repair`, `posture`, and `bundled`.
198 Managing the constitution never changes runtime approval, sandbox,
199 shell, network, trust, default mode, or MCP authority — those stay in runtime
200 posture/config.
201
202 Each repo can carry two distinct, complementary files:
203
204 - **`AGENTS.md`** — ordinary project working instructions.
205 - **`.codewhale/constitution.json`** — Codewhale-specific **repo authority /
206 prioritization policy**: when local sources conflict, which should Codewhale
207 trust first, and what to verify before claiming a task is done. `.codewhale/`
208 lives inside the repo (like `.github/`). Example:
209
210 ```json
211 {
212 "schema_version": 1,
213 "authority": [
214 "current user request",
215 "live code and tests",
216 "GitHub issue/PR details",
217 "AGENTS.md",
218 "memory",
219 "old handoffs"
220 ],
221 "protected_invariants": [
222 "do not break old-session transcript replay"
223 ],
224 "branch_policy": "PRs target the integration branch, not main",
225 "verification_policy": {
226 "before_claiming_done": ["run focused tests", "read changed files back"]
227 },
228 "escalate_when": [
229 "a destructive action was not explicitly authorized"
230 ]
231 }
232 ```
233
234 All fields are optional. When present, the file is rendered into the system
235 prompt as concise prose in a higher-authority block. Legacy `WHALE.md` files
236 are ignored and reported as migration-only diagnostics.
237
238 Each `protected_invariants` entry may be either a plain string (advisory
239 prose, the historical shape) or an object carrying path globs, which is
240 additionally **mechanically enforced** in the tool gate. See
241 [Enforced repo-law invariants](#enforced-repo-law-invariants) below.
242
243 This is the **repo-local law** layer. When guidance conflicts, the
244 **Whose word wins** section of the effective base constitution owns the
245 ordering; the bundled source is
246 [`BASE_PROMPT`](../crates/engine/src/prompts/text.rs). Use `/constitution base`
247 to inspect the effective base, including any opted-in expert override.
248 The order in which these files are described or assembled is not an
249 authority ranking. Runtime policy (permissions, sandbox and cost limits
250 enforced in code) is separate from prompt guidance; editing a constitution
251 does not grant permissions.
252
253 > **`WHALE.md` is deprecated.** It overlapped confusingly with `AGENTS.md`.
254 > Codewhale no longer reads `WHALE.md` as project or global context. If one is
255 > present, setup/context diagnostics report it as ignored so you can migrate it.
256 > Move ordinary instructions to `AGENTS.md` and Codewhale-specific authority
257 > policy to `.codewhale/constitution.json`. Personal standing guidance belongs
258 > in `/constitution` / `$CODEWHALE_HOME/constitution.json`. (The global
259 > Codewhale Constitution shipped in the model prompt is a separate thing and is
260 > unaffected.)
261
262 ### Enforced repo-law invariants
263
264 By default a `protected_invariants` entry is advisory prose: it is rendered into
265 the prompt as guidance the agent should honor, but nothing stops a write. An
266 entry written as an **object with `paths`** is different — it compiles into a
267 mechanical write hold that the engine's tool gate evaluates before the write
268 runs. The law becomes mechanism, not just a request.
269
270 An enforced entry has this shape:
271
272 ```json
273 {
274 "schema_version": 1,
275 "protected_invariants": [
276 "Keep DeepSeek support first-class.",
277 {
278 "text": "The wire format is frozen; protocol changes need a human.",
279 "paths": ["crates/protocol/**"],
280 "action": "block"
281 },
282 {
283 "text": "Release notes need human review.",
284 "paths": ["CHANGELOG.md"],
285 "action": "ask"
286 }
287 ]
288 }
289 ```
290
291 - `text` — required. The reason surfaced on the hold. An empty `text` is skipped.
292 - `paths` — workspace-relative globs (globset syntax, e.g. `crates/protocol/**`,
293 `**/secrets.toml`, `CHANGELOG.md`). An object with no usable `paths` stays
294 advisory-only despite the object shape.
295 - `action` — optional, defaults to `ask`. `ask` force-prompts in Ask and
296 Auto-Review; in Full Access it denies the protected write without opening a
297 modal. `block` **denies the write outright** in every posture for the covered
298 file write tools (`write_file`, `edit_file`, `apply_patch`, and `fim_edit`).
299
300 Semantics:
301
302 - **Tighten-only.** The schema has no allow/widen shape, so law can only *add*
303 holds — a crafted constitution can never grant authority or weaken a gate
304 above it.
305 - **Not bypassable by mode.** Like the built-in safety floor, an `ask` hold
306 force-prompts in Ask and Auto-Review. Full Access never opens approval
307 modals, so the same hold fails closed as a hard block; `block` always denies.
308 Mode cannot turn a hold off.
309 - **Repo-local only.** Only the repo's `.codewhale/constitution.json`
310 participates. The user-global constitution stays advisory prose and never
311 reaches this mechanism.
312 - **Fails safe.** A missing file, parse error, or invalid glob degrades to
313 fewer or zero rules — never a hold on unprotected paths and never a poisoned
314 gate. Across matches the strongest action wins, so `block` outranks `ask`.
315 - **Leaves a receipt.** Every hold emits a `tool.repo_law_decision` tool-audit
316 event naming the invariant, the matched path, and the source file; the
317 approval/denial reason names the invariant too.
318
319 **Coverage is deliberately limited.** Holds are evaluated only for the write
320 tools `write_file`, `edit_file`, `apply_patch`, and `fim_edit`, and only
321 against the filesystem targets named in their inputs (`path`/`target`/
322 `destination`/`file_path`, `changes[].path`, and unified-diff /
323 `apply_patch`-envelope headers). A shell command that writes a protected path is
324 **not** held by repo law, and neither are MCP tools. What holds a shell write
325 depends on the posture:
326
327 - In Ask, Accept Edits, and Auto-Review, a shell command goes through that
328 posture's approval or review as a whole, not by protected path, and through
329 the active OS sandbox.
330 - In Never, a shell command that is not read-only is blocked unless a typed
331 allow rule clears it. A `read-only` sandbox blocks shell writes.
332 - In Full Access with no narrower `sandbox_mode` (its default is
333 `danger-full-access`), neither repo law nor the OS sandbox holds a shell
334 write. Only deny rules, blocking hooks, a configured `sandbox_mode` and
335 shell admission (`allow_shell`, per-command tool lists) can stop it.
336
337 ### Expert full base-prompt override (#3638)
338
339 The global Constitution (the base system prompt, normally compiled in from
340 `crates/engine/src/prompts/text.rs` as `BASE_PROMPT`) can be replaced per-user
341 without rebuilding. This is
342 an expert escape hatch, not the normal `/constitution` guided setup output.
343 Because this is a prompt trust boundary, it takes **two deliberate steps** — a
344 file alone is not enough:
345
346 1. Drop the replacement at `~/.codewhale/prompts/constitution.md` (under
347 `$CODEWHALE_HOME` when set).
348 2. Set the explicit opt-in flag `CODEWHALE_ALLOW_BASE_PROMPT_OVERRIDE=1`
349 (`true`/`on`/`yes` also accepted).
350
351 If the file exists but the flag is unset, the override is **ignored** (with a
352 log line pointing to the flag) and the bundled Constitution stays in place.
353 This is intended for repurposing the TUI beyond software engineering — e.g.
354 long-form writing or document review — where the engineering-oriented base
355 prompt is a poor fit. It is loaded once at startup; a **missing or empty file
356 is a no-op**, so existing installs keep the bundled prompt.
357
358 Scope is deliberately narrow: only the byte-stable **base prompt segment** is
359 overridable. Mode deltas, the approval policy, the tool taxonomy, Context
360 Management, and the Compaction Relay are still owned by Codewhale's runtime
361 assembly, so an override **cannot remove safety-relevant guidance** (sandbox,
362 approvals) — it only swaps the task/voice framing. To customize ordinary
363 personal behavior, prefer `/constitution`; to customize per-repo behavior,
364 prefer `AGENTS.md` + `.codewhale/constitution.json` above.
365
366 ## Where It Looks
367
368 Default config path:
369
370 - `~/.codewhale/config.toml`
371 - Legacy fallback: `~/.deepseek/config.toml`
372
373 Overrides:
374
375 - CLI: `codewhale --config /path/to/config.toml`
376 - Env: `CODEWHALE_CONFIG_PATH=/path/to/config.toml`
377 - Legacy env alias: `DEEPSEEK_CONFIG_PATH=/path/to/config.toml`
378
379 If both are set, `--config` wins. Environment variable overrides are applied after the file is loaded.
380
381 The selected config also selects the saved terminal preferences used by the CLI
382 and the interactive TUI. A file named `config.toml` uses `settings.toml` in the
383 same directory. A custom filename gets its own companion, for example
384 `demo.toml` uses `demo.toml.settings.toml`. Home and legacy home config paths
385 retain the usual home settings fallback. A workspace `.codewhale/config.toml`
386 remains project-scoped. Terminal preferences edited in a project use the
387 user profile. Credentials and session history keep their usual locations.
388
389 `codewhale --config demo.toml config unset calm_mode` removes the saved
390 preference. `config get calm_mode --json` shows its configured and effective
391 values, including environment overrides.
392
393 ### TUI editability audit
394
395 Inside the TUI, run `/config audit` to see which documented keys can be changed
396 from the current session, which ones can also be persisted, and which ones stay
397 file-only or restart-only. The audit includes current values for the high-impact
398 runtime controls such as `approval_policy`, `allow_shell`,
399 `stream_chunk_timeout_secs`, `base_url`, `mcp_config_path`, and the
400 `[subagents]` concurrency/depth/timeout keys.
401
402 Use the command's "Command / reason" column as the source of truth before
403 editing by hand. For example, `/config approval_mode on-request --save` writes
404 top-level `approval_policy = "on-request"`, while provider base URLs are saved
405 but still require restarting the model client.
406
407 ### User workspace entries
408
409 Interactive Agent sessions expose shell tools by default with approval gating
410 unless you explicitly disable them. For a shell opt-in that should live in the
411 user's global config for noninteractive or durable-task profiles rather than in
412 the repository, add a workspace-scoped entry:
413
414 ```toml
415 [workspace.'/absolute/path/to/project']
416 allow_shell = true
417 ```
418
419 The entry applies only when the launched workspace path matches the table key.
420 The legacy `[projects."/absolute/path/to/project"]` table is also accepted for
421 this user-owned override.
422
423 In interactive mode, the per-project overlay
424 `<workspace>/.codewhale/config.toml` is applied after this user entry. A
425 project-level `allow_shell = false` can still tighten the session; project-level
426 `allow_shell = true` is ignored.
427
428 ### Per-project overlay (#485)
429
430 When the TUI starts in a workspace that contains a regular-file
431 `<workspace>/.codewhale/config.toml`, the safe values declared in that file are
432 merged on top of the global config. Legacy
433 `<workspace>/.deepseek/config.toml` files are still read when the Codewhale path
434 is absent. Symlinked project config files are rejected. This lets a repo suggest
435 a model or tighten local safety posture without touching the user's
436 `~/.codewhale/config.toml`. Pass `--no-project-config` to skip the overlay for
437 one launch.
438
439 Supported keys in the project overlay (top-level fields only):
440
441 | Key | Effect |
442 |---|---|
443 | `model` | override `default_text_model`; `codewhale model resolve` reports it as `project config model` |
444 | `reasoning_effort` | force `"high"` / `"max"` for a complex repo |
445 | `approval_policy` | only values that tighten the user's current permission posture |
446 | `sandbox_mode` | only values that tighten the user's current sandbox posture |
447 | `max_subagents` | clamp sub-agent concurrency for a constrained repo (clamped to 1..=128) |
448 | `allow_shell` | `false` can disable shell access; `true` is ignored |
449
450 In `/model`, Enter switches the model and thinking level for this session
451 only. Shift+D also saves them as the startup default in
452 `~/.codewhale/config.toml` and `settings.toml`. Shift+D on the model this
453 project pins saves nothing, so one repo's choice never becomes the default in
454 every other workspace; saving a different model notes that the project still
455 pins its own model here.
456
457 The overlay is intentionally narrow — it covers the fields a repo
458 maintainer is most likely to want to standardize across contributors.
459 Credential, endpoint, provider-selection, MCP config, hooks, skills,
460 retry, hotbar bindings, and `instructions = [...]` settings stay user-global.
461 If a repo-local config declares `api_key`, `base_url`, `providers`, `provider`,
462 `mcp_config_path`, `hotbar`, `allow_shell = true`, or `instructions`,
463 Codewhale ignores that key and keeps the user's global setting.
464
465 The consolidated `codewhale` runtime uses `~/.codewhale/config.toml` for
466 provider and model settings. `codewhale auth set --provider deepseek` saves
467 the key in the local secret store (a private file under `~/.codewhale/secrets/`
468 by default; the OS keychain is an explicit option), rather than writing it
469 into that config file. Legacy `~/.deepseek/config.toml` is migrated on first
470 launch when needed. `codewhale --model deepseek-v4-flash` is forwarded to the
471 TUI as `CODEWHALE_MODEL`. The dispatcher no longer writes `DEEPSEEK_*` twins;
472 a value you set yourself remains a legacy alias when its `CODEWHALE_*`
473 equivalent is unset.
474
475 ### Account provider keys
476
477 `/connect` offers Connect on this computer, and Continue with Codewhale once
478 accounts open (see [Account](ACCOUNT.md)). The
479 account path signs in and lists usable model connections reported by the
480 account service. When none are ready, it offers retry or on-computer setup.
481 Sign-in alone does not supply model access or change the selected model.
482 Local provider keys and local models never need an account; use `/provider`
483 or `codewhale auth set --provider <provider>` to manage them.
484
485 For an account that supports saved provider keys, these commands manage them:
486
487 ```bash
488 codewhale account keys list # configured status, never secret values
489 codewhale account keys remove deepseek # remove the account's saved key
490 ```
491
492 Login never uploads local keys, and removing an account key does not change
493 local copies or revoke the key at the provider.
494
495 The account session is separate from provider keys. Starting a new sign-in is
496 closed until accounts open; once they do, `/login` signs in inside
497 the TUI and `codewhale login` does so from the shell. `codewhale account status`
498 inspects it. `/logout`, `codewhale logout` and `codewhale account logout` remove
499 only the account session for the selected `--profile`. The explicit
500 `codewhale logout --all` action also clears saved model credentials.
501 Account sessions use the private `0600`
502 Codewhale secrets file, scoped to the profile and account API origin; they do
503 not use the OS keychain. The older `codewhale cloud ...` spelling remains an
504 alias for account commands.
505
506 ### Portable config bundles
507
508 `codewhale config export --portable [--project] [--out FILE]` writes a
509 portable, secret-free bundle of your configuration: sorted TOML with
510 credential and machine-specific keys (API keys, base URLs, socket paths)
511 dropped, never a redacted placeholder in their place. Without `--out` the
512 bundle goes to stdout. Typed tables, arrays, numbers, booleans, and datetimes
513 remain typed. Machine-bound authority is deliberately non-portable: project
514 trust overlays, credential readers, auto-running hooks, executable LSP
515 definitions, and local path bindings are omitted rather than copied to a new
516 host. So is trust posture (`yolo`, `allow_shell`, `approval_policy`,
517 `sandbox_mode`, `sandbox_network_access`, and the sandbox read-denylist
518 paths) and local endpoints or executables (`[lifecycle_outbox]`,
519 `[extension_host]`, `[control_socket]`). URLs that carry a credential —
520 userinfo, a token-named query parameter, or a Slack/Discord/Teams webhook
521 path — are treated as credentials.
522
523 `codewhale config import <FILE|HTTPS_URL|-> [--dry-run] [--yes] [--project]`
524 applies a bundle. The envelope is strict (`schema_version = 1`, kind
525 `codewhale.portable-config`; unknown fields fail). Import prints a
526 deterministic plan — added / changed / skipped / conflicting / rejected —
527 then asks for consent unless `--yes` is given; headless use requires it.
528 Credential-shaped entries are rejected by key name and by value shape;
529 rejections name the field, never a value. Remote bundles come from HTTPS
530 only (loopback http excepted) with a 5 MiB cap. The first request and every
531 redirect honor the `[network]` policy and refuse loopback, private, link-local
532 and cloud-metadata destinations, including a host name that resolves to one;
533 the only exceptions are a loopback URL you type yourself and a `localhost` name
534 or private IP address you listed in `network.allow` (never on a redirect to a
535 different host). When `HTTPS_PROXY` (or `HTTP_PROXY`, unless matched by
536 `NO_PROXY`) is set, non-local hops delegate resolution to the proxy and skip
537 the local DNS resolution check. Application backs up the
538 target document to `<config>.bundle-backup-<timestamp>-<random>`, rolls back on any
539 failure, and re-importing an applied bundle changes nothing.
540
541 Import also rejects the non-portable authority classes omitted by export,
542 including nested/camel/dotted credential keys and cookie headers. This keeps a
543 hand-authored or remote bundle from reintroducing machine trust, local
544 credential access, or automatically executable commands that a local export
545 would refuse to carry. Structured tables are deep-merged: a portable model or
546 preference update does not erase target-local provider credentials, endpoints,
547 hooks, or executable definitions that were deliberately omitted from the
548 bundle. Arrays and scalar values still replace the corresponding portable
549 value.
550
551 Sections map to scope: `[project]` entries land only in the workspace
552 document (`--project`, which must target an actual workspace config),
553 `[global]` only in the user-global one; `preferences`, `profiles`, and
554 `plugins` apply at either scope. A global bundle operation refuses a workspace
555 document just as a project operation refuses the user-global document.
556
557 ### Credential read precedence (#5197)
558
559 Credential reads are **folder-independent by default**: every layer below is
560 user-global or process-scoped, so a key saved in one repo resolves identically
561 in every other repo. Repo-local config never carries credential material — the
562 project overlay above reads only its allowlisted keys and ignores `api_key`,
563 and a credential write aimed at a workspace-scoped config is rescoped to the
564 user-global `~/.codewhale/config.toml` (#5045, #5193).
565
566 For the active provider, the runtime resolves the API key in this exact order
567 (first match wins):
568
569 1. **Route-specific auth contract.** Routes whose `auth_mode` disables API
570 keys stop here with no credential. OAuth routes use their explicitly
571 granted token: the official `openai-codex` plan route accepts only
572 Codewhale-owned credentials from `codewhale auth chatgpt`, bound to its
573 issued registration and verified account. Imported Codex CLI and process
574 tokens cannot authorize this route;
575 `[providers.xai] auth_mode = "oauth"` reads Codewhale's own xAI
576 device-login store (or a consent-granted Grok CLI file).
577 2. **Explicit CLI key.** `--api-key` forwarded with its source marker wins
578 over every saved slot.
579 3. **Config file `api_key`.** The `[providers.<name>] api_key` table slot for
580 the active provider. `deepseek-CN` also reads `[providers.deepseek]`. An
581 older top-level `api_key` is read as `[providers.deepseek] api_key` (see
582 [Legacy top-level `base_url` and `api_key`](#legacy-top-level-base_url-and-api_key)).
583 File-owned keys stay bound to their file-owned endpoint: when the
584 environment replaces the route's base URL with a custom host, the saved
585 key is not sent there.
586 4. **`api_key_env` binding.** `[providers.<name>] api_key_env = "VAR"` reads
587 the named environment variable. For custom providers an unset or empty
588 binding is a loud error, not a silent fallback (#5104).
589 5. **Secret store.** The durable per-provider slot written by
590 `codewhale auth set` (file-backed under `~/.codewhale/secrets/` by
591 default; the OS keyring only when explicitly selected). Skipped for named
592 custom routes, self-hosted providers, custom endpoints other than an
593 explicitly authenticated loopback, and routes whose `auth_mode` needs no
594 key.
595 6. **Ambient environment.** The provider's own variable
596 (`DEEPSEEK_API_KEY`, `OPENROUTER_API_KEY`, `MOONSHOT_API_KEY`, …).
597 Ambient keys are only ever sent to the provider's official endpoint and
598 are skipped under the same conditions as the secret store.
599 7. **Keyless fallback.** Self-hosted providers and loopback endpoints may run
600 with no credential; every other route fails with provider-specific setup
601 guidance.
602
603 Legacy compatibility: `~/.deepseek/config.toml` is migrated into
604 `~/.codewhale/config.toml` on first launch, `DEEPSEEK_*` environment
605 variables remain accepted aliases for the `CODEWHALE_*` forms, and
606 `DEEPSEEK_SECRET_BACKEND` is the legacy alias for `CODEWHALE_SECRET_BACKEND`.
607
608 Run `codewhale auth status` to inspect the active provider's config
609 file, OS keyring backend, environment variable, winning source, and last-four
610 label without printing the key itself. The command only probes the active
611 provider's keyring entry.
612
613 For hosted, generic OpenAI-compatible, self-hosted, OpenAI Responses, or native
614 Anthropic providers, set `provider = "<id>"` or pass
615 `codewhale --provider <id>`. The canonical provider IDs are `deepseek`,
616 `nvidia-nim`, `openai`, `atlascloud`, `wanjie-ark`, `volcengine`,
617 `openrouter`, `orcarouter`, `xiaomi-mimo`, `novita`, `fireworks`,
618 `siliconflow`, `arcee`, `siliconflow-CN`, `moonshot`, `sglang`, `vllm`,
619 `ollama`, `ollama-cloud`, `huggingface`, `modelscope`, `together`, `qianfan`, `openai-codex`,
620 `anthropic`, `openmodel`, `zai`, `stepfun`, `minimax`, `deepinfra`,
621 `sakana`, `longcat`, `opencode-go`, `opencode-zen`, `meta`, `xai`,
622 `mistral`, `telecomjs`, `modelstudio-token-plan`, `google`,
623 `edenai`, `concentrate`, `codewhale`, and `custom` (a user-defined OpenAI-compatible endpoint via
624 `[providers.<name>]`).
625 For the provider-by-provider registry, including wire protocol, auth variables,
626 default base URLs, model IDs, and capability metadata, see
627 [PROVIDERS.md](PROVIDERS.md).
628 The facade saves provider credentials in the local secret store and forwards
629 the resolved key, base URL, provider, and model to the TUI process. Use
630 `codewhale auth set --provider nvidia-nim --api-key "YOUR_NVIDIA_API_KEY"` or
631 `codewhale auth set --provider openai --api-key "YOUR_OPENAI_COMPATIBLE_API_KEY"` or
632 `codewhale auth set --provider atlascloud --api-key "YOUR_ATLASCLOUD_API_KEY"` or
633 `codewhale auth set --provider wanjie-ark --api-key "YOUR_WANJIE_API_KEY"` or
634 `codewhale auth set --provider xiaomi-mimo --api-key "YOUR_XIAOMI_KEY"` or
635 `codewhale auth set --provider fireworks --api-key "YOUR_FIREWORKS_API_KEY"` or
636 `codewhale auth set --provider siliconflow --api-key "YOUR_SILICONFLOW_API_KEY"` or
637 `codewhale auth set --provider arcee --api-key "YOUR_ARCEE_API_KEY"` or the
638 matching provider ID from [PROVIDERS.md](PROVIDERS.md) to save provider keys
639 through the facade. The generic `openai` provider defaults
640 to `https://api.openai.com/v1`, accepts `OPENAI_BASE_URL`, and defaults to
641 `gpt-5.6`. A custom OpenAI-compatible gateway can still select its own model
642 explicitly. `atlascloud` defaults to
643 `https://api.atlascloud.ai/v1`, accepts `ATLASCLOUD_BASE_URL`, and uses
644 `deepseek-ai/deepseek-v4-flash` as its default model. `wanjie-ark` targets
645 Wanjie Ark's OpenAI-compatible endpoint at
646 `https://maas-openapi.wanjiedata.com/api/v1`, defaults to `deepseek-reasoner`,
647 and passes model IDs through unchanged because Wanjie model access is
648 account-scoped. SGLang, vLLM, and Ollama are
649 self-hosted and can run without an API key by default. Ollama defaults to
650 `http://localhost:11434/v1` and sends model tags such as `codewhale-coder:1.3b`
651 or `qwen2.5-coder:7b` unchanged. Self-hosted providers and loopback custom
652 URLs (`localhost`, `127.0.0.1`, `[::1]`, `0.0.0.0`) do not read the secret store
653 unless API-key auth is explicitly requested; use an env var or config-file key
654 when a local server does require bearer auth.
655 Ollama Cloud is the separate hosted `ollama-cloud` provider. It defaults to
656 `https://ollama.com/v1` and `gpt-oss:120b`; save its key with
657 `codewhale auth set --provider ollama-cloud`. Ambient auth reads
658 `OLLAMA_CLOUD_API_KEY` first, then Ollama's official `OLLAMA_API_KEY`.
659 SiliconFlow defaults to `https://api.siliconflow.com/v1`, accepts
660 `SILICONFLOW_BASE_URL`, and uses `deepseek-ai/DeepSeek-V4-Pro` by default.
661 `provider = "siliconflow-CN"` selects the China regional default
662 `https://api.siliconflow.cn/v1` with the `[providers.siliconflow_cn]` table and
663 `SILICONFLOW_API_KEY` credential slot.
664 Arcee AI defaults to `https://api.arcee.ai/api/v1`, accepts `ARCEE_BASE_URL`,
665 and uses `trinity-large-thinking` by default for Codewhale agent work.
666 `trinity-large-preview` is also listed as a direct Arcee API model; OpenRouter's
667 `arcee-ai/trinity-large-thinking` remains the OpenRouter namespaced form, while
668 the direct Arcee provider uses the bare `trinity-large-thinking` ID. Direct
669 Arcee large-model API calls are tracked as 256K-context BF16 serving; Thinking
670 is reasoning-capable, while Preview is not marked as a thinking model.
671
672 ### OpenRouter vendor pinning
673
674 OpenRouter serves each model through several upstream vendors, and Codewhale
675 can pin requests to a vendor with `[providers.openrouter] vendor` (#6007):
676
677 ```toml
678 provider = "openrouter"
679 [providers.openrouter]
680 model = "deepseek/deepseek-v4-pro"
681 vendor = "deepinfra" # copy the vendor slug from the model's OpenRouter page
682 ```
683
684 This sends `"provider": {"order": ["deepinfra"], "allow_fallbacks": false}`
685 on OpenRouter requests. A base slug can match multiple endpoint variants;
686 copy a full slug such as `deepinfra/turbo` to select one variant. An unavailable
687 pin fails at OpenRouter. Codewhale's separate `fallback_providers` setting can
688 still switch the whole route after a recoverable error.
689
690 The pin applies across OpenRouter models, including auxiliary requests on that
691 route. Set `vendor = ""` to clear it. Reload config or restart to apply edits;
692 requests already in flight keep their captured route. Other providers do not
693 inherit the pin. `/preview-request` shows the primary request's routing fields.
694
695 Model strings still pass through verbatim: `:floor` sorts by price, `:nitro`
696 sorts by throughput, and `@preset/my-team-preset` references an account preset.
697 See OpenRouter's [provider routing](https://openrouter.ai/docs/guides/routing/provider-selection)
698 and [presets](https://openrouter.ai/docs/guides/features/presets) documentation.
699 Codewhale does not fetch per-vendor endpoint prices or availability; pinned
700 usage reports a routing-dependent unknown cost instead of a catalog estimate.
701
702 ### Custom OpenAI-Compatible Gateways
703
704 For a single third-party service that implements the OpenAI Chat Completions
705 API, the simplest setup is the built-in `openai` provider name pointed at the
706 gateway:
707
708 ```toml
709 provider = "openai"
710 default_text_model = "your-model-id"
711
712 [providers.openai]
713 api_key = "YOUR_OPENAI_COMPATIBLE_API_KEY"
714 base_url = "https://your-gateway.example/v1"
715 ```
716
717 Put the endpoint under `[providers.openai]`, not the legacy top-level
718 `base_url`, so the OpenAI-compatible provider receives it. `default_text_model`
719 is the model ID sent to the gateway; `[providers.openai].model` can be used as
720 the OpenAI-provider-specific override.
721
722 If you keep several OpenAI-compatible gateways, or need a stable name for an
723 AgentProfile provider pin, define a user-named custom provider table:
724
725 ```toml
726 provider = "lm-studio"
727
728 [providers.lm-studio]
729 kind = "openai-compatible"
730 base_url = "http://127.0.0.1:1234/v1"
731 api_key = "lm-studio"
732 model = "qwen-2.5-7b"
733 ```
734
735 Custom provider names may be selected with `provider = "<name>"`,
736 `--provider <name>`, or an AgentProfile `provider = "<name>"` when the matching
737 `[providers.<name>]` table exists.
738
739 A custom table sends Chat Completions requests by default. Add
740 `wire = "responses"` to send OpenAI Responses requests to
741 `<base_url>/responses` instead, or `wire = "anthropic"` for Anthropic Messages:
742
743 ```toml
744 [providers.my-gateway]
745 kind = "openai-compatible"
746 base_url = "https://gateway.example/v1"
747 api_key_env = "MY_GATEWAY_API_KEY"
748 model = "gpt-5.6"
749 wire = "responses"
750 responses_profile = "standard"
751 ```
752
753 `responses_profile` is optional. Leaving it out uses the `standard` Responses dialect. The only profile a custom table may name is `standard`; `codex` and any unknown id are rejected, and the field is rejected unless `wire` selects Responses.
754
755 StepFun has a first-class provider entry, so keep Coding Plan credentials and
756 base URL scoped to `[providers.stepfun]`:
757
758 ```toml
759 provider = "stepfun"
760
761 [providers.stepfun]
762 api_key = "YOUR_STEPFUN_API_KEY"
763 base_url = "https://api.stepfun.ai/step_plan/v1"
764 model = "step-3.7-flash"
765 ```
766
767 `/provider` setup asks which StepFun billing route the key belongs to —
768 pay-as-you-go (`https://api.stepfun.ai/v1`) or a Step Plan subscription
769 (`https://api.stepfun.ai/step_plan/v1`) — and validates the key against the
770 endpoint you pick before saving it. The answer is written to
771 `[providers.stepfun].base_url` and nowhere else. If that key already holds a
772 base URL Codewhale does not recognize as one of those two routes, the question
773 is skipped and your value is left untouched.
774
775 Alibaba Bailian / Model Studio DashScope Qwen routes use the same OpenAI
776 provider shape:
777
778 ```toml
779 provider = "openai"
780
781 [providers.openai]
782 api_key = "YOUR_DASHSCOPE_API_KEY"
783 base_url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
784 model = "qwen-plus"
785 context_window = 1000000
786 ```
787
788 Use the regional DashScope `compatible-mode/v1` base URL that matches the
789 region of your API key. Codewhale keeps `qwen-plus` scoped to the `openai`
790 provider route and does not infer a different provider from the model prefix.
791 The same rule applies to all provider-prefixed model strings: a prefix such as
792 `deepseek-ai/...` or `deepseek/...` is a provider-owned wire ID under the
793 selected provider, not an automatic switch to the DeepSeek provider.
794 Set `context_window` to the gateway/model's real total context window when it
795 differs from Codewhale's static model metadata. See
796 [Context length (context window)](#context-length-context-window) for the full
797 resolution order and for how to check which value is in effect.
798
799 If the gateway accepts `POST /chat/completions` but rejects
800 `/v1/chat/completions`, set a provider-local `path_suffix`:
801
802 ```toml
803 [providers.openai]
804 base_url = "https://your-gateway.example/v1"
805 path_suffix = "/chat/completions"
806 ```
807
808 The suffix applies only to chat-completion requests. Model listing and
809 DeepSeek beta paths keep their built-in routing so a generic gateway override
810 does not accidentally rewrite `/models` or `/beta/completions`.
811
812 For private gateways with broken or intercepted certificates, use
813 `SSL_CERT_FILE` with a trusted CA bundle. The legacy provider-table key
814 `insecure_skip_tls_verify = true` is still parsed so `codewhale doctor --full` can
815 report stale configs, but provider clients reject it instead of disabling TLS
816 certificate verification.
817
818 Local HTTP endpoints such as Ollama, SGLang, and vLLM are allowed by default
819 when they use localhost or loopback addresses. For a non-local `http://`
820 gateway, launch with `DEEPSEEK_ALLOW_INSECURE_HTTP=1` only on a trusted network:
821
822 ```bash
823 DEEPSEEK_ALLOW_INSECURE_HTTP=1 codewhale
824 ```
825
826 Third-party OpenAI-compatible gateways that need extra request headers can set
827 `http_headers = { "X-Model-Provider-Id" = "your-model-provider" }` at the top
828 level or under a provider table such as `[providers.deepseek]`. When configured,
829 codewhale sends those custom headers on model API requests. The equivalent
830 environment override is `DEEPSEEK_HTTP_HEADERS`, using comma-separated
831 `name=value` pairs such as
832 `X-Model-Provider-Id=your-model-provider,X-Gateway-Route=dev`. `Authorization`
833 and `Content-Type` are managed by the client and are not overridden by this
834 setting.
835
836 ### Vision Model
837
838 Codewhale's chat provider and `image_analyze` tool are configured separately.
839 The main chat path remains the selected text/tool provider; image analysis runs
840 through `[vision_model]` when the `vision_model` feature is enabled.
841
842 Xiaomi's current image-understanding docs include `mimo-v2.5` for image input.
843 To use MiMo for `image_analyze`, configure the vision model explicitly:
844
845 ```toml
846 [features]
847 vision_model = true
848
849 [vision_model]
850 model = "mimo-v2.5"
851 api_key = "YOUR_XIAOMI_KEY"
852 base_url = "https://api.xiaomimimo.com/v1"
853 ```
854
855 The example above uses Xiaomi MiMo's pay-as-you-go OpenAI-compatible endpoint.
856 If you are using a Token Plan key (`tp-...`) for `[vision_model]`, you must set
857 `base_url` explicitly because this generic OpenAI-compatible block does not
858 auto-select MiMo endpoints. Use
859 `https://token-plan-sgp.xiaomimimo.com/v1` for Singapore accounts,
860 `https://token-plan-cn.xiaomimimo.com/v1` for China-region accounts, or
861 `https://token-plan-ams.xiaomimimo.com/v1` for Europe/Amsterdam accounts.
862
863 ### Auto Model Routing (`[auto]`, `[auto.router]`)
864
865 With `model = "auto"`, each turn runs on your **declared default model** unless
866 you have opted into something else. Auto never guesses a cheaper or stronger
867 model from how a request is worded; the old keyword-and-length heuristic was
868 removed (`auto_route_declared_fallback` in `crates/engine/src/model_routing.rs`).
869 Two optional layers change that:
870
871 - an `[auto.router]` classifier, which you write down, that picks a model per
872 turn; and
873 - `[auto] cost_saving`, which prefers the active provider's fast sibling.
874
875 With neither set, Auto is local and free: the turn uses the default model and
876 no classifier call is made.
877
878 **There is no default classifier.** With `[auto.router]` unset, no classifier
879 call happens, whatever keys you hold. Holding a DeepSeek key used to elect
880 `deepseek-v4-flash` automatically. That was removed because it spent tokens on
881 a route the user never chose and privileged one provider over the rest
882 (`AutoRouterConfig` in `crates/tui/src/config.rs`). Electing a network
883 classifier is now something you write down.
884
885 Point the classifier at any configured provider with `[auto.router]`:
886
887 ```toml
888 [auto.router]
889 provider = "zai"
890 model = "glm-5-turbo"
891 thinking = "off" # optional; defaults to off
892 timeout_secs = 4 # optional; default 4, 0 = default, capped at 300
893 ```
894
895 A classifier call happens only when `[auto.router]` names both `provider` and
896 `model` *and* that provider has a key:
897 `router_available = router_configured && has_api_key_for(...)` in
898 `ModelInventory::from_config` (`crates/engine/src/model_inventory.rs`). If either
899 condition fails, or the classifier call errors or times out, the local
900 fallback decides: the default model, or the fast sibling under `cost_saving`.
901 The turn's route receipt (Turn Inspector, Ctrl+Alt+O or `/turn inspect`, "Model
902 route + tokens/cost") records which path was taken, and a
903 router you configured that cannot run or fails (missing key, HTTP error,
904 timeout, invalid answer) is shown as `Auto router: failing — …` rather than
905 silently ignored.
906
907 #### Set up model routing
908
909 `/router` (also `/model router`) opens one Router setup view with these
910 presets. Each writes only `[auto.router]`; none is ever chosen for you.
911
912 | Preset | What it writes | Cost and privacy |
913 | --- | --- | --- |
914 | `/router jev` | Jev, TypeSafe's decision model, over OpenRouter (`typesafe/jev-1.13`) or TypeSafe direct, whichever key you have | About $0.00002 per turn ($0.042 per million input tokens, output free). Your latest request and up to six recent context lines go to OpenRouter → TypeSafe (or TypeSafe). |
915 | `/router fast` | The active provider's runnable fast tier with thinking off | Your existing key; the classifier sees the same request text. |
916 | `/router off` | Removes `[auto.router]` | No router call; Auto turns use the default model, or the fast tier while `[auto] cost_saving = true` (Off leaves that setting alone). |
917 | `/router custom` | Nothing; prints the TOML to edit | — |
918
919 Choosing Jev or Fast makes **one test call** with a fixed sample request and
920 shows the tier it picked, the probabilities and confidence, the latency and the
921 provider-reported cost. `Enter` (or `/router save <preset>`) then saves through
922 the normal config writer; `Esc` discards it. TypeSafe paused new signups on
923 2026-09-22, so OpenRouter is the default route for new users. A TypeSafe key is
924 read from `TYPESAFE_API_KEY`, the `typesafe` secret-store entry, or
925 `[providers.typesafe] api_key` / `api_key_env`.
926
927 #### Decision routers (`kind = "decision"`)
928
929 A decision router asks a non-generative decision model typed Choice questions
930 for the active provider's `fast` and `strong` tiers and thinking level, then
931 reads calibrated probabilities. No prose is parsed.
932
933 ```toml
934 [auto.router]
935 kind = "decision" # default "chat"
936 provider = "openrouter" # or "typesafe"
937 model = "typesafe/jev-1.13" # "~typesafe/jev-latest" also works; TypeSafe direct: "jev-latest"
938 timeout_secs = 2
939 min_confidence = 0.5 # default 0.5, clamped to 0..1
940 ```
941
942 - The router is called only when the active provider has a runnable strong/fast
943 pair; otherwise there is no call and no spend.
944 - An answer below `min_confidence` takes the local fallback. Under
945 `[auto] cost_saving`, a `strong` answer also needs a probability of at least
946 0.75, or the turn stays on the fast tier.
947 - An unknown `kind`, or a decision `provider` other than `openrouter` /
948 `typesafe`, leaves the router unconfigured and shown as failing.
949 - `[auto.router] thinking` is ignored for decision routers. Both routes settle tokens through
950 the originating session's routed-usage ledger. TypeSafe is a named Custom route
951 with unknown billing; its price is never borrowed from the active chat provider.
952 Provider-reported cost remains verbatim on the decision receipt.
953 - OpenRouter uses `POST /api/alpha/decisions`; TypeSafe uses `POST /v1/systemone`.
954 The shared client validates Choice, Noul and Score against the offered questions
955 and bounds responses to 256 KiB. Malformed answers fail open with usage retained.
956
957 #### Shadow Decision Gate (experimental, off by default)
958
959 The Superfast Decision Gate asks the decision model three more typed questions
960 about the turn — does it need a tool, can it be answered from the conversation,
961 and what is its intent — and logs a conservative recommendation. It is an option
962 of the decision router above, not a second call:
963
964 ```toml
965 [auto.router]
966 kind = "decision"
967 provider = "openrouter"
968 model = "typesafe/jev-1.13"
969 shadow_gate = true # default off; decision routers only
970 ```
971
972 - The gate's questions ride the router's own request, so it uses the router's
973 route, key, model, `base_url` and `timeout_secs`, runs only when the router
974 runs (Auto model mode with a runnable strong/fast pair), and adds no second
975 request.
976 - It is shadow-only: the recommendation never changes routing. It is logged
977 under the `superfast` target with the route, failure class and latency, never
978 prompt text, and kept as one shadow decision receipt on the originating turn
979 or session. Tokens settle once, through the router's usage record.
980 - It fails open with the router: a timeout, error or rejected answer is the
981 gate's failure class too. The shared client validates every offered question,
982 so a decision server that cannot answer the gate's questions fails the
983 router's answer as well and the turn takes the local fallback.
984 - `shadow_gate = true` on a `kind = "chat"` router leaves the router
985 unconfigured and shown as failing.
986 - The `SUPERFAST_ENABLED`, `SUPERFAST_PROVIDER`, `SUPERFAST_BASE_URL`,
987 `SUPERFAST_MODEL` and `SUPERFAST_TIMEOUT_MS` environment variables are no
988 longer read. Setting any of them logs one warning naming this key; move the
989 route, model and base URL into `[auto.router]`. The separate 150 ms deadline
990 is gone: the gate waits exactly as long as the router does.
991
992 The wire contracts are documented in [TypeSafe's OpenAPI schema](https://api.typesafe.ai/openapi.json)
993 and [OpenRouter's Decisions examples](https://openrouter.ai/blog/insights/what-is-jev/).
994
995 The Decision Gate concept and reference implementation are by Andrea Bruno,
996 released under CC BY 4.0:
997 [harness-superfast](https://github.com/Andrea-Bruno/harness-superfast).
998
999 Two `[auto]` keys shape routing (`AutoConfig` in `crates/tui/src/config.rs`):
1000
1001 ```toml
1002 [auto]
1003 cost_saving = false # default false
1004 cross_provider = false # default false
1005 ```
1006
1007 - **`cost_saving`** (default `false`). Without a classifier, Auto pins the
1008 active provider's validated fast sibling instead of the default model. A
1009 provider with no runnable fast sibling stays on the default. With a
1010 classifier, the classifier is told to prefer the fast tier for routine or
1011 ambiguous work and to pick the strong tier only for clearly agentic,
1012 multi-step, architecture, security or debugging work. Cost-saving never
1013 switches provider just to save money.
1014 - **`cross_provider`** (default `false`). Auto stays on the provider the session
1015 is configured to use. The classifier is only shown that provider's models,
1016 and the fallback never leaves it. Setting `cross_provider = true` lets the
1017 classifier choose among every runnable provider. There is no interactive
1018 toggle for `cross_provider`; it has to be set in config. A decision router
1019 always chooses within the active provider.
1020
1021 To bootstrap MCP and skills directories at their resolved paths, run `codewhale setup`.
1022 To only scaffold MCP, run `codewhale mcp init`.
1023
1024 Note: `setup`, `doctor`, `mcp`, `features`, `sessions`, `resume`/`fork`, `exec`,
1025 `review`, and `eval` are all available from the installed `codewhale` command.
1026 The consolidated dispatcher also provides `auth`, `config`, `model`, `thread`, `sandbox`,
1027 `app-server`, `mcp-server`, `completions`, `login`/`logout`, `account`,
1028 `metrics`, `update`, `lane`, `workflow`, and `web`. Plain prompts enter the
1029 in-process TUI runtime. Release installers expose the same bytes as `codew`.
1030
1031 ### Startup Update Checks
1032
1033 By default, the TUI starts a background check for the latest stable Codewhale
1034 release and shows a short toast only when a newer release is available and the
1035 official release assets are complete. The check never blocks startup, never
1036 blocks a turn, and fails silently when offline.
1037
1038 Disable the startup check entirely for air-gapped, corporate-proxy, or managed
1039 desktop environments:
1040
1041 ```toml
1042 [update]
1043 check_for_updates = false
1044 ```
1045
1046 #### Automatic updates
1047
1048 `mode` decides what happens when a newer release is found (release-binary
1049 installs only; package-manager and desktop-app copies always just notify):
1050
1051 ```toml
1052 [update]
1053 mode = "auto" # auto (default): download in the background, apply at next start
1054 # notify: tell me only; off: no checks
1055 ```
1056
1057 `codewhale config set update.mode notify` writes it. `CODEWHALE_UPDATE_MODE`
1058 overrides it, and an organization policy file overrides both; see
1059 [INSTALL.md](INSTALL.md#automatic-updates) for the full flow, signing, the
1060 policy file and `codewhale update --rollback`.
1061
1062 #### Throttling
1063
1064 The answer is cached in `~/.codewhale/update-check.json` and reused for
1065 `check_interval_hours` (default `6`). Only the *network request* is throttled —
1066 the notice still appears on every launch while an update is outstanding. Set `0`
1067 to check on every launch.
1068
1069 ```toml
1070 [update]
1071 check_interval_hours = 6
1072 ```
1073
1074 A failed check keeps the last answer (so the notice stays) and retries about an
1075 hour later rather than on every launch, which keeps offline and rate-limited
1076 machines quiet.
1077
1078 #### Automatic suppression
1079
1080 Checks are skipped, without contacting the network, when any of these is set to
1081 a non-falsey value:
1082
1083 | Variable | Why |
1084 | --- | --- |
1085 | `CODEWHALE_NO_UPDATE_CHECK` | Explicit opt-out. |
1086 | `NO_UPDATE_NOTIFIER` | The cross-CLI convention, honored for compatibility. |
1087 | `CI`, `CONTINUOUS_INTEGRATION`, `GITHUB_ACTIONS`, `GITLAB_CI`, `BUILDKITE`, `CIRCLECI`, `JENKINS_URL`, `TEAMCITY_VERSION`, `TF_BUILD` | Automated build; nobody is at the terminal. |
1088
1089 Values of `""`, `0`, `false`, `no`, and `off` do not count as set, so a
1090 `CI=false` export does not disable checks for ordinary users.
1091
1092 #### Which update command is offered
1093
1094 Codewhale never installs anything on its own — it only tells you an update
1095 exists. The command it names depends on how the running binary was installed,
1096 detected from its path:
1097
1098 | Install | Command offered |
1099 | --- | --- |
1100 | GitHub release binary (including Termux) | `codewhale update` |
1101 | npm (`node_modules` on the path) | `npm install -g codewhale@latest` |
1102 | Homebrew (`Cellar` / `linuxbrew` prefix) | `brew upgrade codewhale` |
1103 | `cargo install` (`~/.cargo/bin`) | `cargo install codewhale-cli --locked --force` |
1104
1105 For package-managed installs the notice also warns against `codewhale update`:
1106 replacing a binary Homebrew or npm owns leaves the manager describing a version
1107 that is no longer on disk, and the next upgrade silently reverts you.
1108
1109 Override the detection with `CODEWHALE_INSTALL_METHOD=npm|homebrew|cargo|binary`
1110 if you relocated the binary somewhere the path heuristics cannot read.
1111
1112 To redirect the startup check, set `update_uri` to an internal endpoint that
1113 returns GitHub-compatible latest-release JSON. Minimal mirror metadata with a
1114 `tag_name` field is accepted; if `assets` are present, Codewhale requires the
1115 same uploaded asset set as the official release before showing the toast.
1116
1117 ```toml
1118 [update]
1119 check_for_updates = true
1120 update_uri = "https://internal.mirror.example/codewhale/releases/latest"
1121 ```
1122
1123 When `update_uri` is not set, startup checks honor release mirror environment
1124 variables such as `CODEWHALE_RELEASE_BASE_URL` before falling back to the
1125 official GitHub API endpoint. If a configured `update_uri` cannot be fetched or
1126 parsed and a release mirror env var is set, the TUI falls back to that mirror
1127 instead of failing startup.
1128
1129 #### What's new after an update
1130
1131 The first time Codewhale starts after its version goes up, it says so once and
1132 links that version's release notes on codewhale.net:
1133
1134 ```text
1135 Updated to 0.10.2. Got 12 features, 31 fixes and 8 other changes.
1136 Release notes: https://codewhale.net/en/changelog/0.10.2
1137 ```
1138
1139 The counts come from the changelog compiled into the binary. Entries under
1140 Added or New count as features; Fixed, Security and Latest fixes count as
1141 fixes; Contributors, Thanks, Community and Known limits or issues are not
1142 counted; every other section counts as other changes. The link uses your UI
1143 language where the site has it (`zh` for Chinese) and English otherwise.
1144
1145 The TUI shows the notice on the startup card and moves it into the transcript
1146 when the card leaves (at once when the session opens from `--resume`,
1147 `--continue` or a prompt), adding `/change <version>` for reading the notes in
1148 place. The `doctor`, `models`,
1149 `sessions`, `receipts`, `setup`, `init`, `install`, `features`,
1150 `integrations`, `mcp`, `config`, `model`, `metrics`, `providers`, `account`,
1151 `login`, `logout` and `update` commands print it to stderr instead, when
1152 stdout and stderr are both terminals and no JSON output is requested. `exec`,
1153 servers, JSON output and non-terminal runs never show it; the next start that
1154 can show it does.
1155
1156 Nothing is shown on a fresh install or after a downgrade. The version that
1157 last started is recorded in `~/.codewhale/last-launch.json`. The notice reads
1158 only local files, so it is independent of `check_for_updates`. To turn it off:
1159
1160 ```toml
1161 [update]
1162 show_whats_new = false
1163 ```
1164
1165 ## Workshop output budgets
1166
1167 By default an oversized tool result uses bounded spillover: a result
1168 under the byte threshold stays inline, a larger one gets a head/tail
1169 preview plus a session artifact the model can read back. There is no
1170 synthesis sub-agent and no per-call `raw = true` escape.
1171
1172 `[workshop] large_output_threshold_tokens` and
1173 `[workshop.per_tool_thresholds]` (exact model-visible tool names such as
1174 `bash`) only take effect when the process opts in to adaptive evidence
1175 routing with `CODEWHALE_ADAPTIVE_OUTPUT_ROUTING=1`; they set where a result
1176 stops being inline and becomes handle-only evidence.
1177
1178 Two optional byte ceilings (#5367) apply either way. They raise the
1179 model-visible floor and never lower it:
1180
1181 - `read_result_max_bytes` — cap for a single `read` / `read_file`
1182 result. Absent keeps the compile-time defaults (100000 bytes for
1183 `read`, which has no line cap; 16KiB / 500 lines for `read_file`).
1184 For `read` this is the middle of a three-layer budget: the model's
1185 own per-call `max_bytes` (hard maximum 500000) raises the budget for
1186 one call, this setting raises the floor for the whole process, and
1187 either way 2MiB is the absolute ceiling. Highest wins; neither layer
1188 can lower a budget the other granted.
1189 - `tool_result_max_bytes` — cap for a generic tool result after
1190 spillover. Absent keeps the 12K-character compact floor (48K on
1191 windows ≥500K tokens). Hard cap is 2MiB.
1192
1193 ## Context length (context window)
1194
1195 Also called context size, context limit, max context, or window. This is the
1196 total token window Codewhale budgets against, and it drives the header/footer
1197 context percent, the auto-compaction trigger, context-pressure checks, and the
1198 request output cap. If Codewhale compacts at 128K on a model you know serves a
1199 1M window, this is the setting to change (#5134).
1200
1201 **See what is in effect, and where the value came from.** Every one of these
1202 prints the resolved window *and* its source:
1203
1204 - `/status` — a `Context window:` row with the percent and token counts, and a
1205 `Window source:` row naming the provenance and the exact key that overrides
1206 it.
1207 - `/config` → Provider — `Context window` (your override, or `(not set)`) and
1208 `Effective context window` (`1048576 tokens · configured`). Typing
1209 `context length` in the `/config` filter jumps straight to them.
1210 - `/context report` — `Window: 1048576 tokens (12.4% used, ...; source: configured)`.
1211 - `/context json` — machine-readable `context_window_tokens` and
1212 `context_window_source`.
1213
1214 **Change it** with the provider-table key `context_window`:
1215
1216 ```toml
1217 [providers.moonshot]
1218 context_window = 1048576
1219 ```
1220
1221 or from the CLI:
1222
1223 ```bash
1224 codewhale config set providers.moonshot.context_window 1048576
1225 codewhale config unset providers.moonshot.context_window # back to automatic
1226 ```
1227
1228 Use the table for the provider you are actually on (`providers.openai`,
1229 `providers.deepseek`, `providers.moonshot`, …); `/status` names it for you. The
1230 value is a positive token count for the route's *total* window.
1231
1232 When one gateway fronts models with heterogeneous windows, scope the override
1233 to an exact wire model id with `[providers.<name>.model_context_windows]`:
1234
1235 ```toml
1236 [providers.command_code]
1237 context_window = 204800
1238
1239 [providers.command_code.model_context_windows]
1240 "MiniMaxAI/MiniMax-M2.5" = 204800
1241 "google/gemini-3.1-flash-lite" = 1000000
1242 ```
1243
1244 Keys are the exact wire model ids the route sends (dotted and `org/model`
1245 spellings both work as TOML keys when quoted); each value must be a positive
1246 token count. A matching entry beats the provider-level `context_window` for
1247 that model only — every other model on the provider still resolves against
1248 `context_window` and the rungs below. From the CLI:
1249
1250 ```bash
1251 codewhale config set 'providers.command_code.model_context_windows."MiniMaxAI/MiniMax-M2.5"' 204800
1252 codewhale config unset 'providers.command_code.model_context_windows."MiniMaxAI/MiniMax-M2.5"'
1253 ```
1254
1255 For an older configuration with `provider = "custom"` and a top-level `base_url`, the editor saves limits in a top-level `[model_context_windows]` table. This preserves the route used by existing sessions. A profile that inherits this older route must select a named provider to save its own limit.
1256
1257 ### How the effective window is resolved
1258
1259 First match wins, and the source label each surface prints is exactly this
1260 rung:
1261
1262 1. `configured (per-model)` — a `[providers.<name>.model_context_windows]`
1263 entry keyed by the route's exact wire model id. A hard override for that
1264 model only; it never rewrites another model's window.
1265 2. `configured` — `[providers.<name>] context_window` in `config.toml`. A hard
1266 override for every model on the provider: nothing below it can raise or
1267 lower the result. Read-time aliases:
1268 `contextWindow`, `context_window_tokens`, `contextWindowTokens`,
1269 `context_length`, `contextLength`.
1270 3. `provider-reported` — route-scoped 1M metadata a provider actually reported
1271 for the Kimi Code `k3` route, when it was observed within the last 24 hours.
1272 4. `static Kimi Code safe floor` — 262,144 tokens for Kimi Code memberships,
1273 because 1M access is plan-gated (Allegretto and above).
1274 5. `catalog` — the bundled route catalog (hand-curated offerings first, then
1275 the bundled Models.dev rows). The official `openai-codex` roster supplies
1276 account-specific model choices, not context-window metadata. Refresh it
1277 with `codewhale models --update --provider openai-codex`; Codewhale does
1278 not read `$CODEX_HOME` for this route.
1279 6. `model-name hint` — an `_Nk` suffix parsed from the model name itself
1280 (`qwen3-32b-256k` → 256,000), vendor-agnostic. A naming convention the
1281 serving engine may not honor is not a fact about the route, so this rung
1282 sits *below* the catalog: any catalog row for the same id beats it (#5441).
1283 7. `fallback` — the static per-provider capability path when no catalog offering
1284 matches the resolved route (see
1285 [`MODELS_AND_PROVIDERS.md`](MODELS_AND_PROVIDERS.md)): 200,000 for
1286 Anthropic-wire routes, 128,000 for `openai-codex`, 8,192 for Ollama,
1287 otherwise Codewhale's reviewed per-model limits
1288 (`codewhale_models::context_window_for_model`), and finally 128,000 when the
1289 model is unknown.
1290
1291 ### What "(unverified)" means
1292
1293 The `model-name hint` and `fallback` rungs still drive real budgets — the
1294 compaction trigger, the context meter, and the output reservation all use the
1295 number — but they are guesses, not capabilities anyone checked. Every surface
1296 that renders one of these windows appends `(unverified)` to its source label
1297 (the status line, the context-pressure message, `/status`, `/config`, and the
1298 model picker chip), so a window you did not configure and no provider reported
1299 can never read as a verified limit (#5239, #5441). The `context_window` and
1300 `model_context_windows` provider-table keys above are the fix: a configured
1301 window is a hard override and renders as `configured` (or
1302 `configured (per-model)`) with no marker.
1303
1304 Output ceilings follow the same rule (#5440): an Anthropic-family model the
1305 catalog does not describe keeps the 64K Messages floor as its clamp, labeled
1306 `unverified` (or an "assumed floor") instead of `documented`. The official
1307 ChatGPT plan preview does not accept `max_output_tokens`; Codewhale sends no
1308 output-token cap on that route. A local request budget is not an upstream
1309 limit or a guarantee about the completed response length.
1310
1311 There is no environment variable for the context window; the provider-table
1312 `context_window` and per-model `model_context_windows` keys are the user
1313 knobs. They are the right ones to set when a gateway or self-hosted runtime
1314 serves a window Codewhale's catalog does not model — per-model when only some
1315 of a provider's routes differ, provider-wide when they all do. Codewhale will
1316 not invent a window it cannot justify — it falls back to a conservative value,
1317 labels it `fallback`, and marks it `(unverified)` at every surface that shows
1318 it.
1319
1320 ### Adjacent knobs
1321
1322 - `auto_compact_threshold_percent` (settings.toml; also accepted as
1323 `auto_compact_threshold`; `10`–`100`, default `80`): the share of the full
1324 route context window at which auto-compaction fires, clamped so it can never
1325 cross the spendable input ceiling after output reservation and headroom.
1326 Editable from `/config`. Raising the window without touching this raises the
1327 absolute compaction point along with it.
1328 - `auto_compact` (settings.toml, on/off): turns automatic compaction off
1329 entirely; `/compact` and Ctrl+L stay available.
1330 - `[compaction] summary_instructions` and
1331 `[compaction] retained_user_message_tokens` (config.toml): standing
1332 summarizer instructions and the verbatim user-message retention budget. See
1333 the `compaction.*` entry in the config-key reference below.
1334 - `CODEWHALE_MAX_OUTPUT_TOKENS` (environment variable; legacy alias
1335 `DEEPSEEK_MAX_OUTPUT_TOKENS`): overrides the requested output cap. Without an
1336 override, Codewhale starts at the safe `65536` request cap and intersects it
1337 with any smaller documented model or route ceiling; a catalog `max_output`
1338 such as DeepSeek V4's 384K remains a capability ceiling, not the amount every
1339 response requests. Explicit overrides are preserved within the resolved
1340 route context window and any route output ceiling, and preflight/emergency
1341 budgeting reserves the same effective value that can reach the wire. A
1342 separately documented route input ceiling also clamps preflight and
1343 compaction even when the total context window is larger. A blank canonical
1344 variable falls through to a nonblank legacy value; a nonblank invalid or
1345 zero canonical value is authoritative and falls back to the safe automatic
1346 default instead of activating a stale legacy setting. There is no
1347 `max_output_tokens` key in `config.toml`.
1348
1349 Before compaction replaces conversation history, Codewhale durably saves the
1350 original messages to the session's `artifacts/context-transfer-<id>.json` and,
1351 when a model summary is produced, its handoff to the matching `.md` file.
1352 These use the existing session artifact store and persistence redaction.
1353 A failed write aborts compaction without replacing context. Pruning-only passes
1354 save the original messages without making an extra model call. The model can
1355 read them back through `context_archive_search`: with `query` it runs an ASCII
1356 case-insensitive substring search returning short snippets and an archive id,
1357 and with `id` it pages through one message; the handoff note names it so the
1358 model knows the archive exists. Pressure metadata
1359 shows estimated input tokens and the configured trigger; it is an estimate, not
1360 an exact promise about a provider's remaining context.
1361
1362 Compaction history is available through `codewhale metrics` (or `--json`) and
1363 `audit.log` in the Codewhale home. Completed passes record their trigger,
1364 summary/pruning path, message and estimated-token counts, effective threshold,
1365 and summarizer token usage. Automatic refusals are recorded once per turn with
1366 their reason. These are local diagnostics, not provider invoice totals; earlier
1367 artifacts are not retroactively counted. A text-mode `exec` that attempts
1368 compaction saves its owning session at turn completion so its recovery artifacts
1369 remain discoverable. A killed process may leave artifacts without that final
1370 session snapshot; the audit writer reports I/O failures instead of inventing data.
1371
1372 See [Settings File](#settings-file-persistent-ui-preferences) for the
1373 compaction settings and [Token Quantities and
1374 Drivers](#token-quantities-and-drivers) for what each displayed token number
1375 actually measures.
1376
1377 ## Profiles
1378
1379 You can define multiple profiles in the same file:
1380
1381 ```toml
1382 default_text_model = "deepseek-flash"
1383
1384 [providers.deepseek]
1385 api_key = "PERSONAL_KEY"
1386
1387 [profiles.work.providers.deepseek]
1388 api_key = "WORK_KEY"
1389 base_url = "https://api.deepseek.com/beta"
1390
1391 [profiles.nvidia-nim]
1392 provider = "nvidia-nim"
1393 default_text_model = "deepseek-ai/deepseek-v4-pro"
1394
1395 [profiles.nvidia-nim.providers.nvidia_nim]
1396 api_key = "NVIDIA_KEY"
1397 base_url = "https://integrate.api.nvidia.com/v1"
1398
1399 [profiles.fireworks]
1400 provider = "fireworks"
1401 default_text_model = "accounts/fireworks/models/deepseek-v4-pro"
1402
1403 [profiles.siliconflow]
1404 provider = "siliconflow"
1405 default_text_model = "deepseek-ai/DeepSeek-V4-Pro"
1406
1407 [profiles.siliconflow.providers.siliconflow]
1408 base_url = "https://api.siliconflow.com/v1"
1409
1410 [profiles.openai-compatible]
1411 provider = "openai"
1412
1413 [profiles.openai-compatible.providers.openai]
1414 base_url = "https://openai-compatible.example/v4"
1415 model = "glm-5"
1416
1417 [profiles.atlascloud]
1418 provider = "atlascloud"
1419
1420 [profiles.atlascloud.providers.atlascloud]
1421 base_url = "https://api.atlascloud.ai/v1"
1422 model = "deepseek-ai/deepseek-v4-flash"
1423
1424 [profiles.sglang]
1425 provider = "sglang"
1426
1427 [profiles.sglang.providers.sglang]
1428 base_url = "http://localhost:30000/v1"
1429 model = "deepseek-ai/DeepSeek-V4-Pro"
1430
1431 [profiles.vllm]
1432 provider = "vllm"
1433
1434 [profiles.vllm.providers.vllm]
1435 base_url = "http://localhost:8000/v1"
1436 model = "deepseek-ai/DeepSeek-V4-Pro"
1437
1438 [profiles.ollama]
1439 provider = "ollama"
1440
1441 [profiles.ollama.providers.ollama]
1442 base_url = "http://localhost:11434/v1"
1443 model = "qwen2.5-coder:7b" # an installed chat-capable tag
1444
1445 [profiles.ollama-cloud]
1446 provider = "ollama-cloud"
1447
1448 [profiles.ollama-cloud.providers.ollama_cloud]
1449 base_url = "https://ollama.com/v1"
1450 model = "gpt-oss:120b"
1451 ```
1452
1453 Select a profile with:
1454
1455 - CLI: `codewhale --profile work`
1456 - Env: `DEEPSEEK_PROFILE=work`
1457
1458 If a profile is selected but missing, codewhale exits with an error listing available profiles.
1459
1460 For local Ollama, omit `providers.ollama.model` to select a tag whose native
1461 catalog confirms completion support. `/provider ollama`, exec, and Runtime API
1462 default-model admission refresh that catalog; embedding-only catalogs have no
1463 automatic chat default. An explicit model keeps its exact tag.
1464
1465 A loaded model's `/api/ps` context observation is usable for 60 seconds.
1466 `/api/show` reports the trained maximum, which does not establish the served
1467 window. An unloaded model or an expired observation uses the unverified 8192-token
1468 fallback; explicit context-window configuration still takes precedence.
1469
1470 ## Legacy top-level `base_url` and `api_key`
1471
1472 Older releases kept DeepSeek's endpoint and key at the top of `config.toml`,
1473 and each reader decided for itself which other routes inherited them. They
1474 now live in provider tables only. An older file keeps working unchanged:
1475 every load reads the top-level keys as if they were already in their table,
1476 by one rule, per file and per `[profiles.<name>]`:
1477
1478 1. `provider = "custom"` with no `[providers.custom]` table: the endpoint, key
1479 and a copy of the model become `[providers.custom]`.
1480 2. An endpoint on another vendor's official host (for example
1481 `integrate.api.nvidia.com`, `xiaomimimo.com`, `openrouter.ai`, or the
1482 ChatGPT Codex endpoint) belongs to that vendor's table, so a DeepSeek route
1483 never sends requests there.
1484 3. Anything else belongs to `[providers.deepseek]`, which DeepSeek-CN also
1485 reads for its endpoint and key.
1486
1487 The key goes with DeepSeek (or the literal custom route). It follows the
1488 endpoint to another vendor only when the same table sets `provider` to that
1489 vendor, the host is that vendor's own, and the vendor's table has no key. When
1490 no `provider` is set, a NIM host still selects `nvidia-nim` and
1491 `api.deepseeki.com` still selects `deepseek-cn`. A `[vision_model]` without a
1492 key of its own keeps using the top-level key. A profile's top-level
1493 `base_url` now overrides the base file's `[providers.deepseek] base_url`
1494 (before, the base table silently won).
1495
1496 When a top-level value and its table disagree, the table's `base_url` and the
1497 top-level `api_key` are used, which is what the runtime sent before.
1498
1499 Loading never rewrites the file. The next save Codewhale makes (for example
1500 `codewhale config set`, `/config ... --save`, or `auth set`) moves the keys,
1501 keeps comments, writes a one-time credential-free copy of the old file to
1502 `config.toml.pre-migrate.bak`, and prints one line saying what moved. A
1503 disagreeing pair is never resolved in the file on its own; both values stay
1504 until you choose, and `codewhale config doctor` / `codewhale doctor --full` report
1505 it (sources only, never values). `codewhale config get|set|unset base_url`
1506 (and `api_key`) address the active provider's table.
1507
1508 To tidy the file yourself:
1509
1510 ```bash
1511 codewhale config migrate --dry-run # show what would move
1512 codewhale config migrate # move it (backup first)
1513 codewhale config migrate --prefer top-level # resolve a conflict: keep the top-level value
1514 codewhale config migrate --prefer table # resolve a conflict: keep the table value
1515 ```
1516
1517 ## Environment Variables
1518
1519 Most runtime environment variables override config values. API-key variables are
1520 fallbacks after saved config and keyring credentials.
1521
1522 The three user-facing slots — provider, model, base URL — expose `CODEWHALE_*`
1523 aliases. When both forms are set the `CODEWHALE_*` value wins; the
1524 `DEEPSEEK_*` form is kept for older shells:
1525
1526 - `CODEWHALE_PROVIDER` (preferred) / `DEEPSEEK_PROVIDER` (legacy alias) —
1527 `deepseek|deepseek-anthropic|nvidia-nim|openai|atlascloud|wanjie-ark|volcengine|openrouter|xiaomi-mimo|novita|fireworks|siliconflow|arcee|siliconflow-CN|moonshot|sglang|vllm|ollama|ollama-cloud|huggingface|modelscope|together|qianfan|openai-codex|anthropic|openmodel|zai|stepfun|minimax|deepinfra|mistral`
1528 - `CODEWHALE_MODEL` (preferred) / `DEEPSEEK_MODEL` (legacy alias) — default model for the active provider
1529 - `CODEWHALE_BASE_URL` (preferred) / `DEEPSEEK_BASE_URL` (legacy alias) — base URL for the active provider
1530
1531 `CODEWHALE_BASE_URL` applies to the **active** route only. A request pinned to
1532 another provider — a subagent or fleet child, a routed tool, the per-turn
1533 auto-router, a picker preview — resolves its endpoint from that provider's own
1534 `[providers.<table>]`, then its provider-scoped variable (`MOONSHOT_BASE_URL`,
1535 `OPENAI_BASE_URL`, …), then that provider's default. It never inherits the
1536 active session's host, and a custom route with no configured `base_url` fails
1537 closed on a loopback placeholder rather than borrowing another provider's
1538 endpoint. The environment writes the value into the active identity's own
1539 table: DeepSeek-CN falls back to `[providers.deepseek]` for its endpoint and
1540 key, but never to a DeepSeek value the environment addressed to DeepSeek alone.
1541 A managed-config overlay that supplies or reselects the effective
1542 route's endpoint takes the generic override away from every route.
1543
1544 Remaining variables:
1545
1546 - `CODEWHALE_LOCAL_PROXY_FALLBACK` (`0`) — keeps reqwest's build-time proxy snapshot; the loopback fallback is on by default. Read once when the first client is built.
1547 - `DEEPSEEK_API_KEY`
1548 - `DEEPSEEK_ANTHROPIC_BASE_URL`
1549 - `DEEPSEEK_HTTP_HEADERS` (custom model request headers, comma-separated `name=value` pairs)
1550 - `DEEPSEEK_DEFAULT_TEXT_MODEL` (extra legacy alias of `DEEPSEEK_MODEL`)
1551 - `DEEPSEEK_STREAM_IDLE_TIMEOUT_SECS` (stream idle timeout in seconds; default `900`, clamped to `1..=3600`)
1552 - `DEEPSEEK_STREAM_OPEN_TIMEOUT_SECS` (connection setup + response-header wait in seconds; default `180`, clamped to `5..=600`; distinct from the per-chunk idle timeout; `stream.open_timeout_secs` (legacy `tui.stream_open_timeout_secs` fallback) wins when positive)
1553 - `CODEWHALE_CACHE_MAXIMAL` (`1`/`true`/`on`/`yes`) — cache-maximal context mode (#528). When on, the Repo Working Set block materializes the **full current contents** of the top active files into the system prompt each turn (deterministic order, byte-bounded), instead of only listing their paths. The block stays byte-stable while those files are unchanged so DeepSeek's KV prefix cache keeps hitting; editing a file cache-misses from its block onward. Off by default (path list only). Byte caps default to 24 KB per file / 96 KB total.
1554 - `NVIDIA_API_KEY` or `NVIDIA_NIM_API_KEY` (when provider is `nvidia-nim`)
1555 - `NVIDIA_NIM_BASE_URL`, `NIM_BASE_URL`, or `NVIDIA_BASE_URL`
1556 - `NVIDIA_NIM_MODEL`
1557 - `OPENAI_API_KEY`
1558 - `OPENAI_BASE_URL`
1559 - `OPENAI_MODEL`
1560 - `ATLASCLOUD_API_KEY`
1561 - `ATLASCLOUD_BASE_URL`
1562 - `ATLASCLOUD_MODEL`
1563 - `WANJIE_ARK_API_KEY`, `WANJIE_API_KEY`, or `WANJIE_MAAS_API_KEY`
1564 - `WANJIE_ARK_BASE_URL`, `WANJIE_BASE_URL`, or `WANJIE_MAAS_BASE_URL`
1565 - `WANJIE_ARK_MODEL`, `WANJIE_MODEL`, or `WANJIE_MAAS_MODEL`
1566 - `VOLCENGINE_API_KEY`, `VOLCENGINE_ARK_API_KEY`, or `ARK_API_KEY`
1567 - `VOLCENGINE_BASE_URL`, `VOLCENGINE_ARK_BASE_URL`, or `ARK_BASE_URL`
1568 - `VOLCENGINE_MODEL` or `VOLCENGINE_ARK_MODEL`
1569 - `OPENROUTER_API_KEY`
1570 - `OPENROUTER_BASE_URL`
1571 - `OPENROUTER_MODEL`
1572 - `XIAOMI_MIMO_TOKEN_PLAN_API_KEY`, `MIMO_TOKEN_PLAN_API_KEY`, `XIAOMI_MIMO_API_KEY`, `XIAOMI_API_KEY`, or `MIMO_API_KEY`
1573 - `XIAOMI_MIMO_BASE_URL` or `MIMO_BASE_URL`
1574 - `XIAOMI_MIMO_MODEL` or `MIMO_MODEL`
1575 - `XIAOMI_MIMO_MODE` or `MIMO_MODE` (`token-plan-sgp`, `token-plan-cn`,
1576 `token-plan-ams`, or `pay-as-you-go`)
1577 - `NOVITA_API_KEY`
1578 - `NOVITA_BASE_URL`
1579 - `NOVITA_MODEL`
1580 - `FIREWORKS_API_KEY`
1581 - `FIREWORKS_BASE_URL`
1582 - `FIREWORKS_MODEL`
1583 - `HUGGINGFACE_API_KEY` or `HF_TOKEN` (`HF_TOKEN` is a fallback alias accepted when provider is `huggingface`)
1584 - `MODELSCOPE_API_KEY`
1585 - `HUGGINGFACE_BASE_URL` or `HF_BASE_URL`
1586 - `HUGGINGFACE_MODEL` or `HF_MODEL`
1587 - `SILICONFLOW_API_KEY`
1588 - `SILICONFLOW_BASE_URL`
1589 - `SILICONFLOW_MODEL`
1590 - `ARCEE_API_KEY`
1591 - `ARCEE_BASE_URL`
1592 - `ARCEE_MODEL`
1593 - `TOGETHER_API_KEY`
1594 - `TOGETHER_BASE_URL`
1595 - `TOGETHER_MODEL`
1596 - `QIANFAN_API_KEY` or `BAIDU_QIANFAN_API_KEY`
1597 - `QIANFAN_BASE_URL` or `BAIDU_QIANFAN_BASE_URL`
1598 - `QIANFAN_MODEL` or `BAIDU_QIANFAN_MODEL`
1599 - `OPENAI_CODEX_ACCESS_TOKEN` or `CODEX_ACCESS_TOKEN` (legacy process tokens; ignored by the official ChatGPT plan route)
1600 - `OPENAI_CODEX_BASE_URL` or `CODEX_BASE_URL`
1601 - `OPENAI_CODEX_MODEL` or `CODEX_MODEL`
1602 - `OPENAI_CODEX_ACCOUNT_ID` or `CODEX_ACCOUNT_ID` (legacy identity hints; ignored by the official ChatGPT plan route)
1603 - `CODEWHALE_CHATGPT_NEW_ACCOUNT=1` explicitly replaces the single selected ChatGPT registration after a validated browser sign-in
1604 - `ANTHROPIC_API_KEY`
1605 - `ANTHROPIC_BASE_URL`
1606 - `ANTHROPIC_MODEL`
1607 - `ZAI_API_KEY` or `Z_AI_API_KEY`
1608 - `ZAI_BASE_URL` or `Z_AI_BASE_URL`
1609 - `ZAI_MODEL` or `Z_AI_MODEL`
1610 - `STEPFUN_API_KEY` or `STEP_API_KEY`
1611 - `STEPFUN_BASE_URL` or `STEP_BASE_URL`
1612 - `STEPFUN_MODEL` or `STEP_MODEL`
1613 - `MINIMAX_API_KEY`
1614 - `MINIMAX_BASE_URL`
1615 - `MINIMAX_MODEL`
1616 - `DEEPINFRA_API_KEY` or `DEEPINFRA_TOKEN`
1617 - `DEEPINFRA_BASE_URL`
1618 - `DEEPINFRA_MODEL`
1619 - `MISTRAL_API_KEY`
1620 - `MISTRAL_BASE_URL`
1621 - `MISTRAL_MODEL`
1622 - `MOONSHOT_API_KEY` or `KIMI_API_KEY`
1623 - `MOONSHOT_BASE_URL` or `KIMI_BASE_URL`
1624 - `MOONSHOT_MODEL`, `KIMI_MODEL_NAME`, or `KIMI_MODEL`
1625 - `SGLANG_BASE_URL`
1626 - `SGLANG_MODEL`
1627 - `SGLANG_API_KEY` (optional; many localhost SGLang servers do not require auth)
1628 - `VLLM_BASE_URL`
1629 - `VLLM_MODEL`
1630 - `VLLM_API_KEY` (optional; many localhost vLLM servers do not require auth)
1631 - `OLLAMA_BASE_URL`
1632 - `OLLAMA_MODEL`
1633 - `OLLAMA_API_KEY` (optional; many localhost Ollama servers do not require auth)
1634 - `OLLAMA_CLOUD_BASE_URL`
1635 - `OLLAMA_CLOUD_MODEL`
1636 - `OLLAMA_CLOUD_API_KEY` (preferred Cloud key; `OLLAMA_API_KEY` is the official fallback)
1637 For every product-level `CODEWHALE_*` variable below, the matching legacy
1638 `DEEPSEEK_*` name is still read as a compatibility fallback; when both are set,
1639 the `CODEWHALE_*` value wins.
1640
1641 - `CODEWHALE_TIMING=1` emits local JSON phase durations on stderr for startup, model preparation, tool planning, approval waits and postprocessing. Nested intervals overlap. The records contain only phase, process ID, end time and elapsed microseconds; stream-json stdout is unchanged.
1642 - `CODEWHALE_LOG_LEVEL` or `RUST_LOG` (`info`/`debug`/`trace` enables lightweight verbose logs)
1643 - `CODEWHALE_SKILLS_DIR`
1644 - `CODEWHALE_MCP_CONFIG`
1645 - `CODEWHALE_MEMORY` (`1|on|true|yes|y|enabled` turns user memory on)
1646 - `CODEWHALE_MEMORY_PATH`
1647 - `CODEWHALE_TELEMETRY` / `DEEPSEEK_TELEMETRY` (legacy alias) — anonymous usage
1648 counting is on by default in the current source, with a disclosure
1649 naming Codewhale as the sole first-party collector and an easy durable opt-out. Prior explicit
1650 declines remain off. Accepts `0|1|true|false|yes|no|on|off|enabled|
1651 disabled`. An explicit "off" is a **floor**: it beats `--telemetry true` and
1652 `telemetry = true` in config, and a value this list cannot read also resolves
1653 to off, because a typo in a kill switch must never resolve to "on". See
1654 [`TELEMETRY.md`](TELEMETRY.md).
1655 - `CODEWHALE_TELEMETRY_ENDPOINT` / `DEEPSEEK_TELEMETRY_ENDPOINT` (legacy alias)
1656 — `https://`, or plain `http://` only for loopback. Overrides the config file.
1657 Unset selects the shipped default,
1658 `https://telemetry.codewhale.net/v1/telemetry`; setting it to the **empty
1659 string** routes batches to a local dry-run file and contacts nobody. Either
1660 way it only decides where a session sends — it cannot override an opt-out.
1661 - `CODEWHALE_ALLOW_SHELL` (`1`/`true` enables)
1662 - `CODEWHALE_APPROVAL_POLICY` (`on-request|untrusted|never`)
1663 - `CODEWHALE_SANDBOX_MODE` (`read-only|workspace-write|danger-full-access|external-sandbox`)
1664 - `CODEWHALE_NO_NEW_PRIVS` (`0`/`false`/`no`/`off`/`disabled` opts out) — Linux only. The
1665 TUI process sets the kernel's irreversible no-new-privileges flag at startup
1666 as defense-in-depth, which blocks `sudo`/`su`/setuid helpers for Codewhale's
1667 whole process tree. The flag is already skipped when the startup sandbox
1668 mode resolves to `danger-full-access` (#5723), so this variable is the
1669 explicit override in the remaining cases: set it to a falsey value before
1670 launching if you administer through Codewhale as a wheel-group user under a
1671 narrower posture and need escalation to work (#5413), or set a truthy value
1672 to force the flag on even under `danger-full-access`. Unset, the posture
1673 decides; the other startup hardening (no ptrace, no core dumps) always
1674 stays on.
1675 - `CODEWHALE_MANAGED_CONFIG_PATH`
1676 - `CODEWHALE_REQUIREMENTS_PATH`
1677 - `CODEWHALE_MAX_SUBAGENTS` (clamped to `1..=128`)
1678 - `CODEWHALE_TASKS_DIR` (runtime task queue/artifact storage, default
1679 `~/.codewhale/tasks`, with legacy `~/.deepseek/tasks` fallback when only the
1680 legacy directory exists)
1681 - `CODEWHALE_RUNTIME_DIR` (override the runtime thread store root). Interactive
1682 sessions default to `$CODEWHALE_HOME/sessions/<session-id>/runtime` so each
1683 Codewhale process owns its own store (#5630). The store is single-owner: a
1684 second process on the **same** root fails at startup. Set this variable to
1685 share one store across processes, or when the runtime API server should use a
1686 stable non-session path. Unset, the API/server path remains
1687 `$CODEWHALE_HOME/tasks/runtime`. Legacy alias: `DEEPSEEK_RUNTIME_DIR`.
1688 - `CODEWHALE_ALLOW_INSECURE_HTTP` (`1`/`true` allows non-local `http://` base URLs; default is reject)
1689 - `CODEWHALE_FORCE_HTTP1` (`1|true|yes|on` pins the HTTP client to HTTP/1.1, disabling HTTP/2; useful on Windows or behind proxies that mishandle long-lived H2 streams)
1690 - `CODEWHALE_HOME` (override the base data directory; defaults to `~/.codewhale`).
1691 If you previously exported `DEEPSEEK_HOME`, rename it to `CODEWHALE_HOME`;
1692 the old env var is not used for new Codewhale state paths.
1693 - `CODEWHALE_RELEASE_BASE_URL` (release asset mirror used by `codewhale update`
1694 and by TUI startup update checks when `[update].update_uri` is not set, or as
1695 a fallback when that configured URI cannot be fetched)
1696 - `CODEWHALE_AUTOMATIONS_DIR` (override the automations storage directory; uses
1697 `~/.codewhale/automations` by default, with legacy `~/.deepseek/automations`
1698 fallback when only the legacy directory exists)
1699 - `NO_ANIMATIONS` (`1|true|yes|on` forces `low_motion = true` and
1700 `fancy_animations = false` at startup, regardless of the saved
1701 settings; see [`docs/ACCESSIBILITY.md`](./ACCESSIBILITY.md)).
1702 - `SSL_CERT_FILE` — corporate-proxy / TLS-inspecting MITM users
1703 point this at a PEM bundle (or single DER cert) and the cert(s)
1704 get added alongside the platform's system trust store. Failures
1705 log a warning and continue — the existing system roots still
1706 apply.
1707
1708 ### Instruction sources (`instructions = [...]`, #454)
1709
1710 Add a list of additional system-prompt sources that get
1711 concatenated, in declared order, alongside the auto-loaded
1712 `AGENTS.md`:
1713
1714 ```toml
1715 instructions = [
1716 "./AGENTS.md",
1717 "~/.codewhale/global.md",
1718 "~/team/agents-shared.md",
1719 ]
1720 ```
1721
1722 Rules:
1723
1724 - Paths run through `expand_path` so `~` and env vars work.
1725 - These entries are **global-scope** instruction authority: they are charged
1726 to the global budget together with the global `AGENTS.md`/`instructions.md`
1727 fallbacks and `~/.claude/CLAUDE.md`.
1728 - A file keeps at most its first 100 KiB. A file larger than
1729 `[instruction_budget] file_max_bytes` (8 MiB by default) is skipped with a
1730 notice. Missing and empty files are skipped with a notice so a stale entry
1731 doesn't fail the launch.
1732 - Only user-owned config, profiles, and managed config may set this array.
1733 Project config (`<workspace>/.codewhale/config.toml`, or legacy
1734 `<workspace>/.deepseek/config.toml`) ignores `instructions` so a cloned repo
1735 cannot choose arbitrary local files to place into the prompt.
1736
1737 ### Instruction budget (`[instruction_budget]`, #6526)
1738
1739 Standing instruction files are assembled into two independent scopes and
1740 budgeted in **estimated tokens** — the same conservative estimator `/context`
1741 uses, never a `bytes/4` shortcut, which underestimates Cyrillic by 30–50%.
1742
1743 - **global** — `~/.codewhale/AGENTS.md` (or the `.agents`/`.deepseek`
1744 fallbacks), the global `instructions.md` fallbacks, `~/.claude/CLAUDE.md`
1745 as a last resort when `claude_fallback` is on, and the
1746 `instructions = [...]` array.
1747 - **project** — the repository-root → workspace `AGENTS.md` chain, co-read
1748 foreign files, and the `.codewhale/rules`/`.claude/rules` block.
1749
1750 Each scope is capped at `min(absolute_tokens, percent × usable_window)`. The
1751 usable window is the route window minus the output reservation the request
1752 will actually carry and a safety reserve of 10% of the window (minimum 2,048
1753 tokens). A route whose context window is unknown has no usable window: the
1754 percentage ceilings and the guard are reported as `unknown` and only the
1755 absolute caps apply.
1756
1757 ```toml
1758 [instruction_budget]
1759 global_budget_tokens = 100000
1760 project_budget_tokens = 100000
1761 global_budget_percent = 25
1762 project_budget_percent = 25
1763 static_prefix_guard_percent = 80
1764 file_max_bytes = 8388608
1765 policy = "trim"
1766 claude_fallback = false
1767 ```
1768
1769 With a 64K (65,536-token) output reservation:
1770
1771 | window | usable | per scope | both scopes | guard 80% |
1772 | --- | --- | --- | --- | --- |
1773 | 128,000 | 49,664 | 12,416 | 24,832 | 39,731 |
1774 | 1,000,000 | 834,464 | 100,000 (absolute cap) | 200,000 | 667,571 |
1775
1776 Behaviour:
1777
1778 - **Nothing is trimmed while a source is within its scope budget.**
1779 - A scope over budget drops whole files from the broadest end first — the
1780 root-most ancestor goes first, the workspace file last — and a single file
1781 that alone exceeds the remaining budget keeps its **head** and drops its
1782 tail with a marker carrying bytes and estimated tokens.
1783 - Every instruction, rules, and configured file retains at most its first
1784 100 KiB of text, ending in a marker that names the bytes kept and dropped.
1785 - Rules are charged to the project scope after the instruction chain and keep
1786 a head-first trim.
1787 - `file_max_bytes` is a hard ceiling that can only be lowered from its 8 MiB
1788 default: a larger file is **skipped**, never trimmed, and the read is
1789 bounded on the open file, so a FIFO or a growing file cannot exhaust memory.
1790 The same applies to a whitespace-only file and to files beyond the
1791 50-per-directory rules cap.
1792 - `policy = "trim"` (default) trims and reports. `policy = "refuse"` stops the
1793 request before dispatch when a scope budget, the rules budget, or the
1794 100 KiB retention would trim, or when the request prefix exceeds the guard;
1795 skips stay skips, because one bad file must not make the project unopenable.
1796 - `static_prefix_guard_percent` caps the request prefix: every system block
1797 plus the tool schemas the request carries. When it trips, the two scopes are
1798 narrowed largest first until the prefix fits, only the installed instruction
1799 block is replaced, and the change is recorded as a declared prefix change.
1800 If the prefix still exceeds the guard afterwards, the residual excess is
1801 reported rather than looped on. The guard must leave at least 10 points
1802 above the two scope percents. Prompts owned by a host (child agents,
1803 isolated chat, RLM) are measured and can be refused, but are never trimmed.
1804 - `claude_fallback = true` (opt in; default `false`): a directory with no
1805 `AGENTS.md` (or codewhale `instructions.md`) uses its `CLAUDE.md`. A skipped
1806 `AGENTS.md` counts as absent; a file already loaded from a wider scope (a
1807 symlink) is a reported duplicate, not a fallback trigger. Other tools'
1808 instruction files are never imported unless you opt in here or through
1809 `project_instruction_imports`.
1810 - Every loss — trimmed, skipped, refused — reaches the model as one
1811 runtime-provenance message whenever the list changes, and appears per source
1812 in `/context report`. `codewhale doctor`'s report is a preview built from the
1813 current files and config; it does not claim a request passed the tool-schema
1814 guard.
1815 - The table is **user config only**, like `instructions`: project config is
1816 ignored and a cloned repository cannot shrink the global budget or force
1817 `refuse`. An invalid table (unknown key, zero budget, percent outside
1818 1–100, guard without room left, `file_max_bytes` outside 1–8388608) fails
1819 the launch.
1820
1821 ### Hooks
1822
1823 Hooks are a **TUI runtime feature**. They fire from the interactive TUI and
1824 the engine turn loop it drives; `codewhale exec`, the CLI subcommands, the
1825 app-server / ACP surfaces, and the `workflow` tool do not fire them.
1826
1827 [`docs/HOOKS.md`](HOOKS.md) is the authoritative reference for all eleven hook
1828 events — their firing points, environment variables, stdin payloads, timeout
1829 and background semantics, and which three of them can steer Codewhale. The
1830 sections below cover the configuration surface and the steering contracts in
1831 more depth.
1832
1833 Two contract points worth reading there before writing a hook:
1834
1835 - `background = true` means **submitted and never awaited**. The hook still
1836 gets the documented stdin payload and the same timeout, but it has no exit
1837 code and cannot steer.
1838 - A condition that references context its event never carries (an `exit_code`
1839 condition outside `tool_call_after` / `on_error`, a `mode` condition on
1840 `shell_env`, a tool condition on a non-tool event) is **rejected at load**,
1841 logged, and shown in `/hooks list`. It does not silently never match.
1842 Rejection is per entry, so a broken hook never drops another one that merely
1843 shares its `name` or is likewise unnamed.
1844
1845 ### `/hooks` listing
1846
1847 Run `/hooks` (or `/hooks list`) inside the TUI to see every
1848 configured lifecycle hook grouped by event, including each
1849 hook's name, command preview, effective timeout, and condition. When
1850 `[hooks].default_timeout_secs` is set it replaces every per-hook
1851 `timeout_secs`, and the listing shows that effective value and names the
1852 override rather than echoing the per-hook number. A
1853 `default_timeout_secs = 0` is rejected at load — it would expire every hook
1854 in the config immediately — so the override is ignored, per-hook
1855 `timeout_secs` applies, the listing shows that per-hook value with no
1856 override provenance, and the rejection appears under `configuration
1857 problems`. The
1858 `[hooks].enabled` flag's state is shown at the top so it's
1859 obvious when hooks are globally suppressed, and any entry rejected
1860 at load is listed under `configuration problems` with the reason.
1861 Hooks are configured under `[[hooks.hooks]]` entries — see
1862 [`docs/HOOKS.md`](HOOKS.md) for the full schema.
1863
1864 ### Mutable `message_submit` hooks
1865
1866 `message_submit` hooks run before a submitted message is added to
1867 history or sent to the model. Unlike observer-only lifecycle hooks,
1868 non-background `message_submit` hooks can replace or block the
1869 submitted text.
1870
1871 ```toml
1872 [[hooks.hooks]]
1873 event = "message_submit"
1874 command = "~/.codewhale/hooks/inject-context.sh"
1875 timeout_secs = 2
1876 continue_on_error = true
1877 ```
1878
1879 The hook receives JSON on stdin:
1880
1881 ```json
1882 {
1883 "event": "message_submit",
1884 "text": "original user text",
1885 "text_bytes": 18,
1886 "text_original_bytes": 18,
1887 "text_truncated": false,
1888 "session_id": "sess_12345678",
1889 "workspace": "/path/to/workspace",
1890 "mode": "agent",
1891 "model": "deepseek-chat",
1892 "total_tokens": 1234
1893 }
1894 ```
1895
1896 The entire serialized document is capped at 32 KiB. Codewhale retains the
1897 largest UTF-8-safe `text` prefix that fits after JSON escaping and bounded
1898 metadata, and the three `text_*` fields make truncation explicit. Immediate
1899 messages, restored queue entries, merged steers, and prior-hook replacements
1900 all cross this same serialization boundary.
1901
1902 If the hook exits `0` and prints JSON with a non-empty string `text` field,
1903 that value replaces the submitted text:
1904
1905 ```json
1906 { "text": "replacement user text" }
1907 ```
1908
1909 Exit `0` with empty stdout, or stdout JSON without `text`, leaves
1910 the current text unchanged. A JSON `text` field must not be empty;
1911 `{"text":""}` is treated as invalid stdout and ignored. Exit `2`
1912 blocks the submission before the turn starts; a structured `reason` field can
1913 provide the bounded, redacted status message shown in the TUI. Raw stdout,
1914 stderr, and process-error text are not copied into denial receipts.
1915 Other non-zero exits follow the hook's `continue_on_error` setting.
1916 Timeouts and spawn failures are also surfaced as transient TUI status
1917 messages when `continue_on_error = true` lets submission continue.
1918
1919 Multiple `message_submit` hooks run in config order, and each hook
1920 receives the text produced by the previous hook. Hooks marked
1921 `background = true` are observer-only and cannot transform or block
1922 the message — they still receive the same stdin payload and the same
1923 environment, they are simply never awaited. Existing environment
1924 variables remain available.
1925 `shell_env` hooks keep their existing `KEY=VALUE` stdout contract;
1926 JSON stdout contracts exist for `message_submit` (above) and
1927 `tool_call_before` (below).
1928
1929 ### `tool_call_before` decision hooks
1930
1931 `tool_call_before` hooks run before each tool call the root agent makes (not
1932 sub-agent tool calls). In
1933 addition to the legacy hard deny (exit code `2`, which always wins
1934 regardless of stdout), a foreground hook may print a JSON decision on
1935 stdout with exit code `0`:
1936
1937 ```json
1938 {
1939 "decision": "allow" | "deny" | "ask",
1940 "reason": "human-readable explanation (used for deny)",
1941 "updatedInput": { "command": "ls -la" },
1942 "additionalContext": "text appended to the tool result for the model"
1943 }
1944 ```
1945
1946 All fields are optional. Empty stdout, non-JSON stdout, and JSON
1947 without a `decision` field behave exactly as before (allow). An
1948 unrecognized `decision` string logs a fixed warning without echoing the
1949 untrusted value and is treated as allow.
1950
1951 - `deny` blocks the tool; the model receives a permission-denied tool
1952 result containing `reason`.
1953 - `ask` forces the interactive approval prompt in Ask and Auto-Review even for
1954 tools that would otherwise auto-run. Full Access does not open tool-approval
1955 prompts, so hook `ask` does not downgrade that posture.
1956 - `updatedInput` must be a JSON object; it replaces the tool input
1957 before execution. When several hooks supply it, the last hook wins.
1958 - `additionalContext` is appended to the tool result sent back to the
1959 model as `[hook context] ...`. Multiple hooks' contexts are
1960 concatenated.
1961
1962 When multiple hooks match, precedence is deny > ask > allow. Hooks
1963 marked `background = true` cannot steer tool calls — they are
1964 submitted and never awaited, so they have no verdict to contribute.
1965
1966 A foreground hook that produced no verdict at all — it hit its timeout, the
1967 process could not be started, or a strict process exited non-zero without an
1968 explicit JSON decision — is not treated as permission. If
1969 *that* hook is configured with `continue_on_error = false`, the outcome
1970 denies the tool call and the denial names the hook and a bounded reason.
1971 Strictness is read off the hooks that actually matched this call, so a
1972 strict gate scoped to another tool cannot deny it, and a lenient hook's
1973 timeout does not deny merely because a strict hook exists elsewhere in
1974 config. Under the default `continue_on_error = true` the outcome is
1975 logged and the call proceeds.
1976
1977 `reason` and `additionalContext` are capped (2 000 characters per field,
1978 8 000 for the concatenated context of one call) and stripped of control
1979 characters before they reach the TUI or the model.
1980
1981 Example deny hook:
1982
1983 ```toml
1984 [[hooks.hooks]]
1985 event = "tool_call_before"
1986 command = '''echo '{"decision":"deny","reason":"blocked by project policy"}' '''
1987 condition = { type = "tool_name", name = "exec_shell" }
1988 ```
1989
1990 Example ask hook (force approval for every MCP tool):
1991
1992 ```toml
1993 [[hooks.hooks]]
1994 event = "tool_call_before"
1995 command = '''echo '{"decision":"ask"}' '''
1996 condition = { type = "tool_name", name = "mcp__*" }
1997 ```
1998
1999 Example input rewrite:
2000
2001 ```toml
2002 [[hooks.hooks]]
2003 event = "tool_call_before"
2004 command = "~/.codewhale/hooks/clamp-shell-timeout.sh"
2005 condition = { type = "tool_name", name = "exec_shell" }
2006 ```
2007
2008 where the script reads the hook context, then prints
2009 `{"updatedInput": {...}}` with the adjusted arguments.
2010
2011 `tool_name` conditions support `*` globs: `mcp__*` matches every MCP
2012 tool (e.g. `mcp__github__create_issue`) but not built-ins like
2013 `read_file`; exact names keep matching exactly. Other regex
2014 metacharacters in the pattern are matched literally.
2015
2016 ### Project-local hooks
2017
2018 Repositories can ship policy in `<workspace>/.codewhale/hooks.toml`,
2019 using the same shape as the `[hooks]` table (top-level fields plus
2020 `[[hooks]]` entries). Project hooks are executable shell
2021 configuration, so Codewhale only loads them after the workspace has
2022 been trusted in user-owned config through the trust prompt or a
2023 `[projects."<workspace>"] trust_level = "trusted"` entry. Session
2024 `/trust on` mode does not enable repo-supplied hooks by itself.
2025 Once trusted, project hooks are appended after global
2026 hooks from `config.toml`, so they run last and, for `updatedInput`,
2027 win ties. A malformed trusted project file logs a warning and startup
2028 falls back to global hooks only.
2029
2030 ```toml
2031 # .codewhale/hooks.toml
2032 [[hooks]]
2033 event = "tool_call_before"
2034 command = '''echo '{"decision":"deny","reason":"no shell in this repo"}' '''
2035 condition = { type = "tool_name", name = "exec_shell" }
2036 ```
2037
2038 ### Turn-end observer hooks
2039
2040 `turn_end` hooks observe the end of each model turn after post-turn
2041 state, usage totals, cost accounting, notifications, receipts, and
2042 queue recovery have been updated. They receive JSON on stdin and are
2043 observer-only: stdout is ignored, failures are logged as warnings, and
2044 the hook cannot block user input, mutate the transcript, or change the
2045 next queued follow-up.
2046
2047 Observer-only UI events share one 32-entry queue and two persistent workers;
2048 the terminal loop uses non-blocking submission and does not create a thread per
2049 event. A full queue or unavailable dispatcher drops that observer event and is
2050 kept as an event-specific error toast, independent of ordinary agent/turn
2051 status text.
2052
2053 ```toml
2054 [[hooks.hooks]]
2055 event = "turn_end"
2056 command = "~/.codewhale/hooks/turn-audit.sh"
2057 timeout_secs = 2
2058 continue_on_error = true
2059 ```
2060
2061 The payload includes common hook metadata plus post-turn accounting:
2062
2063 ```json
2064 {
2065 "event": "turn_end",
2066 "session_id": "sess_12345678",
2067 "workspace": "/path/to/workspace",
2068 "mode": "agent",
2069 "created_at": "2026-07-12T10:30:00+00:00",
2070 "model_backed": true,
2071 "provider": "deepseek",
2072 "model": "deepseek-chat",
2073 "billing_surface": null,
2074 "turn_id": "turn_12345678",
2075 "status": "completed",
2076 "error": null,
2077 "duration_ms": 1834,
2078 "usage": {
2079 "input_tokens": 1200,
2080 "output_tokens": 180,
2081 "prompt_cache_hit_tokens": 900,
2082 "prompt_cache_miss_tokens": 300,
2083 "prompt_cache_write_tokens": 0,
2084 "reasoning_tokens": null,
2085 "reasoning_replay_tokens": null
2086 },
2087 "totals": {
2088 "session_tokens": 1380,
2089 "conversation_tokens": 1380,
2090 "input_tokens": 1200,
2091 "output_tokens": 180
2092 },
2093 "tool_count": 2,
2094 "queued_message_count": 1,
2095 "stop_hook_active": false
2096 }
2097 ```
2098
2099 `created_at` anchors time-window pricing; `provider` and `model` identify the
2100 effective route used for model-backed turns. `billing_surface` is an optional,
2101 non-secret classification derived from the endpoint that actually served the
2102 turn. Recognized StepFun routes emit `stepfun-payg` or `stepfun-plan`; the raw
2103 base URL is never written to hook or runtime records. Runtime `TurnRecord`
2104 exports call the same field `effective_billing_surface`. This keeps
2105 subscription quota separate from token-priced usage. Unrecognized and custom endpoints remain `null` and unpriced.
2106
2107 Shell-only lifecycle completions set `model_backed` to `false` and may report a
2108 `null` provider; they carry no model token or cost usage. Completion-only shell, manual-compaction, and purge events that do
2109 not have a matching `TurnStarted` retain the observer notification with a
2110 synthetic `lifecycle_<uuid>` turn id and the time the completion was observed.
2111
2112 For `interrupted` or `failed` turns, `status` reflects that terminal
2113 state and `error` carries the engine error string when one is available.
2114 `stop_hook_active` is reserved for future re-entry protection and is
2115 currently always `false`.
2116
2117 ### Sub-agent lifecycle hooks
2118
2119 `subagent_spawn` and `subagent_complete` hooks observe sub-agent lifecycle
2120 events. They receive bounded JSON metadata on stdin and are observer-only:
2121 hook failures are logged as warnings and do not block sub-agent scheduling,
2122 change prompts, or change results. For these observer events,
2123 `continue_on_error` has no effect: later matching hooks still run even when an
2124 earlier hook exits non-zero.
2125
2126 ```toml
2127 [[hooks.hooks]]
2128 event = "subagent_complete"
2129 command = "~/.codewhale/hooks/subagent-audit.sh"
2130 timeout_secs = 2
2131 continue_on_error = true
2132 ```
2133
2134 `subagent_spawn` receives:
2135
2136 ```json
2137 {
2138 "event": "subagent_spawn",
2139 "agent_id": "agent_12345678",
2140 "session_id": "sess_12345678",
2141 "workspace": "/path/to/workspace",
2142 "mode": "agent",
2143 "model": "deepseek-chat",
2144 "total_tokens": 1234,
2145 "prompt_preview": "bounded prompt preview",
2146 "prompt_truncated": false
2147 }
2148 ```
2149
2150 `subagent_complete` receives the same common fields plus terminal metadata:
2151
2152 ```json
2153 {
2154 "event": "subagent_complete",
2155 "agent_id": "agent_12345678",
2156 "session_id": "sess_12345678",
2157 "workspace": "/path/to/workspace",
2158 "mode": "agent",
2159 "model": "deepseek-chat",
2160 "total_tokens": 1234,
2161 "status": "completed",
2162 "result_preview": "bounded result preview",
2163 "result_truncated": false
2164 }
2165 ```
2166
2167 Previews are capped before delivery so lifecycle hooks do not receive full
2168 sub-agent prompts, transcripts, or unbounded results. Use the transcript handle
2169 returned by `agent` when full sub-agent details are needed.
2170
2171 ### Running-turn input
2172
2173 Composer shortcuts keep the same role throughout a session:
2174
2175 - **Enter** sends when idle and queues a next-turn follow-up while busy. The
2176 behavior does not change before versus after the provider's first token.
2177 - With an empty composer and queued follow-ups visible, **Enter** sends the
2178 oldest queued follow-up into the active turn now.
2179 - **Ctrl+Enter** (or **Cmd+Enter** when the terminal forwards it) explicitly
2180 steers the active turn. It sends normally when idle.
2181 - By default, **Shift+Enter**, **Alt+Enter**, and **Ctrl+J** insert a newline.
2182 - Set `composer_multiline_mode = true` to make **Enter** insert a newline and
2183 **Alt+Enter** send instead. **Shift+Enter** also sends when the terminal
2184 reports it distinctly; legacy terminals may report it as plain **Enter**.
2185 **Ctrl+J** still inserts a newline, and supported **Ctrl+Enter** /
2186 **Cmd+Enter** behavior is unchanged.
2187 - **Ctrl+G** and **Ctrl+S** only stash drafts; they never send or steer.
2188
2189 ### Composer stash (`/stash`, Ctrl+G / Ctrl+S)
2190
2191 Press **Ctrl+G** in the composer to park the current draft to
2192 `~/.codewhale/composer_stash.jsonl`. `/stash list` shows parked
2193 drafts with one-line previews and timestamps; `/stash pop`
2194 restores the most recently parked draft (LIFO); `/stash clear`
2195 wipes the file. Capped at 200 entries; multiline drafts round-trip intact.
2196 **Ctrl+S** remains an alias in terminals that forward it; Cursor and VS Code
2197 reserve Ctrl+S for Save, so Ctrl+G is the portable default.
2198
2199 ## Settings File (Persistent UI Preferences)
2200
2201 codewhale also stores user preferences in:
2202
2203 - `~/.codewhale/settings.toml` on new installs
2204 - `~/.deepseek/settings.toml` or the legacy platform config-dir
2205 `deepseek/settings.toml` when an existing settings file is present
2206
2207 Notable settings include `auto_compact`, which uses a model-aware default-on
2208 policy for known context windows up to the 1M-token V4 class. Automatic
2209 compaction runs before the active model limit and carries the compacted summary
2210 forward into the next request. The trigger defaults to
2211 `auto_compact_threshold_percent = 80`. Users who prefer manual continuity can
2212 persist `auto_compact = false`; manual `/compact` / Ctrl+L remains available.
2213 Bare `/settings` opens the typed settings editor, where rows can be changed and
2214 saved; `/settings text` prints the resolved values instead. `/config <key>
2215 <value>` changes one key, and `--save` persists it.
2216
2217 Common settings keys:
2218
2219 - `theme` (`system`, `terminal`, `underwater`, `underwater-retro`,
2220 `shoreline`, `shoreline-light`, `dark`, `light`, `grayscale`,
2221 `catppuccin-mocha`, `tokyo-night`, `dracula`, `gruvbox-dark`, `claude`,
2222 `matrix`, `solarized-light`, `uwu`; default `underwater`): `underwater` is
2223 the dark navy fresh-install default, `shoreline` is its warm charcoal
2224 alternative and `shoreline-light` the light variant, `system` follows terminal
2225 background detection, `dark`/`light` use the Codewhale Whale pair,
2226 `terminal` inherits the host terminal, `grayscale` is the low-opinion
2227 black/white theme, and the named community presets apply across the TUI.
2228 Aliases such as `whale`, `mono`, `black-white`, `tokyonight`, and `gruvbox`
2229 are accepted. In Whale, cobalt blue owns action/focus, seafoam owns live
2230 work, Signal Gold owns human decisions and the whale, coral owns warnings,
2231 rose owns danger, and green remains completed/verified.
2232 Text labels, markers, and motion policy carry the same states when color is
2233 unavailable; color is never the only cue.
2234 User-authored overlays live only at `~/.codewhale/themes/<name>.json` (or
2235 `$CODEWHALE_HOME/themes/<name>.json`) and are selected with
2236 `/theme custom:<name>`. The filename is a bounded slug, symlinks and files
2237 over 64 KiB are refused, colors must be `#RRGGBB`, and unknown fields fail
2238 validation. `/theme schema` prints the embedded JSON Schema and `/theme path`
2239 shows the exact directory. An overlay names one compiled `base` theme and
2240 changes only listed semantic colors; it cannot include or read another file.
2241 Open `/theme` to browse valid overlays, preview them live, and keep the
2242 active `custom:<name>` selector when the picker is opened without moving.
2243 - `auto_compact` (on/off, model-aware default on for known context windows
2244 unless explicitly configured)
2245 - `auto_compact_threshold_percent` (10-100, default `80`): pre-send
2246 auto-compaction threshold used only when `auto_compact` is enabled.
2247 - `bracketed_paste` asks the terminal to mark the start and end of pasted
2248 input. It accepts `true` (default) and `false`. Codewhale automatically
2249 disables this mode on the legacy Windows Console Host.
2250 - `paste_burst_detection` (on/off, default on): fallback rapid-key paste
2251 detection for terminals that do not emit bracketed-paste events. This is
2252 independent of terminal bracketed-paste mode.
2253 - `synchronized_output` lets the terminal present each TUI redraw as a single
2254 update to reduce flicker. The default, `auto`, disables synchronization on
2255 terminals with known compatibility issues, such as Ptyxis. `on` overrides
2256 the automatic fallback for normal redraws. Use `off` if the terminal flashes
2257 on redraw.
2258 - `work_surface_placement` (`bottom`, `top`, `left`, `right`, or `off`;
2259 default `bottom`): places the workbar — Tasks / To-do / Workers — under the
2260 composer (the default bottom workbar), above the transcript, in a side
2261 workbar, or hides it entirely (`off`). Side choices fall back to the top
2262 layout on narrow terminals without changing the saved preference. Set it
2263 live with `/config work_surface_placement right --save` (or `left` / `top` /
2264 `bottom` / `off`).
2265 - `rail_panel` (`tasks`, `agents`, `background`, `files`, `notepad`,
2266 `context`, `git`, `price`; default `tasks`, alias key `rail`): which panel
2267 the workbar shows. Panel selection is orthogonal to placement. `tasks` is
2268 the full live work list (to-dos, then sub-agents); `agents` narrows to the
2269 sub-agent rows; `background` lists background shells and automations;
2270 `files` lists touched files; `notepad` shows the workspace notes; `context`
2271 is a read-only session-facts list; `git` shows branch status; `price`
2272 shows cost. In every panel except `context`, rows are selectable and
2273 clickable and open their detail surface. `Alt+!`/`Alt+@`/`Alt+#`/`Alt+$`
2274 switch panels live.
2275 - `work_surface_top_height` (2–16) and `work_surface_side_width` (26–80):
2276 ceilings for the top strip's height and the side workbar's width. Both are
2277 normally persisted by dragging the divider rather than edited by hand; the
2278 strip still auto-fits its content below the ceiling.
2279 - `composer_density` (`compact`, `comfortable`, or `spacious`; default
2280 `comfortable`): vertical padding inside the composer.
2281 - `composer_border` (`true`/`false`; default `true`): draws the composer's
2282 border.
2283 - `thinking_highlight` (`true`/`false`; default `true`): fills the background
2284 behind model reasoning while `calm_mode` is off; calm mode, on by default,
2285 never fills it. The dashed reasoning rule stays when it is off.
2286 - `transcript_spacing` (`compact` or `spacious`; default `spacious`): blank
2287 lines between transcript entries.
2288 - `focus_texture` (`off`, `scrim`, or `grain`; default `off`): focus-context
2289 texture for modal views. `scrim` dims the already-rendered background
2290 outside the focused modal toward the theme surface; `grain` sprinkles
2291 sparse dots over blank cells there. The texture is static (no time
2292 component, so it is unaffected by `low_motion`), never writes over a cell
2293 that carries text, and preserves the 4.5:1 body-text contrast floor
2294 wherever both colors are resolvable. It is skipped entirely on frames
2295 below the ambient-life minimum size and when the focused modal already
2296 covers 90% or more of the frame. Set it live with
2297 `/config focus_texture scrim --save`.
2298 - `mention_menu_limit` (integer, default `128`): maximum number of
2299 `@`-mention popup candidates retained before the composer renders the
2300 visible window. The visible rows still depend on terminal height.
2301 - `mention_walk_depth` (integer, default `10`): maximum workspace depth for
2302 `@`-mention completion walks. Set to `0` for unlimited depth in deeply
2303 nested workspaces; keep the default in very large repos unless needed.
2304 - `mention_menu_behavior` (`fuzzy`, `browser`; default `fuzzy`): controls how
2305 `@`-mention completions are populated. `fuzzy` searches the workspace and
2306 applies mention frecency. `browser` lists only the immediate children of the
2307 currently typed directory segment in deterministic alphabetical order.
2308 - `show_thinking` (on/off, default on): shows model thinking in the transcript,
2309 live while it streams and collapsed under a `Thought for …` header once the
2310 answer starts. Off hides it; answers and tools stay visible. A value already
2311 saved in `settings.toml` is kept.
2312 - `thinking_default_expanded` (on/off, default off): renders thinking blocks
2313 expanded initially when `show_thinking` is enabled. Space still toggles the
2314 selected block, and it decides only the blocks you have not touched: a block
2315 you expanded or collapsed yourself keeps that state if you change this
2316 setting later. This is useful in SSH/tmux environments where the Space
2317 binding may be intercepted.
2318 - `thinking_preview_lines` (integer, default `2`): how many body rows a
2319 **collapsed** completed thought still shows. `0` is header-only; `10` is
2320 the older dump. Live streaming preview is unchanged. Expand a block with
2321 Space, or set `thinking_default_expanded` to open every block.
2322 - `help_expand_groups` (on/off, default off): start Help/shortcuts with every
2323 group expanded. Default folds the long tail (Grok-style); type-to-filter
2324 still unfolds matches.
2325 - `pin_last_prompt` (on/off, default on): pin the last user prompt at the top
2326 of the transcript viewport after it scrolls off.
2327 - `show_tool_details` (on/off)
2328 - `inline_diffs` (`full`, `summary`, or `off`; default `full`): controls the
2329 inline presentation of successful structured File mutations. `full` shows a
2330 bounded red/green diff and semantic statistics, `summary` keeps only the
2331 statistics, and `off` keeps the calm changed-file outcome. All three retain
2332 the exact applied change in the selected File receipt's Alt/Option+V detail.
2333 Failure and cancellation never render a successful diff. Save the choice
2334 with `/config inline_diffs <mode> --save`.
2335 - `locale` (`auto`, `en`, `ja`, `zh-Hans`, `zh-Hant`, `pt-BR`, `es-419`, `vi`,
2336 `ko`; default `auto`): UI chrome locale. `auto` checks `LC_ALL`,
2337 `LC_MESSAGES`, then `LANG`; unsupported locale selections resolve to English.
2338 Every shipped pack holds full `en.json` parity, so no string falls back
2339 to English. The runtime also exposes the resolved locale in the system
2340 prompt as the fallback natural language for V4 reasoning and replies when the
2341 latest user message is ambiguous. Clear user language still takes priority;
2342 Chinese turns should produce Chinese `reasoning_content` and Chinese final
2343 replies even when the resolved locale is English.
2344 - `background_color` (`#RRGGBB`, `RRGGBB`, or `default`): optional main TUI
2345 background color applied to the root, header, transcript, and footer
2346 surfaces while preserving panel contrast.
2347 - `cost_currency` (`usd`, `cny`; default `usd`): currency used by the footer,
2348 context panel, `/cost`, `/tokens`, and long-turn notification summaries. The
2349 aliases `rmb` and `yuan` normalize to `cny`.
2350 - `default_mode` (`agent` or `plan`; legacy values such as `normal` and `operate` load as `agent` and are not live mode vocabulary)
2351 - `permission_posture` (`ask`, `accept-edits`, `auto-review`, `full-access`; default `accept-edits` when unset). Explicit saved choices, including `ask` from earlier versions, are preserved on upgrade and restart.
2352 - `launch_screen` (legacy, migration-only): this historical `on`/`off` value
2353 is still accepted when reading an existing settings file, but it no longer
2354 changes behavior and is omitted from new saves. A fresh interactive launch
2355 always opens Tideline Startup; only an explicit resume or an explicit
2356 initial prompt enters the live session directly.
2357 - `sidebar_focus` (legacy, migration-only): the classic right sidebar this key
2358 configured was removed in the 0.9.4 rail unification. The key is still read
2359 once so old settings carry forward, then folds into the live keys:
2360 `pinned`/`work`/`plan`/`todos` become `rail_panel = "pinned"`,
2361 `agents`/`subagents` become `rail_panel = "agents"`, `context`/`session`
2362 become `rail_panel = "context"`, `tasks`/`auto` (the old default) become the
2363 `tasks` panel, `sessions` enables `sessions_rail`, and `hidden` turns the
2364 workbar off via `work_surface_placement = "off"`. An explicit `rail_panel`
2365 in the file always wins over the migrated value. Configure the workbar with
2366 `rail_panel` and `work_surface_placement`, not this key.
2367 - `sessions_rail` (`on`/`off`; default `off`): show the persistent Sessions
2368 list in the workbar. Rows list this workspace's recent
2369 non-archived sessions, newest first, with the active one marked; activating a
2370 row opens the session picker preselected on it (`/sessions open <id>`), so
2371 resume keeps its single implementation. Rows are projected from cached
2372 session metadata — the list never reads a transcript per frame, and never
2373 contacts a provider.
2374 - `session_auto_resume` (`on`/`off`; default `off`): reattach to this
2375 workspace's most recent session when Codewhale starts. Off by default so
2376 plain `codewhale` keeps starting fresh. `--resume`, `--continue`, and
2377 `--fresh` always take precedence. When it is on, startup still refuses to
2378 resume a session that is archived, fails to load, or is recorded against a
2379 different workspace; each of those falls back to a fresh transcript and says
2380 which session was skipped and why. It applies to the interactive launch only
2381 — `codewhale "<prompt>"` and `codewhale exec` are never silently prefixed
2382 with a prior conversation.
2383 - `max_input_history` (number of submitted input history entries; cleared
2384 drafts are also kept locally for composer history search). Note the spelling:
2385 the serde field on disk is `max_input_history`
2386 (`crates/tui/src/settings.rs:426`, default 100). `max_history` is the key
2387 name accepted by `/config set` and `settings.set()` (`settings.rs:1388`), not
2388 a settings.toml key — writing `max_history` into the file is silently
2389 ignored.
2390 - `default_model` (model name override)
2391
2392 `/task digest` (alias `/tasks digest`) renders the canonical Work Graph
2393 operations and four-state To-do list as plain text, running work first. It
2394 reads the same snapshots as the styled Work surface and owns no parallel
2395 progress state.
2396
2397 Plan and Work are the two modes in the UI. Switch between them with `/mode` or
2398 the `Shift+Tab` permission dial, where Plan sits between Accept Edits and
2399 Auto-Review. The retired `operate` spelling still parses, as Work, and says so
2400 once. For compatibility, older settings files with
2401 `default_mode = "normal"` still load as `agent`.
2402
2403 Localization scope is tracked in [LOCALIZATION.md](LOCALIZATION.md). The core
2404 pack covers high-visibility TUI chrome only; provider/tool schemas,
2405 personality prompts, and full documentation remain English unless explicitly
2406 translated later.
2407
2408 Readability semantics:
2409
2410 - Selection uses a unified style across transcript, composer menus, and modals.
2411 - Footer hints use a dedicated semantic role (`FOOTER_HINT`) so hint text stays readable across themes.
2412
2413 ### Token Quantities and Drivers
2414
2415 DeepSeek V4 prefix caching makes token labels matter. These quantities are kept
2416 separate:
2417
2418 | Quantity | Meaning | Allowed to drive |
2419 |---|---|---|
2420 | Active request input estimate | Conservative estimate of the next request's live system prompt and transcript payload. | Header/footer context percent, auto-compaction trigger, opt-in Flash seam trigger, and emergency overflow preflight. |
2421 | Reserved response headroom | The effective request cap plus `1024` safety tokens. Normal no-override requests start at `65536`; a smaller route/provider ceiling narrows that value, and an explicit output override raises it only within the resolved route window and output ceiling. The identical cap reaches the wire and drives preflight, except on a route that states an output limit above half its known context window with no explicit output override: there compaction aims to keep a quarter of the window free (at most `65536`, and never more than the request cap), preflight refuses a request only when fewer than `128` output tokens would fit, and every request's `max_tokens` is what the window has left after that request's estimated input and the `1024` safety tokens, never above the request cap. Reasoning effort does not add a second hidden reservation. A separately published route input ceiling independently clamps the spendable input budget. | Emergency overflow budget checks only. |
2422 | Cumulative API usage | Provider-reported input plus output tokens summed across completed API calls; multi-tool turns may count the same stable prefix more than once. | Session usage and approximate cost telemetry only. |
2423 | Prompt cache hit/miss | Provider cache telemetry for the most recent call when available. | Cache-hit display and cost estimation only; never compaction or seam triggers. |
2424 | Context percent | Active request input estimate divided by the model context window. | Display only; it mirrors the active-input basis used by context safeguards. |
2425 | Cost estimate | Approximate spend from provider usage and configured DeepSeek rates. | Display only. |
2426
2427 For known context-window models, including 1M-class V4 models, replacement
2428 compaction is enabled by default unless the user explicitly configures
2429 `auto_compact = false`. It fires at the active model's compaction threshold and
2430 replaces old history with recent user context followed by one ordinary
2431 checkpoint message. The standing system prompt remains unchanged. Unknown model
2432 ids remain opt-in.
2433
2434 ### Command Migration Notes
2435
2436 If you are upgrading from older releases:
2437
2438 - Old: `/codewhale`
2439 New: `/links` (aliases: `/dashboard`, `/api`)
2440 - Old: `/set model deepseek-reasoner`
2441 New: `/config` and edit the `model` row to `deepseek-v4-pro` or `deepseek-flash`
2442 - Old: visible `Normal` mode or `default_mode = "normal"`
2443 New: use `Agent` / `default_mode = "agent"`; legacy `normal` still maps to `agent`
2444 - Old: discover `/set` in slash UX/help
2445 New: use `/settings` for the typed editor, `/settings text` for a read-only
2446 listing, and `/config <key> <value>` for one key
2447
2448 ## Key Reference
2449
2450 ### Kimi Code membership model IDs
2451
2452 The exact `https://api.kimi.com/coding/v1` endpoint accepts `k3`, `k3-256k`,
2453 `kimi-for-coding`, and `kimi-for-coding-highspeed`. Use `k3-256k` for a fixed
2454 262,144-token K3 window; use bare `k3` with `context_window = 1048576` only
2455 when the membership plan includes the 1M entitlement. Both K3 ids use the same
2456 reasoning contract, and all four membership ids omit generic sampling fields.
2457
2458 ### Core keys (used by the TUI/engine)
2459
2460 - `provider` (string, optional): `deepseek` (default), `deepseek-anthropic`, `nvidia-nim`, `openai`, `atlascloud`, `wanjie-ark`, `volcengine`, `openrouter`, `xiaomi-mimo`, `novita`, `fireworks`, `siliconflow`, `arcee`, `siliconflow-CN`, `moonshot`, `sglang`, `vllm`, `ollama`, `ollama-cloud`, `huggingface`, `modelscope`, `together`, `qianfan`, `openai-codex`, `anthropic`, `openmodel`, `zai`, `stepfun`, `minimax`, `deepinfra`, `sakana`, `longcat`, `opencode-go`, `meta`, `mistral`, `telecomjs`, `xai`, `orcarouter`, `modelstudio-token-plan`, `google`, `edenai`, or `custom`. Legacy `deepseek-cn` configs are still accepted as an alias for `deepseek`; DeepSeek uses the same official host [`https://api.deepseek.com`](https://api-docs.deepseek.com/) worldwide. `deepseek-anthropic` targets DeepSeek's Anthropic Messages-compatible endpoint at `https://api.deepseek.com/anthropic` using `DEEPSEEK_API_KEY`; `nvidia-nim` targets NVIDIA's NIM-hosted DeepSeek endpoints through `https://integrate.api.nvidia.com/v1`; `openai` targets a generic OpenAI-compatible endpoint, defaulting to `https://api.openai.com/v1`; `atlascloud` targets AtlasCloud's OpenAI-compatible endpoint at `https://api.atlascloud.ai/v1`; `wanjie-ark` targets Wanjie Ark's OpenAI-compatible endpoint at `https://maas-openapi.wanjiedata.com/api/v1`; `volcengine` targets Volcengine Ark's OpenAI-compatible coding endpoint at `https://ark.cn-beijing.volces.com/api/coding/v3`; `openrouter` targets `https://openrouter.ai/api/v1`; `xiaomi-mimo` targets Xiaomi MiMo's OpenAI-compatible endpoint, using `https://token-plan-sgp.xiaomimimo.com/v1` by default for Token Plan keys (`tp-...`) and `https://api.xiaomimimo.com/v1` for pay-as-you-go keys. For Token Plan accounts outside the Singapore default, set `base_url` explicitly or use `mode = "token-plan-cn"` for China and `mode = "token-plan-ams"` for Europe/Amsterdam; `novita` targets `https://api.novita.ai/openai/v1`; `fireworks` targets `https://api.fireworks.ai/inference/v1`; `siliconflow` targets SiliconFlow, defaulting to `https://api.siliconflow.com/v1`; `arcee` targets Arcee AI's OpenAI-compatible endpoint at `https://api.arcee.ai/api/v1`; `siliconflow-CN` targets the SiliconFlow China regional endpoint through `[providers.siliconflow_cn]`; `moonshot` targets Moonshot/Kimi, defaulting to `https://api.moonshot.ai/v1`; `sglang` targets a self-hosted OpenAI-compatible endpoint, defaulting to `http://localhost:30000/v1`; `vllm` targets a self-hosted vLLM OpenAI-compatible endpoint, defaulting to `http://localhost:8000/v1`; `ollama` targets Ollama's OpenAI-compatible endpoint, defaulting to `http://localhost:11434/v1`; `huggingface` targets Hugging Face Inference Providers at `https://router.huggingface.co/v1`; `modelscope` targets ModelScope's OpenAI-compatible inference API at `https://api-inference.modelscope.cn/v1`; `together` targets Together AI at `https://api.together.xyz/v1`; `qianfan` targets Baidu Qianfan at `https://api.baiduqianfan.ai/v1`; `openai-codex` targets official ChatGPT plan inference with Codewhale-owned OAuth at `https://api.openai.com/v1`; `anthropic` targets Claude's native Messages API; `openmodel` targets OpenModel's Anthropic-compatible Messages API at `https://api.openmodel.ai`; `zai` targets Z.ai at `https://api.z.ai/api/coding/paas/v4`; `stepfun` targets StepFun at `https://api.stepfun.ai/v1`; `minimax` targets MiniMax at `https://api.minimax.io/v1`; `deepinfra` targets DeepInfra at `https://api.deepinfra.com/v1/openai`; `sakana` targets Sakana AI Fugu at `https://api.sakana.ai/v1`; `longcat` targets Meituan LongCat at `https://api.longcat.chat/openai/v1`; `opencode-go` targets the subscription-backed OpenCode Go model-aware route (Chat Completions, Responses, or Messages according to the documented model) at `https://opencode.ai/zen/go/v1`; `meta` targets Meta Model API; `mistral` targets Mistral AI's OpenAI-compatible endpoint at `https://api.mistral.ai/v1`; `telecomjs` targets TelecomJS TokenHub at `https://aigw.telecomjs.com/v1`; and `xai` targets xAI's API-key or OAuth route.
2461 - `opencode-zen` (string provider value): selects the model-aware OpenCode Zen gateway through `[providers.opencode_zen]`. The default base URL is `https://opencode.ai/zen/v1`, the default model is `gpt-5.6`, and credentials come from `api_key`, `OPENCODE_ZEN_API_KEY`, or fallback `OPENCODE_API_KEY`—never ChatGPT/Codex OAuth. `OPENCODE_ZEN_BASE_URL` and `OPENCODE_ZEN_MODEL` are accepted. The selected model's wire comes from the curated Zen snapshot, then from the AI SDK package its Models.dev `opencode` row names (refresh with `codewhale models --update`): GPT, Grok, and Muse Spark use Responses; Claude and most Qwen rows use Anthropic Messages; DeepSeek, MiniMax, GLM, Kimi, `qwen3.8-max`, and the free rows use Chat Completions. Gemini, Models.dev rows marked `deprecated`, and models no loaded catalog lists fail closed because Codewhale has no proven supported wire contract for them. See the exact current model groups in [`PROVIDERS.md`](PROVIDERS.md#opencode-zen-protocol-catalog).
2462 - `minimax-anthropic` (string provider value): selects MiniMax's Anthropic-compatible Messages route through `[providers.minimax_anthropic]`. The default Base URL is `https://api.minimax.io/anthropic`; set `https://api.minimaxi.com/anthropic` for China. Keep the `/anthropic` suffix because Codewhale appends `/v1/messages`. The route uses `MINIMAX_API_KEY` and defaults to `MiniMax-M3`; `MiniMax-M2.7` is also registered. Official M3 input modalities are text, image, and video, with adaptive or disabled thinking. M2.7 is text-only and always keeps thinking enabled.
2463 - `api_key` (string, required for hosted providers): must be non-empty for DeepSeek/hosted providers (or set the provider API key env var). Self-hosted SGLang, vLLM, and local `ollama` can omit it. `ollama-cloud` requires a key saved for that provider or supplied by `OLLAMA_CLOUD_API_KEY`, then `OLLAMA_API_KEY`.
2464 - `auth_mode` (string, optional provider-table key): selects a provider-specific authentication contract. Kimi Code membership uses `auth_mode = "api_key"` (or omit the field), a key created in the [Kimi Code console](https://www.kimi.com/code/console), `base_url = "https://api.kimi.com/coding/v1"`, and bare `model = "k3"` for K3. Codewhale gives that route a safe 262,144-token baseline; set `context_window = 1048576` only when the Kimi Code plan includes 1M access (Allegretto and above). `k3[1m]` is a Claude Code-only convention, not an API model ID, and Codewhale rejects it instead of silently changing the wire model or assuming an entitlement. `model = "kimi-for-coding"` remains the valid K2.7 compatibility route available to all Kimi Code members. Legacy `auth_mode = "kimi_oauth"` fails closed with API-key guidance and never probes, reads, refreshes, or rewrites `kimi_cli`/`kimi_code_cli` credential files. First-class OAuth requires Codewhale's own vendor-registered client identity and remains tracked in #4417.
2465 - `base_url` (string, optional, `[providers.<name>]` key; see [Legacy top-level `base_url` and `api_key`](#legacy-top-level-base_url-and-api_key) for the older top-level spelling): defaults to `https://api.deepseek.com/beta` for DeepSeek's OpenAI-compatible Chat Completions API, including legacy `provider = "deepseek-cn"` configs. Other defaults are `https://api.deepseek.com/anthropic` for `deepseek-anthropic`, `https://integrate.api.nvidia.com/v1` for `nvidia-nim`, `https://api.openai.com/v1` for `openai`, `https://api.atlascloud.ai/v1` for `atlascloud`, `https://maas-openapi.wanjiedata.com/api/v1` for `wanjie-ark`, `https://ark.cn-beijing.volces.com/api/coding/v3` for `volcengine`, `https://openrouter.ai/api/v1` for `openrouter`, `https://token-plan-sgp.xiaomimimo.com/v1` for `xiaomi-mimo` when the API key starts with `tp-...` and `https://api.xiaomimimo.com/v1` otherwise, `https://api.novita.ai/openai/v1` for `novita`, `https://api.fireworks.ai/inference/v1` for `fireworks`, `https://api.siliconflow.com/v1` for `siliconflow`, `https://api.siliconflow.cn/v1` for `siliconflow-CN`, `https://api.arcee.ai/api/v1` for `arcee`, `https://api.moonshot.ai/v1` for `moonshot`, `https://api.minimax.io/v1` for `minimax`, `https://api.openmodel.ai` for `openmodel`, `https://api.z.ai/api/coding/paas/v4` for `zai`, `https://api.stepfun.ai/v1` for `stepfun`, `https://api.deepinfra.com/v1/openai` for `deepinfra`, `https://api.sakana.ai/v1` for `sakana`, `https://router.huggingface.co/v1` for `huggingface`, `https://api-inference.modelscope.cn/v1` for `modelscope`, `https://api.together.xyz/v1` for `together`, `https://api.baiduqianfan.ai/v1` for `qianfan`, `https://api.openai.com/v1` for `openai-codex`, `https://api.anthropic.com` for `anthropic`, `https://api.mistral.ai/v1` for `mistral`, `http://localhost:30000/v1` for `sglang`, `http://localhost:8000/v1` for `vllm`, `http://localhost:11434/v1` for `ollama`, and `https://ollama.com/v1` for `ollama-cloud`. Set `base_url = "https://token-plan-cn.xiaomimimo.com/v1"` for China-region Xiaomi MiMo Token Plan accounts or `base_url = "https://token-plan-ams.xiaomimimo.com/v1"` for Europe/Amsterdam accounts. Mistral-specific reasoning fields and polymorphic replay are enabled only on the documented first-party HTTPS `/v1` hosts; a custom Mistral base URL keeps generic Chat semantics. Set `https://api.deepseek.com` or `https://api.deepseek.com/v1` explicitly to opt out of DeepSeek beta features.
2466 - `ollama-cloud` route: select `provider = "ollama-cloud"`, configure `[providers.ollama_cloud]` when overriding the default `https://ollama.com/v1` / `gpt-oss:120b` tuple, and save a key from [Ollama account settings](https://ollama.com/settings/keys) with `codewhale auth set --provider ollama-cloud`. Ambient precedence is `OLLAMA_CLOUD_API_KEY`, then `OLLAMA_API_KEY`; arbitrary Ollama model IDs pass through unchanged.
2467 - Legacy Ollama Cloud migration: a released `provider = "ollama"` config whose normalized `[providers.ollama].base_url` is exactly `https://ollama.com/v1` is upgraded to the `ollama-cloud` runtime identity in memory. Only that exact tuple may read its old `ollama` provider table and secret slot. The config and secrets are never rewritten, and neighboring paths, HTTP downgrades, lookalike hosts, or an explicit `ollama-cloud` selection never consume the fallback.
2468 - `telecomjs` base URL and catalog: `[providers.telecomjs]` defaults to `https://aigw.telecomjs.com/v1`; `TELECOMJS_BASE_URL` overrides it. With `TELECOMJS_API_KEY`, `/models` refreshes a key-scoped catalog without mixing rows into another provider.
2469 - `edenai` gateway: select `provider = "edenai"`; `[providers.edenai]` defaults to `https://api.edenai.run/v3` and `deepseek/deepseek-v4-pro`. `EDENAI_API_KEY`, `EDENAI_BASE_URL`, and `EDENAI_MODEL` are accepted. Use `EDENAI_BASE_URL = "https://api.eu.edenai.run/v3"` for Eden AI's documented EU endpoint; the default `deepseek/deepseek-v4-pro` is only listed on the global catalog, so pair the EU endpoint with an EU-listed model such as `qwen/deepseek-v4-pro` via `EDENAI_MODEL` or `model`. The provider refreshes Eden AI's `/models` catalog, but leaves model-specific reasoning controls untouched because the gateway spans multiple model families.
2470 - `codewhale` (Codewhale API): select `provider = "codewhale"`; `[providers.codewhale]` defaults to `https://api.codewhale.net/v1` and `deepseek/deepseek-v4-pro`. The credential is a Codewhale account API key (`cwc_key_…`) with the `models:infer` scope, read from `CODEWHALE_API_KEY` or the `codewhale` secret-store slot; `codewhale account api-keys create --name <name> --use` mints one and saves it locally. `CODEWHALE_API_BASE` overrides the origin and must be HTTPS except on loopback. The model catalog is the account's own authenticated `GET /v1/models`: ids are `provider/model` and each row states its wire (`chat-completions` → `/v1/chat/completions`, `anthropic-messages` → `/v1/messages`, `responses` → `/v1/responses`). Connect the underlying provider keys with `codewhale account keys set <provider>`.
2471 - `concentrate` gateway: select `provider = "concentrate"`; `[providers.concentrate]` defaults to `https://api.concentrate.ai/v1` and `deepseek-v4-pro` over the OpenAI Responses wire. `CONCENTRATE_API_KEY`, `CONCENTRATE_BASE_URL`, and `CONCENTRATE_MODEL` are accepted. Model ids pass through verbatim (`gpt-5.6-sol`, `openai/gpt-5.6-sol`, or `concentrate/auto` for the gateway router). BYOK only; see [PROVIDERS.md](PROVIDERS.md#concentrate-notes).
2472 - `mistral` model and reasoning contract: `[providers.mistral]` defaults to `mistral-code-latest`; `MISTRAL_MODEL` overrides it and the generic `CODEWHALE_MODEL` override wins when both are set. The current picker also lists `mistral-medium-latest`, `mistral-small-latest`, and `mistral-large-latest`. On exact first-party HTTPS `/v1` routes, Medium and Small accept only `reasoning_effort = "none" | "high"` and replay polymorphic thinking blocks. Deprecated native Magistral IDs may still be configured explicitly, remain always-reasoning, and never receive the adjustable effort field.
2473 - `context_window` (integer, optional provider-table key): override the total context window for the active `[providers.<name>]` route when an OpenAI-compatible gateway, hosted model alias, or self-hosted runtime has a different limit than Codewhale's static model table. For example, `[providers.openai] context_window = 1000000` lets an OpenAI-compatible DashScope/Qwen route budget against a 1M-token window instead of the conservative fallback. For Kimi Code K3, keep `model = "k3"` and set `[providers.moonshot] context_window = 1048576` only when the membership plan includes 1M access; otherwise omit it to retain the 262,144-token safe baseline. The value must be greater than 0 and affects prompt context notes, compaction thresholds, context-pressure checks, and request output caps. Full resolution order, and how to see which rung produced the current window: [Context length (context window)](#context-length-context-window).
2474 - `path_suffix` (string, optional provider-table key): override the chat-completions path for OpenAI-compatible gateways that do not serve `/v1/chat/completions`. For example, `[providers.openai] path_suffix = "/chat/completions"` sends chat requests to the unversioned base URL plus `/chat/completions`; `models` and `beta/*` requests keep their normal routing.
2475 - `reasoning_stream_style` (string, optional provider-table key): override how streaming reasoning is separated from answer text for the active provider route. Use `separate_field` for `reasoning_content` / `reasoning` deltas, `inline_tags` for gateways that stream `<think>...</think>` inside `delta.content`, or `none` to render incoming content exactly as answer text. When unset, every Chat Completions route uses `separate_field` (Mistral's first-party route uses its typed thinking blocks); set `none` only for a gateway that streams its answer inside `reasoning_content`.
2476 - `[providers.<name>.auth]` (table, optional): provider-scoped auth source metadata. `source = "command"` stores a command argv plus optional `timeout_ms`; `source = "secret"` stores a `secret_id`. This slice lets provider readiness, `/provider`, and doctor JSON report the auth source class without exposing command argv output or secret values; executing commands and resolving external secret material is handled by the follow-up resolver work.
2477 - `insecure_skip_tls_verify` (bool, optional provider-table key): legacy compatibility key, disabled by default. When true on the active provider table, provider clients reject the configuration instead of skipping TLS certificate verification. Use `SSL_CERT_FILE` for corporate or private CA bundles; `codewhale doctor` reports stale uses of this setting.
2478 - `default_text_model` (string, optional): defaults to `deepseek-flash` for DeepSeek and `deepseek-anthropic`, `gpt-5.6` for OpenAI, `grok-4.7` for xAI, `deepseek-ai/deepseek-v4-pro` for NVIDIA NIM, `deepseek-ai/deepseek-v4-flash` for AtlasCloud, `deepseek-reasoner` for Wanjie Ark, `DeepSeek-V4-Pro` for Volcengine Ark, `deepseek/deepseek-v4-pro` for OpenRouter and Novita, `mimo-v2.6-pro` for Xiaomi MiMo, `accounts/fireworks/models/deepseek-v4-pro` for Fireworks, `deepseek-ai/DeepSeek-V4-Pro` for SiliconFlow and DeepInfra, `trinity-large-thinking` for Arcee AI, `kimi-k2.7-code` for Moonshot, `MiniMax-M3` for MiniMax, `GLM-5.3` for Z.ai, `step-3.7-flash` for StepFun, `ernie-4.0-turbo-8k` for Qianfan, `fugu` for Sakana AI, `deepseek-ai/DeepSeek-V4-Pro` for SGLang/vLLM, no fixed id for local Ollama (Codewhale adopts a chat-capable tag from the live local catalog — coder or tool-capable tags first, then the largest context — and never an embedding or reranker model), and `gpt-oss:120b` for Ollama Cloud. Hugging Face and Together AI both default to `deepseek-ai/DeepSeek-V4-Pro`; `openai-codex` defaults to `gpt-6.1-sol`; `anthropic` defaults to `claude-sonnet-5-5`; `openmodel` defaults to `deepseek-v4-flash`. Current public DeepSeek IDs include `deepseek-v4-pro` and `deepseek-flash` (V4.1 Flash, shipped as the unversioned id), both with 1M context windows, 384K max output, and thinking mode enabled by default. DeepSeek's live pricing/model page now labels the Pro backend `DeepSeek-V4-Pro-0813`; the callable API ID remains `deepseek-v4-pro`, so Codewhale does not send the backend label or the Claude Code-specific `deepseek-v4-pro[1m]` selector. DeepSeek retired `deepseek-chat` and `deepseek-reasoner` on July 24, 2026; direct first-party routes migrate both to `deepseek-flash`, with omitted reasoning settings preserving their former non-thinking (`off`) and thinking (`high`) intent. DeepSeek has also retired the `deepseek-v4-flash` and `deepseek-v4-flash-vision-exp` models: it still accepts both names, serves them with V4.1 Flash, and bills them at the `deepseek-flash` price, which Codewhale applies to turns from 2026-09-10 04:00 UTC. The `flash`, `deepseek-v4flash`, `flash-vision`, and `deepseek-v4flashvisionexp` shorthands select `deepseek-flash`. Explicit `reasoning_effort` wins, and provider-owned ids on Wanjie Ark, aggregators, self-hosted runtimes, and custom endpoints are not globally rewritten. SiliconFlow retains its own mapping: `deepseek-reasoner` and `deepseek-r1` select its Pro model while `deepseek-chat` and `deepseek-v3` select Flash. Provider-specific mappings translate `deepseek-v4-pro` / `deepseek-v4-flash` to each provider's model ID where supported. OpenRouter also recognizes recent large IDs such as `arcee-ai/trinity-large-thinking`, `minimax/minimax-m3`, `minimax/minimax-m2.7`, `xiaomi/mimo-v2.5-pro`, `qwen/qwen3.6-flash`, `qwen/qwen3.6-35b-a3b`, `qwen/qwen3.6-max-preview`, `qwen/qwen3.6-27b`, `qwen/qwen3.6-plus`, `qwen/qwen3.7-max`, `google/gemma-4-31b-it`, `moonshotai/kimi-k2.7-code`, `moonshotai/kimi-k2.6`, `nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free`, and `nvidia/nemotron-3-ultra-550b-a55b`; direct Arcee uses bare IDs such as `trinity-large-thinking` and `trinity-large-preview`; direct Moonshot recognizes `kimi-k3`, `kimi-k2.7-code`, and `kimi-k2.6`. The exact Kimi Code endpoint recognizes bare `k3` for K3 and `kimi-for-coding` for K2.7; those membership IDs are distinct from the direct Moonshot IDs and are never rewritten across routes. Direct MiniMax recognizes `MiniMax-M3` and the documented M2.x chat model IDs; direct Z.ai recognizes `GLM-5.3` (the default), `GLM-5.2`, `GLM-5.1`, and `GLM-5-Turbo`, and OpenRouter recognizes the matching `z-ai/glm-5.1`, `z-ai/glm-5.2`, `z-ai/glm-5.3`, and `z-ai/glm-5-turbo` IDs — `GLM-5.3` has been live on the Z.ai Coding Plan since 2026-08-13; it inherits its catalog metadata from `GLM-5.2` until Z.ai publishes distinct 5.3 numbers and carries no price, and an explicit `GLM-5.2` selection keeps its own id; direct Sakana recognizes `fugu` and `fugu-ultra-20260615`; direct Xiaomi MiMo recognizes chat IDs `mimo-v2.6-pro`, `mimo-v2.6-flash`, and `mimo-v2.5-pro-ultraspeed` (the retired `mimo-v2.5-pro` and `mimo-v2.5` are sent as `mimo-v2.6-pro` and `mimo-v2.6-flash`), while TTS IDs are selected through `codewhale speech` / `tts`. Per-provider model ID policies (`catalog`, `strict`, `roster`, `verbatim`), stripped prefixes, aliases, vendor `wire_slugs`, and the rule that any non-`roster` provider with a custom `base_url` preserves explicit model IDs verbatim are owned by `resolve_model` and documented in [`MODELS_AND_PROVIDERS.md`](MODELS_AND_PROVIDERS.md). Use `/models` or `codewhale models` to discover live IDs from your configured endpoint. `CODEWHALE_MODEL` overrides this for a single process; `DEEPSEEK_MODEL` is the legacy alias.
2479 - TelecomJS uses `deepseek-v4-pro` only as a conservative pre-refresh fallback. Once its key-scoped `/models` catalog is available, the picker uses those live rows; Codewhale omits unsupported reasoning request fields on this route.
2480 - `reasoning_effort` (string, optional): `auto`, `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `ultra` (`ultracode` is an alias of `ultra`), or `max`; defaults to the configured UI tier. DeepSeek Platform receives top-level `thinking` / `reasoning_effort` fields. Ollama Cloud's OpenAI-compatible Chat Completions route preserves its documented `none` / `low` / `medium` / `high` / `max` ladder (`off` is sent as `none`; `xhigh` and `ultracode` normalize to `max`). Direct xAI `grok-4.7` and `grok-4.6` on exact `https://api.x.ai/v1` receive top-level `reasoning_effort = "low" | "medium" | "high" | "xhigh"` (the ladder comes from the bundled catalog row; `grok-4.5` maps `xhigh` to `high`, and rows without a documented effort such as `grok-4.3` get no field); Grok reasoning cannot be disabled, so `off` normalizes to `high`, `max`/`ultracode` to `xhigh`, and `auto` leaves the field omitted so xAI's documented default `high` applies. A custom xAI-compatible `base_url` does not inherit that dialect. Direct Moonshot `kimi-k3` on exact `https://api.moonshot.ai/v1` is always-thinking and receives only top-level `reasoning_effort = "low" | "high" | "max"`; `off` normalizes to `low`, and `medium` to `high`. Kimi Code membership `k3` on exact `https://api.kimi.com/coding/v1` instead receives nested `thinking.effort`, and its `off` setting also normalizes to enabled `low`. Normal dispatched `auto` uses Codewhale's auto-reasoning selector and sends a concrete route-normalized tier; only an omitted reasoning setting leaves the provider default in control. Neighboring gateways and model/endpoint combinations retain the generic Moonshot contract. OpenAI Codex normalizes stale `off` to `low` and sends `max` / `ultracode` as Responses `xhigh`. Z.ai receives documented `thinking` controls and treats enabled thinking as the GLM coding high/max lane. NVIDIA NIM receives equivalent settings through `chat_template_kwargs`.
2481 - `verbosity` (string, optional): `normal` or `concise`. `normal` keeps the
2482 default conversational prompt. `concise` appends a prompt discipline block
2483 for direct, low-chatter output; CLI noninteractive commands (`exec` and
2484 `eval`) default to `concise` unless config/env/CLI overrides it.
2485 Override per process with `CODEWHALE_VERBOSITY` or the legacy
2486 `DEEPSEEK_VERBOSITY` alias.
2487 - `telemetry` (bool, optional): anonymous usage counting, **`true` by default**.
2488 Notice version `6` names Codewhale as the sole first-party collector
2489 and describes the opt-out policy; no acceptance is invented for a default
2490 user. Existing explicit declines remain off. An explicit `false` here is the
2491 durable *opt-out*: it deletes the random install id, truncates buffered and
2492 dry-run events, and leaves a tombstone reasserted while the setting is false.
2493 It is a floor: `--telemetry true` and `CODEWHALE_TELEMETRY=1` lose to it.
2494 Use `/settings` or `codewhale config set telemetry true` to turn counting
2495 back on explicitly for new sessions through the existing privacy transition. `CODEWHALE_TELEMETRY`
2496 (legacy alias `DEEPSEEK_TELEMETRY`) and `--telemetry false` provide a run-scoped
2497 kill switch that stops collection and delivery without erasing the owner's
2498 state. A repo-local `.codewhale/config.toml` cannot set this preference.
2499 `codewhale config telemetry` shows the disclosure; `codewhale config get
2500 telemetry` reports preference and privacy status. Full schema and opt-out
2501 behavior: [`TELEMETRY.md`](TELEMETRY.md).
2502 - `telemetry_endpoint` (string, optional): where batches are POSTed. Leaving it
2503 unset selects the shipped default,
2504 **`https://telemetry.codewhale.net/v1/telemetry`** — the first-party ingest
2505 service described in [`TELEMETRY.md`](TELEMETRY.md), whose source is in
2506 `telemetry-ingest/`. This key decides only *where* a permitted session sends;
2507 it cannot override an opt-out. Setting it
2508 to the **empty string** is how you stay enabled and contact nobody: each batch
2509 is then written to `$CODEWHALE_HOME/telemetry/dryrun.jsonl` and no HTTP client
2510 is constructed at all, so you can read exactly what would have been sent. Any
2511 other value replaces the default outright. `https://` is required; plain
2512 `http://` is accepted only for loopback hosts, and there is no environment
2513 variable that overrides that refusal. A rejected endpoint turns telemetry off
2514 for the run rather than falling back to plaintext or to the default. Override
2515 per process with `CODEWHALE_TELEMETRY_ENDPOINT` (legacy alias
2516 `DEEPSEEK_TELEMETRY_ENDPOINT`), where an empty value means the same "contact
2517 nobody". A repo-local `.codewhale/config.toml` cannot set it.
2518 - `allow_shell` (bool, optional): in interactive TUI Agent sessions, omitting
2519 this keeps shell tools available with approval prompts; setting it to `false`
2520 hides shell tools. Headless, durable-task, and other noninteractive profiles
2521 keep the conservative omitted-field default and require `allow_shell = true`
2522 to expose shell. Plan mode always hides shell; Full Access enables shell and
2523 auto-approval.
2524 - `approval_policy` (string, optional): `on-request`, `untrusted`, `accept-edits`, or `never`. Runtime `approval_mode` editing in `/config` also accepts `on-request` and `untrusted` aliases. A project file may set only a value that tightens the user's posture; the order from loosest is `auto`, `accept-edits`, `on-request`, `never`.
2525 - `[approval] default_selection` (string, optional): which control the
2526 terminal approval bar highlights when it first appears — `allow_once`
2527 (default) or `deny`. Enter commits the highlighted control, which is tagged
2528 `[Enter]`, so by default Enter allows the one action shown, once; `n` denies
2529 and `Esc` refuses the action and stops the turn. An Enter that would allow
2530 is ignored, with a notice saying so, for the first three quarters of a
2531 second after the bar becomes the prompt in front and straight after another
2532 Enter or typed characters, so an Enter in flight, held or pasted does not
2533 approve. The letter keys (`y`, `a`, `1`) are not delayed. Set `deny` to make Enter refuse the call instead
2534 (the earlier default, #5293); `y` still allows once. It moves the
2535 highlight only: which calls are prompted for is still `approval_policy`
2536 plus the rules in `permissions.toml`. The sandbox elevation prompt is not
2537 affected and still starts on the option that skips the call.
2538
2539 ```toml
2540 [approval]
2541 default_selection = "deny"
2542 ```
2543 - `[approval] timeout_seconds` (integer, optional): bound how long an
2544 approval may wait — the TUI card and the Runtime API approvals the desktop
2545 app and web use alike. When the window elapses the call is refused
2546 (fail-closed) and recorded as a timeout, not as the operator's denial.
2547 Omitted or `0` waits indefinitely, which is the default everywhere: no
2548 approval is ever denied on your behalf unless you set this. Values above
2549 24h clamp with a warning (#6101).
2550
2551 ```toml
2552 [approval]
2553 timeout_seconds = 300
2554 ```
2555 - `sandbox_mode` (string, optional): `read-only`, `workspace-write`, `danger-full-access`, `external-sandbox`.
2556 The value can only narrow the sandbox the permission mode picks (Full
2557 Access: no wrapper; Ask, Accept Edits and Auto-Review: `workspace-write`; Plan:
2558 `read-only`), so `danger-full-access` and `external-sandbox` take effect
2559 only in Full Access (`yolo`).
2560 Platform support is not identical. macOS uses Seatbelt when its runtime
2561 probe succeeds. Linux uses bubblewrap by default whenever `/usr/bin/bwrap`
2562 is installed and a probe proves it can confine a child; `prefer_bwrap =
2563 false` opts out and reports no OS command sandbox. If an installed
2564 launcher fails that probe, a `workspace-write` posture refuses the command
2565 instead of running it unwrapped; the refusal names the launcher's
2566 diagnostic. `read-only` keeps its existing rule: arbitrary commands require
2567 native enforcement, while the separately hardened allowlisted argv may run
2568 without it. Windows does not currently advertise an OS sandbox; its planned helper contract starts
2569 with process-tree containment only and must not be described as read-only
2570 filesystem isolation, workspace-write enforcement, network blocking,
2571 registry isolation, or AppContainer isolation until those are implemented.
2572 - The cross-layer relationship between mode admission, hooks, registered tool
2573 requirements, typed rules, auto-review, repo law, human approval, and the
2574 execution sandbox is defined in
2575 [Authorization order](AUTHORIZATION_ORDER.md).
2576 - **Read deny-list.** Every sandbox posture (`read-only` included) grants
2577 read access to the whole filesystem; the postures differ in what they may
2578 *write* and whether they may reach the network. The read deny-list narrows
2579 that, in two scopes. Codewhale's own read-side tools (`read_file`, `list_dir`,
2580 `file_search`, `grep_files`, `read_media`, `image_ocr`, `pandoc`,
2581 `validate_data`, `verify`, `review`, `rlm_open` and the read in `fim_edit`)
2582 refuse every listed path; `write_file`, `edit_file` and `apply_patch` do not
2583 check it. A sandboxed shell
2584 command refuses only the *key material and other-principal* entries: SSH and
2585 GPG keys, `/etc/shadow`, `/etc/sudoers`, system and login keychains, browser
2586 profiles, other agents' credential stores, Codewhale's own secret stores,
2587 runtime daemon sockets, and anything in `sandbox_denied_read_paths`. Full
2588 Access with its default `danger-full-access` sandbox (not a narrower configured
2589 `sandbox_mode`), `external-sandbox` and a missing wrapper run
2590 shell commands without the local sandbox wrapper, so the read deny-list does
2591 not stop shell reads there. A tool's own auth
2592 config is refused to the model but stays readable to the tool: `gh` cannot
2593 start without `~/.config/gh/hosts.yml`, so denying it to the process would
2594 disable the CLI without keeping its token out of reach.
2595 - `sandbox_read_denylist_defaults` (bool, default `true`): apply the built-in
2596 credential-store set — `~/.ssh`, `~/.gnupg`, cloud credential directories
2597 (`~/.aws`, `~/.config/gcloud`, `~/.azure`, `~/.kube`, …), `~/.netrc`,
2598 `~/.npmrc`, `~/.git-credentials`, macOS keychains, browser profiles,
2599 Codewhale's own secret stores, and `.env` files (but not `.env.example`
2600 and friends). Ordinary source, `Cargo.toml`, `~/.gitconfig`, `~/.cargo`,
2601 and `~/.npm` stay readable so builds and tests still work. Set `false` to
2602 restore the pre-0.9.12 full-disk-read behavior.
2603 - `sandbox_denied_read_paths` (list of paths): additional denied subpaths.
2604 `~` expands. These can never be exempted.
2605 - `sandbox_read_denylist_exempt` (list of paths): subtract a path from the
2606 *built-in defaults* when a project genuinely needs it. Deny wins over
2607 allow: this never reopens anything in `sandbox_denied_read_paths`.
2608
2609 Exemption granularity is **whole-rule**, not per-file. An exempt path
2610 removes a built-in rule only when the rule's own path is at or below it,
2611 so exempting `~/.ssh/config` does nothing: the `~/.ssh` rule still denies
2612 it, because `~/.ssh` does not lie within `~/.ssh/config`. To reopen that
2613 one file you must exempt `~/.ssh` itself — which also reopens the private
2614 keys next to it. That is the documented tradeoff: there is no shipped way
2615 to narrow a built-in rule to "everything except one file"; copy what you
2616 need out of the denied tree instead. The one name-shaped rule, `.env`
2617 files, is exempted by *name* rather than by path: any exempt entry whose
2618 file name is exactly `.env` — bare `.env`, `~/.env`,
2619 `some/project/.env` — disables the entire `.env` filename rule, i.e.
2620 every `.env` and `.env.<name>` on disk rather than one project's.
2621 (`.env.example` and friends are never denied, so they need no exemption.)
2622
2623 Enforced at two points, with different reach. Codewhale's own in-process
2624 tools, which the OS sandbox never wraps, refuse every rule — `read_file` /
2625 `read` / `read_media` for contents, `list_dir` / `file_search` for
2626 *enumeration* (listing a denied directory, or searching one, is refused just
2627 as Seatbelt blocks its readdir; a name search rooted above a denied tree
2628 skips entries inside it). Sandboxed shell commands (Seatbelt last-match-wins
2629 `deny file-read*` rules; bubblewrap masks each path) refuse only the
2630 key-material and other-principal rules, so an authenticated CLI can still
2631 read its own config. A refused read is always an explicit error, never an
2632 empty result, and the error names the path as the caller spelled it rather
2633 than a symlink target's real location.
2634
2635 **This is defense-in-depth, not a security boundary.** Workspace `read` /
2636 `read_file` operations traverse each path component without following
2637 symlinks, verify the opened file descriptor's resolved path before reading
2638 (for outside-workspace reads as well), and feed PDF/OCR extraction from those
2639 verified bytes without reopening by name. Still, it does not stop a hardlink
2640 to a denied file outside workspace-confined opens or in sandboxed shell
2641 commands, a secret already copied into the workspace, an indirect read
2642 (`ssh-agent`, `security find-generic-password`, `aws sts …`), reads under
2643 `danger-full-access` shell commands, reads by MCP servers or other unwrapped
2644 child processes, or exfiltration of anything that *was* read. Keep
2645 least-privilege credentials and short-lived tokens doing the real work.
2646 - `permissions.toml` (sibling file, optional): typed permission rule records
2647 loaded next to `config.toml`, for example `~/.codewhale/permissions.toml`.
2648 This active user file is the only permission-rule source today; project
2649 config overlays do not load a project-local `permissions.toml`. A rule's
2650 optional `workspace` field is its repository scope, not a second source.
2651 Manually authored `[[rules]]` entries accept `tool`, optional `command` or
2652 `path`, optional absolute `workspace`, optional `command_exact = true`, and
2653 optional `action = "deny" | "ask" | "allow"`; omitted `action` defaults to
2654 `"ask"`. File-tool rules must use the tool names `read_file`, `write_file`,
2655 and `edit_file`; a rule written with `write` or `edit` matches nothing today.
2656 `workspace` limits a rule to that repository, while
2657 `command_exact = true` changes a command rule from the historical
2658 arity-aware prefix match to a complete-command match. `deny` blocks matching
2659 invocations before mode-based
2660 approval handling, `allow` skips approval for matching invocations, and
2661 `ask` forces approval only in modes that can prompt. In Auto-Review, broad
2662 typed `allow` rules (`exec_shell`/`bash` without a command, globs such as
2663 `*`, `python*`, or `npm run *`, bare script/package runner prefixes such as
2664 `python`, `node`, `npm run`, or `cargo run`, `agent`/`subagent`/`spawn_agent`,
2665 `*`, and write/edit/patch file rules without `path`) are paused without
2666 changing `permissions.toml` and resume when leaving Auto-Review; entering
2667 Auto-Review displays a one-line note when broad allow rules are paused.
2668 Narrow typed `allow` rules (statically expanded, unwrapped `exec_shell`/`bash`
2669 calls whose extra operands have no flags, or exact non-agent non-plugin
2670 tools with explicit `path` for file tools) skip the Auto-Review reviewer when
2671 no safety floor, soft rule, hook hold, plugin hold, or
2672 `auto_review.review_all_shell` applies. Outside the TUI
2673 auto-approve path, a matching `ask` rule under `approval_policy = "never"`
2674 is rejected because no prompt can be shown. In Full Access / auto-approval sessions,
2675 `ask` rules do not downgrade the session into prompting or blocking; explicit
2676 `deny` rules still block according to the current execution-policy logic.
2677
2678 Command `deny` rules match statically parsed command lines (including common
2679 shell, wrapper, and launcher invocations), failing closed when a command word
2680 cannot be resolved until run time. They do not inspect script files, inline
2681 interpreter payloads (`python -c`, `perl -e`), renamed binaries, alternative
2682 commands with the same effect, or execution inside remote hosts or container
2683 images beyond what is spelled on the local command line. Use the execution
2684 sandbox as the real containment control.
2685
2686 In a supported approval card, press `S` to allow the request once and append
2687 exact `action = "ask"` rules to this file. For eligible safe requests, choose
2688 **Always allow this exact rule in this repo** (shortcut `P`) to append an
2689 `action = "allow"` rule with the current absolute `workspace` scope.
2690 Remembered shell grants set `command_exact = true`, so later commands with
2691 extra arguments do not inherit the grant. File and patch grants retain the
2692 exact workspace-relative paths produced by the existing validation path.
2693 Supported saves are intentionally narrow:
2694 `exec_shell` stores the exact approved command string; `write_file` and
2695 `edit_file` store the exact workspace-relative file path; `apply_patch`
2696 stores one exact workspace-relative `path` rule per validated touched file
2697 from apply-patch preflight. Existing exec command matching remains
2698 arity-aware for manually authored prefix rules; approval-card allow grants
2699 use complete-command matching. File paths are normalized to the same
2700 workspace-relative form used by runtime matching.
2701
2702 `read_file` rules can still be authored manually when you want `read_file`
2703 calls on one exact path to ask, allow, or deny, but the approval UI does not
2704 save `read_file` rules. Rules are matched by tool name first and by exact
2705 path second (not a folder), so a `path` rule covers only the single tool it
2706 names. Shell calls and MCP calls carry no path, so a `path` rule never
2707 matches either (including a `tool = "bash"` rule that sets `path`), and a
2708 `deny` rule with `tool = "*"` never matches. To block an MCP tool, use a
2709 `deny` rule on its exact tool name with no `path`, or list it in
2710 `disabled_tools` on the server. Commands classified as requiring approval or
2711 dangerous, critical approval cards, and repo-law prompts cannot save allow
2712 grants and continue to require review.
2713
2714 `/permissions` (or `/permissions list`) is the narrow rule-management
2715 surface. It lists each numbered rule with the active user-file source, its
2716 exact effective matcher (tool-wide, command prefix, exact command, or exact
2717 normalized path), global or repository scope, and whether that scope
2718 applies in the current workspace. `/config ask-rules` remains a compatibility
2719 entry to the same list.
2720
2721 Deletion is review-gated: `/permissions remove <number>` only previews the
2722 selected rule and prints a confirmation command. That command carries an
2723 opaque token bound to the exact file bytes and rule index; if another writer
2724 changes `permissions.toml`, confirmation fails instead of deleting a rule
2725 that moved into the old position. Confirmed removal and approval-card appends
2726 share the adjacent `permissions.toml.lock`, preserve unrelated TOML comments
2727 and formatting, and atomically replace the file. The running TUI reloads the
2728 user ruleset without clearing session-only approvals. The Runtime API
2729 exposes the same list, token-bound removal and repo-scoped allow save for
2730 the desktop app ([Runtime API](RUNTIME_API.md), "Permission rules and
2731 grants").
2732
2733 This editor intentionally does not create or rewrite rules, persist deny
2734 choices from approval cards, expand globs, or create broad
2735 directory/recursive rules. Author those supported exact/prefix records
2736 manually when needed.
2737 - `[[hotbar]]` (array of tables, optional): user-owned 1-8 slot bindings for
2738 the TUI hotbar. Each entry has `slot`, `action`, and optional `label`.
2739 The Hotbar is hidden by default (#3807): omitting `hotbar` and setting
2740 `hotbar = []` both mean no hotbar. `/hotbar on` writes the eight default
2741 slots (`slash.workflow`, `slash.goal`, `slash.auto`, `mode.plan`,
2742 `mode.agent`, `reasoning.cycle`, `palette.open`, `sidebar.toggle`) as explicit
2743 `[[hotbar]]` tables. When one or more `[[hotbar]]` tables are present, that
2744 list is the whole bar; missing slots stay empty. Invalid slots outside `1..=8` are skipped with a warning, duplicate
2745 slots use the later entry, and unknown action IDs are kept so the UI can show
2746 a disabled/unknown cell instead of silently deleting user config. Trusted
2747 user config, profiles, and managed config replace the whole list; project
2748 overlays cannot change hotbar bindings. Setup or wizard flows that persist
2749 hotbar bindings write this same schema to the resolved `~/.codewhale/config.toml`
2750 path, preserving legacy `~/.deepseek/config.toml` only when that fallback file
2751 is already the active config.
2752
2753 ```toml
2754 [[hotbar]]
2755 slot = 1
2756 action = "mode.plan"
2757 label = "Plan"
2758
2759 [[hotbar]]
2760 slot = 2
2761 action = "session.compact"
2762 ```
2763 - `[auto_review]` (table, optional): tool-call review policy — a deterministic floor plus a model guardian tier.
2764 This layer sits on top of the existing permission posture; it can hold or block a
2765 tool call, but it is not an auto-push, auto-merge, or hosted review service.
2766 `auto_review.reviewer_model` (string, optional; also settable live or saved
2767 with `/config auto_review.reviewer_model <model|default> [--save]`) selects the
2768 model for guardian reviews on your active provider route; when unset,
2769 Codewhale selects a capable catalog model on that provider route (or falls
2770 back to the active session model) without crossing providers or accounts.
2771 `auto_review.environment` (array of strings, optional; user and managed config
2772 only) lists trusted environment context lines (such as trusted remotes,
2773 accounts, hosts, or buckets) passed in the guardian's `environment` field to
2774 judge pushes and outbound network requests in context. Entries cannot be
2775 blank or contain control characters, and project `.codewhale/config.toml`
2776 files cannot set or alter `[auto_review]` or `auto_review.environment` (a
2777 project-scope `[auto_review]` table is ignored with a warning).
2778 Block rules are checked first, then the built-in safety floor, then named
2779 soft rules in Auto-Review (`force-push`, `git-tag`, `deploy-branch`,
2780 `git-discard`, `infra-destroy`, `ci-or-pr-bypass`, `print-credentials`,
2781 `secret-commit`, and `deploy-wrapper`) and instruction-file writes, then allow
2782 rules. In Ask and Accept Edits, a safety hold opens approval that no session grant or allow
2783 rule can answer; in Auto-Review or a non-interactive `never` posture it
2784 fails closed as a hard block. Full Access skips the built-in floor. In
2785 Auto-Review, package and release publishing (`npm publish`, `cargo publish`,
2786 `gh release`, and release tools), destructive unattended work, and
2787 detected credential uploads or hidden Unicode remain on the deterministic
2788 safety floor; repository-remote `git push` calls are judged by the guardian
2789 against your request and `auto_review.environment` when `owner_present` is
2790 true, and are hard-blocked on unattended turns (`!owner_present`). Soft rules
2791 hold common shell and git forms before `allow` rules, carry the rule name in
2792 block reasons and receipts, and require a specific person request rather than
2793 broad authorization. Outside Full Access, hidden Unicode checks also refuse
2794 shell commands or shell input containing invisible or bidirectional control
2795 characters, naming the code point and its position.
2796
2797 ```toml
2798 [auto_review]
2799 reviewer_model = "claude-sonnet-4-6" # optional; stays on your active provider route
2800 environment = [
2801 "trusted git remote: github.com/org/repo",
2802 "trusted staging API: https://staging.example.internal",
2803 ]
2804
2805 [[auto_review.allow]]
2806 id = "read-only-inspection"
2807 action_kind = "read"
2808 reason = "Read-only inspection is safe to run automatically."
2809
2810 [[auto_review.block]]
2811 id = "no-release-publish"
2812 action_kind = "publish"
2813 reason = "Release and publish actions require maintainer review."
2814 ```
2815
2816 Rule matchers are exact `tool` and/or `action_kind`. At least one matcher is
2817 required. `action_kind` accepts the six decision-relevant kinds `read`,
2818 `write`, `shell`, `external`, `publish`, and `destructive`. Invalid names
2819 fail config validation instead of silently broadening into another policy
2820 class. In Auto-Review, broad `[[auto_review.allow]]` rules whose
2821 `action_kind` normalizes to `shell`, `external`, `write`, `destructive`, or
2822 `publish` (without a specific non-shell/non-agent tool) or whose `tool`
2823 matches `exec_shell`, `bash`, `agent`, or `*` are omitted with a warning while
2824 specific non-shell/non-agent tool allow rules remain active. Set
2825 `auto_review.review_all_shell = true` (user and managed config only; ignored
2826 in `.codewhale/config.toml`) to send every shell command — including benign
2827 reads and narrow-allowed shell commands — to the Auto-Review reviewer after
2828 deterministic safety-floor, block, soft-rule, and plugin checks. In block
2829 rules, the old names remain conservative compatibility
2830 aliases: `network`, `git`, `mcp_action`, `browser`, and `unknown` map to
2831 `external`; `secret` maps to `destructive`; and `mcp_read` maps to `read`.
2832 Retired narrow kinds in allow rules fail validation rather than widening to
2833 a broader class. The retired `text_contains` matcher likewise fails
2834 validation instead of silently broadening an old intent-dependent rule.
2835 Fallback holds in Auto-Review escalate to one stateless guardian request
2836 within a 64 KiB context budget. The request passes untrusted-evidence JSON
2837 fields containing the session-recorded typed owner composer prompts (newest
2838 first), any approved plan text, earlier redacted non-read actions from the
2839 same turn, session-start pinned user-level and repository-level instructions
2840 with SHA-256 hashes (never re-read mid-session), deterministic observations,
2841 and the exact held call (preserving `description`). Tool outputs, assistant
2842 prose, attached `@`-file contents, skill bodies, and non-owner or generated
2843 prompts (tasks, automations, `send_later`, goal continuations, subagent
2844 briefs, reviews, and chat relays) are excluded from `person_messages`. High or
2845 critical risk cannot auto-run even if the model says allow. An oversized
2846 current request or exact held call returns unavailable (failing closed)
2847 rather than being truncated. Exactly one reviewer request is made;
2848 incomplete or malformed output, timeout, cancellation, provider failure, or an
2849 empty rationale all fail closed. The deterministic floor is never
2850 model-reviewed, and headless adapters use the deterministic-only tier. The
2851 pinned Codex, Kimi, and DeepSeek source boundaries are linked from
2852 [Permission Posture](MODES.md#permission-posture). Reviewer outcomes emit
2853 `tool.auto_review` audit events with `gate = "guardian"` and `reviewer_model`,
2854 and transcript receipts show the resolved reviewer model.
2855
2856 Auto-review decisions emit `tool.auto_review` audit events with
2857 `gate = "deterministic"` when tool
2858 audit logging is enabled. Future PreToolUse/PostToolUse hooks can add
2859 observer input around this layer, but the configured auto-review policy is
2860 evaluated before a tool call is allowed to proceed.
2861 Set `disabled = true` under `[auto_review]` in managed config to turn
2862 Auto-Review off: `Shift+Tab` skips Auto-Review, and `--permission-mode auto-review`,
2863 `/auto`, and `approval_policy = "auto"` are refused. A managed `[auto_review]`
2864 table replaces the user's whole `[auto_review]` table rather than merging keys.
2865 - `managed_config_path` (string, optional): managed config file loaded after user/env config. `CODEWHALE_MANAGED_CONFIG_PATH` outranks it. A named file that is missing or unreadable is a load error, and it cannot replace an existing file at the default managed path.
2866 - `requirements_path` (string, optional): requirements file used to enforce allowed approval/sandbox values.
2867 - `max_subagents` (int, optional): defaults to `64` and is clamped to `1..=128`.
2868 - `subagents.*` (optional compatibility table): manual per-role model pins
2869 for direct and Workflow `agent` starts. An explicit saved profile wins,
2870 then a manual role pin, then a unique saved role pin. Conflicting tool
2871 `model` or `model_strength` choices are refused before admission. Unpinned
2872 roles allow task model/strength choices before inherited defaults.
2873 `[subagents.roles.<role>] model = "provider/model"` folds into the existing override
2874 map and wins over `[subagents.models]`, then the convenience keys. Structured
2875 canonical role keys win over legacy aliases. Only this structured syntax
2876 separates the explicit provider from the model suffix; unknown providers
2877 fail before admission. Bare structured model ids inherit the active provider.
2878 Legacy scalar/map values preserve namespaced provider-owned ids unchanged.
2879 Supported convenience keys are
2880 `default_model`, `worker_model`, `scout_model`, `planner_model`,
2881 `reviewer_model`, `custom_model`, `max_concurrent`, `max_admitted`,
2882 `launch_concurrency`, `api_timeout_secs`, and `heartbeat_timeout_secs`. The
2883 legacy keys `explorer_model`, `awaiter_model`, and `review_model` remain
2884 accepted as aliases. The `[subagents] max_concurrent` value overrides
2885 top-level `max_subagents` and is also clamped to `1..=128`. `[subagents]
2886 max_admitted` (aliases: `max_total`, `admission_limit`) is the bounded total
2887 of queued plus running sub-agents; it defaults to `1024`
2888 (`MAX_SUBAGENT_ADMISSION`, `crates/tui/src/config/subagent_limits.rs:21`,
2889 applied at `config.rs:6400`) so high-fanout turns can queue and drain while
2890 runtime launch pressure remains bounded, and is clamped to
2891 `max_concurrent..=1024`. `[subagents]
2892 launch_concurrency` sets how many direct children start at once before the
2893 rest queue for a launch slot; it defaults to the resolved `max_subagents` cap
2894 and is clamped to `1..=max_subagents` (the deprecated
2895 `interactive_max_launch` key is accepted as an alias, with the new key
2896 winning when both are set). `[subagents] api_timeout_secs`
2897 controls the per-step API timeout for sub-agent model calls and is clamped to
2898 `1..=3600`, with `0` or unset preserving the 600 second default. A timeout
2899 after possible dispatch interrupts with a preserved checkpoint and unknown
2900 outcome. Only a transient connection timeout proven to precede dispatch uses
2901 exponential backoff, up to 5 retries.
2902 `[subagents] heartbeat_timeout_secs` controls stale running agent cleanup,
2903 defaults to `300`, and is clamped to `30..=3600` while staying above the
2904 resolved API timeout. `[subagents.providers.<provider>]` accepts the same
2905 fanout, depth, and timeout knobs (`enabled`, `max_concurrent`,
2906 `max_admitted`, `launch_concurrency`, `max_depth`, `api_timeout_secs`,
2907 `heartbeat_timeout_secs`) and inherits the global
2908 `[subagents]` value for any key you omit. Provider keys accept canonical
2909 names such as `deepseek`, `zai`, `openrouter`, `anthropic`, plus convenience
2910 aliases such as `glm` for Z.ai and `deepseek_api` for direct DeepSeek:
2911
2912 ```toml
2913 [subagents]
2914 max_concurrent = 20
2915 launch_concurrency = 20
2916 max_admitted = 200
2917 max_depth = 6
2918
2919 [subagents.providers.deepseek]
2920 max_concurrent = 20
2921 launch_concurrency = 20
2922 max_admitted = 200
2923
2924 [subagents.providers.glm]
2925 max_concurrent = 4
2926 launch_concurrency = 3
2927 max_admitted = 12
2928 max_depth = 2
2929
2930 [subagents.providers.openrouter]
2931 max_concurrent = 5
2932 launch_concurrency = 3
2933 max_admitted = 20
2934 ```
2935
2936 `/config subagents status` prints both global values and the active
2937 provider's resolved profile so rate-limit tuning is visible in the TUI.
2938 `[subagents.models]` accepts lower-case Fleet role keys such as `worker`,
2939 `scout`, `planner`, `reviewer`, `builder`, and `verifier`; legacy type keys
2940 remain accepted as compatibility aliases. Values are validated
2941 against the active provider at spawn time; direct DeepSeek requires DeepSeek
2942 IDs, while OpenAI-compatible/custom provider routes pass explicit model IDs
2943 through to that provider. To route a child to a different provider than the
2944 parent session, save a Fleet/AgentProfile with explicit `provider` and
2945 `model` fields (including user-named custom providers such as `lm-studio`)
2946 and call `agent(profile: "...")`; see [SUBAGENTS.md](SUBAGENTS.md).
2947 - `skills_dir` (string, optional): defaults to `~/.codewhale/skills` (each skill is
2948 a directory containing `SKILL.md`). After workspace trust, project skills
2949 take precedence, with `.codewhale/skills` ahead of compatible roots such as
2950 `.agents/skills`. Flat `./skills` requires explicit opt-in below. The runtime
2951 also discovers global agentskills.io-compatible `~/.agents/skills` and the
2952 broader Claude-ecosystem
2953 `~/.claude/skills`. With the default bundle policy and no `skills_dir`
2954 override, first launch installs six starter skills in `skills/.system/`.
2955 Optional workflow and document packs are available from the marketplace. Only
2956 Codewhale-owned roots (`<workspace>/.codewhale/skills` and
2957 `~/.codewhale/skills`) are writable install/import targets; compatible harness
2958 roots stay read-only. Bare `/skills` opens Plugins → Skills (owned-only,
2959 zero network); `/skills manage` opens the manager. See [SKILLS.md](SKILLS.md)
2960 for the manager, audit statuses, provenance markers, and mutation rules, and
2961 [CLAUDE_PLUGIN_COMPAT.md](CLAUDE_PLUGIN_COMPAT.md) for the supported boundary
2962 between portable `SKILL.md` bundles and Claude Code plugin runtimes.
2963 - `[skills.bundled].install` (`"auto"` default, `"all"`, `"none"`): controls bundle writes independently of discovery. `auto` keeps deletion-as-opt-out and disables installation when `skills_dir` is set. `all` repairs enabled missing skills into `$CODEWHALE_HOME/skills/.system` (normally `~/.codewhale/skills/.system`) even with a discovery override. `none` writes nothing and leaves the marker untouched. Modified and managed bodies are preserved in every mode. The six starters share one content fingerprint.
2964 - `[skills.bundled].selected` / `disabled` / `explicit_only` (arrays of names, default `[]`): selection limits installation and discovery; empty selects the whole bundle. Disabled wins and reveals lower-root copies. Explicit-only retains user invocation while removing the shipped copy from the model index and model loading. Aliases share canonical policy. These settings affect recognized global bundle copies only and never delete files. Profile fields merge separately; `[]` clears an inherited list. `doctor` warns about unknown/ignored entries and `/skills inspect` reports per-path reasons. See [bundled skills](SKILLS.md#bundled-skills).
2965 - `[skills].listing_max_description_chars` (integer, default `120`, range `1..=40000`): description cap for the once-per-session `<codewhale:runtime_event kind="skills_context">` catalog (and `/context` / `doctor --context-json` preview), the description warning in `/skills inspect`, and the descriptions in the `load_skill` list. Unknown `[skills]` keys are rejected.
2966 - `[skills].listing_budget_fraction` (finite number, default `0.002`, greater than `0` and at most `1`): share of the route window for the bounded 3-tier `<codewhale:runtime_event kind="skills_context">` listing, estimated at four characters per token and clamped to `2400..=40000` characters. Installed skills (trusted project roots, `~/.codewhale/skills`, enabled plugins with descriptions, and compatible roots excluding Cursor/Claude vendor defaults under `/.cursor/` and `/.claude/`) are surfaced once per parent session in that history message — keeping the static system prompt cache-stable and re-injecting automatically after `/compact` — while sub-agents continue loading skills on demand through [`load_skill`](SKILLS.md#config-knobs). Explicit profile fields override inherited values independently.
2967 - `[skills].always_load` (array of skill names, default `[]`): preloads the full body of each named skill into the session's `skills_context` message at session start (mirroring `[tools] always_load`). Fails loud if a listed skill is missing or disabled, and caps preloaded bodies at 64 KiB per skill and 128 KiB total with a warning if truncated.
2968 - Skill manifests may declare named tool and MCP dependencies in `agents/openai.yaml`. Explicit user mentions can activate enabled lazy servers already approved in MCP configuration, subject to the turn’s tool restrictions.
2969 - `[skills].scan_codewhale_only` (bool, default `false`): when `true`, session
2970 skill discovery ignores cross-tool roots such as `.claude/skills`,
2971 `.opencode/skills`, `.cursor/skills`, and `~/.agents/skills`. Codewhale still
2972 scans `<workspace>/.codewhale/skills`, `~/.codewhale/skills`, and any explicit
2973 `skills_dir` override. The Skills Manager can still toggle a local compatible
2974 audit scan independently of this runtime knob — see [SKILLS.md](SKILLS.md).
2975 - `[skills].flat_workspace_root` (bool, default `false`): opt in to the flat
2976 `<workspace>/skills` compatibility root after workspace trust. Without this
2977 opt-in it is an audit candidate only; an explicit `skills_dir` remains an
2978 alternative. `scan_codewhale_only = true` excludes the flat compatibility
2979 root regardless of this flag, unless it is the explicit `skills_dir`.
2980 - `[skills].registry_url` / `[skills].max_install_size_bytes` (optional): used by
2981 `/skills --remote`, `/skills suggest <task>`, `/skills sync`, and `/skill
2982 install|update`. The default manager open path does not contact the registry.
2983 - `[verifier].enabled` (bool, default `false`): enables automatic
2984 claim-of-done verifier preview once that runtime trigger is active. The
2985 manual `run_verifiers` tool is still available when this is false.
2986 - `mcp_config_path` (string, optional): defaults to `~/.codewhale/mcp.json`, with
2987 legacy `~/.deepseek/mcp.json` fallback when the Codewhale path is absent.
2988 Custom paths must be absolute; a relative value falls back to the user-global
2989 path so changing the launch directory cannot silently change the MCP pool.
2990 It is visible in `/config` and can be changed from the TUI. The new path is
2991 used immediately by `/mcp`; run `/mcp reload` to rebuild the model-visible
2992 MCP tool pool without restarting the TUI. A headless runtime still needs a
2993 restart because its `ConfigReload` request does not refresh MCP connections.
2994 - `[memory].enabled` (bool, optional): defaults to `false`. When `true`,
2995 the TUI loads the user memory file into a `<user_memory>` prompt block,
2996 enables `# foo` quick-capture in the composer, surfaces the `/memory`
2997 slash command, and registers the `remember` tool. The same toggle is
2998 available via `DEEPSEEK_MEMORY=on`.
2999 - `memory_path` (string, optional): anchors the native memory store. The
3000 configured filename is **not** the file that is written. Under the Native
3001 backend (the only backend) the store is re-rooted to
3002 `<parent-of-memory_path>/memory/global/MEMORY.md` — so the default
3003 `~/.codewhale/memory.md` yields `~/.codewhale/memory/global/MEMORY.md`
3004 (plus workspace-scoped files and a rebuildable SQLite FTS5 index). See
3005 [`MEMORY.md`](MEMORY.md) for the full feature surface (`# foo` composer
3006 prefix, `/memory` slash command, `remember` tool, opt-in toggle).
3007 - `snapshots.*` (optional): side-git workspace snapshots for file rollback:
3008 - `[snapshots].enabled` (bool, default `true`)
3009 - `[snapshots].max_age_days` (int, default `7`)
3010 - snapshots live under
3011 `~/.codewhale/snapshots/<project_hash>/<worktree_hash>/.git`, with legacy
3012 `~/.deepseek/snapshots/...` fallback when only the legacy state exists, and
3013 never use the workspace's own `.git` directory
3014 - `context.*` (optional):
3015 - `[context].project_pack` (bool, default `false`): include a deterministic
3016 project context pack (a large pretty-printed directory listing) in the
3017 stable prompt prefix (#4781). Useful for weak tool-calling models; the
3018 model can rebuild the same information with one `File` call.
3019 - The removed seam-manager keys (`enabled`, `verbatim_window_turns`,
3020 `l1_threshold`, `l2_threshold`, `l3_threshold`, `seam_model`) are
3021 ignored if an older config still carries them; they no longer load.
3022 - `compaction.*` (optional, config.toml): how a compaction pass behaves once
3023 it fires. `auto_compact` / `auto_compact_threshold_percent` (settings.toml)
3024 still decide *when* it fires. Both keys are absent by default, and absent
3025 means the built-in behaviour, unchanged:
3026 - `[compaction].summary_instructions` (string, default empty): standing
3027 operator instructions appended to the summarizer prompt as a clearly
3028 delimited "Additional instructions from the operator" section on **every**
3029 pass, manual and automatic — the effort-free counterpart to a one-off
3030 `/compact <focus>`, which still composes after this text. Useful for
3031 "always list exact file paths and line numbers", "always restate open
3032 decisions and their trade-offs", "always write a TL;DR first". Truncated
3033 at 4 000 characters with a warning naming the key; whitespace-only reads
3034 as unset. The summarizer still runs with no system prompt and no tools —
3035 this suffix is the only operator-authored input it sees.
3036 - `[compaction].retained_user_message_tokens` (int, default `20000`, clamped
3037 to `2000`–`200000`; also accepted as `retained_user_message_max_tokens`):
3038 token budget for the recent plain user messages kept **verbatim** in the
3039 replacement history. Raising it keeps more of the user's own earlier
3040 messages instead of only whatever the lossy summary captured; the
3041 last-round survival contract still applies on top. The `/compact` receipt
3042 names the effective budget and whether operator instructions were applied,
3043 so you can tell the knob took effect.
3044 - `retry.*` (optional): HTTP retry settings. The following backoff fields govern
3045 ordinary transport retries; HTTP 429 uses the independent policy below:
3046 - `[retry].enabled` (bool, default `true`)
3047 - `[retry].max_retries` (int, default `3`): ordinary transport retries
3048 - `[retry].initial_delay` (float seconds, default `1.0`)
3049 - `[retry].max_delay` (float seconds, default `60.0`)
3050 - `[retry].exponential_base` (float, default `2.0`)
3051 - `[retry].jitter` (bool, default `true`): randomize ordinary transport backoff
3052 - `[retry].jitter_factor` (float, default `0.1` = ±10%; clamps to `0.0..=1.0`)
3053 - `[retry].respect_retry_after` (bool, default `true`): wait for a server
3054 `Retry-After` preference retained for legacy retry configuration; it does not
3055 disable HTTP 429 server minima
3056
3057 HTTP 429 recovery has its own validated `[retry.rate_limit]` fields:
3058
3059 - `max_attempts` (integer, default `20`, range `1..=1000`): total attempts,
3060 including the first
3061 - `recovery_budget_secs` (integer seconds, default `600`, range `1..=86400`)
3062 - `initial_delay_secs` (integer seconds, default `5`)
3063 - `max_delay_secs` (integer seconds, default `60`), with
3064 `1 <= initial_delay_secs <= max_delay_secs <= 86400`
3065
3066 This policy always honors server minima and uses equal jitter, independently
3067 of the legacy `initial_delay`, `max_delay`, `exponential_base`, `jitter`,
3068 `jitter_factor` and `respect_retry_after` fields. `max_retries = 0` does not
3069 disable 429 recovery; set `retry.rate_limit.max_attempts = 1` to disable only
3070 automatic 429 retries, or `retry.enabled = false` to disable this HTTP retry
3071 loop. A safe pre-dispatch HTTP/1.1 fallback inside a stream-opening operation
3072 remains possible. The one-hour limit on actual provider pauses and automatic sleeps
3073 still applies. See [HTTP rate-limit retries](rate-limit-retries.md) for the
3074 budget, server-minimum and active-time boundaries.
3075
3076 `[retry]` schedules HTTP-request retries inside the client. Each physical
3077 streaming request gets its own `stream.open_timeout_secs` response-header
3078 wait. Provider backoff and honored `Retry-After` waits happen between
3079 attempts, outside that timer, so the configured retry count remains
3080 reachable. Inference retries require an ordinary rate limit or a proven
3081 transient connection failure before dispatch. Only that connection failure
3082 can switch once to HTTP/1.1; a header stall cannot. Both inference clients
3083 disable redirects and reqwest protocol retries. Explicit plan-window
3084 exhaustion is a terminal quota error. Server failures and interrupted streams
3085 after any output preserve unknown coverage and stop without automatically
3086 reissuing inference. Two bounded exceptions retry before any output is
3087 streamed: a response-header timeout is sent again `stream.open_retries` times
3088 (default once) with a `Retry attempt: stream-open-timeout` line, and a
3089 pre-output transport failure or stream closed before `[DONE]`/`finish_reason`
3090 with an unknown outcome is sent again `stream.unknown_outcome_retries` times
3091 (opt-in, default `0`, maximum `3`) with a
3092 `Retry attempt: stream-unknown-outcome` line. Partial output is never
3093 replayed, and `QuotaExhausted`, auth `4xx`, and billing/subscription/credit
3094 errors remain terminal. The provider may have processed and billed an earlier
3095 unknown-outcome request, so its usage stays recorded as unknown. Read-only catalog GETs retain bounded
3096 retries at their actual method owner. The `[stream]` keys below bound safe
3097 pre-dispatch recovery and stream consumption; legacy `tui.stream_max_*`
3098 keys remain configuration fallbacks.
3099 - `[notifications]`: notification delivery, attention, categories and audio share one
3100 policy. `quiet = true`, `method = "off"`, `condition = "never"` and disabled
3101 categories suppress both the banner and Codewhale's selected sound.
3102 - `notifications.method`: `auto` (default), `osc9`, `kitty`, `ghostty`, `bel`, `off`.
3103 - `notifications.condition`: `unfocused` (default), `always`, `never`. When absent,
3104 the legacy `tui.notification_condition` remains the fallback. `always` also
3105 bypasses the duration threshold; `unfocused` requires two seconds away.
3106 - `notifications.threshold_secs`: nonnegative integer, default `30`.
3107 - `notifications.include_summary`: boolean, default `false`.
3108 - `notifications.sound`: optional `off`, `whale`, `bell`, `beep`, `file`.
3109 A selected value controls audio across enabled categories. Absent keeps legacy
3110 `completion_sound` and `event_sound` choices; `off` overrides both.
3111 - `notifications.sound_file`: custom local WAV path for `sound = "file"` or legacy
3112 `completion_sound = "file"`.
3113 - `notifications.subagent_completion`: `always`, `final-only` (default), `off`.
3114 Covers all background work that finishes: sub-agents, background shells and
3115 durable tasks. `final-only` sends one notice naming everything that finished
3116 once no agent, workflow or durable task is still running; a running shell
3117 (a dev server, a watcher) never holds it back. `always` sends one per item.
3118 - `notifications.quiet`: boolean, default `false`.
3119 - `notifications.events`: six boolean categories, all enabled by default; see below.
3120 - `notifications.completion_sound`: legacy completion cue, default `off`, with the
3121 same values as `sound`. Used only when `sound` is absent.
3122 - `notifications.event_sound`: legacy `enabled` (default `false`), `events`
3123 (default `["turn-complete", "approval-needed"]`), and `quiet` (default `false`).
3124 `min_interval_ms` (default `2000`) applies to each category's audio in both modes.
3125 - `tui.mouse_capture` (bool, optional, default `true` on non-Windows terminals and on Windows Terminal/ConEmu/Cmder when the alternate screen is active; `false` on legacy Windows console and inside JetBrains JediTerm — PyCharm/IDEA/CLion/etc. — where mouse-event escapes leak into the input stream as garbled text, see #878 / #898): enable internal mouse scrolling, transcript selection, right-click context actions, and transcript scrollbar dragging. TUI-owned drag selection copies the intersected cells, removes visual wrap-column line breaks from paragraphs, and keeps selection scoped to the transcript pane; the payload is Markdown source by default, see `tui.selection_copy_markdown` below. Set this to `false` or run with `--no-mouse-capture` for raw terminal selection; set it to `true` or run with `--mouse-capture` to opt in anywhere it's defaulted off. On raw terminal selection, especially on legacy Windows console or when mouse capture is disabled, selection may cross the right workbar and include visual wraps because the terminal, not the TUI, owns the selection.
3126 On Linux, finishing a transcript or composer selection quietly copies text to
3127 PRIMARY, leaving the regular clipboard unchanged. Middle-click inside the
3128 composer pastes PRIMARY at the pointer without submitting it. This uses native
3129 X11 or Wayland data control; compositors must support PRIMARY selection. Over
3130 SSH without a forwarded graphical display, use your terminal's selection/paste
3131 gestures or `--no-mouse-capture`. Explicit Copy still uses the regular clipboard.
3132
3133 - `tui.selection_copy_markdown` (bool, optional, default `true`): copy TUI-owned
3134 transcript selections (drag release, context-menu Copy, and `Cmd+C`/`Ctrl+C`
3135 on an active selection) as Markdown source instead of rendered text. Every
3136 intersected cell serializes through the same canonical projection `Ctrl-Y`
3137 and `/copy` use — user and assistant cells keep their authored Markdown,
3138 other cells keep their full transcript form — partial intersections round out
3139 to whole cells, cells join with blank lines, and a toast names the copied
3140 cell count. Set `false` to copy the rendered text as displayed. Composer
3141 selections and the Linux PRIMARY auto-copy are unchanged; PRIMARY always
3142 carries rendered text.
3143
3144 - `tui.stream_chunk_timeout_secs` (int, optional, default `900`): per-SSE-chunk idle timeout for streamed model responses. Slow local or compatible servers can raise this with `/config stream_chunk_timeout_secs <seconds>` (add `--save` to write canonical `stream.chunk_timeout_secs`); `0` maps to the default and explicit values must be `1..=3600`. The legacy `DEEPSEEK_STREAM_IDLE_TIMEOUT_SECS` env var is still honored when this key is omitted.
3145 - `tui.osc8_links` (bool, optional, default on for macOS/Linux, off for Windows): emit OSC 8 escape sequences around URLs in transcript output so supporting terminals (iTerm2, Terminal.app 13+, Ghostty, Kitty, WezTerm, Alacritty, recent gnome-terminal/konsole) can open them with the terminal's link gesture—usually Cmd-click on macOS and Ctrl-click on Linux/Windows. Terminals without OSC 8 support render the plain label and ignore the escape. The escapes are emitted out-of-band (not inside buffer cells), so column corruption is not a concern; set `false` only for terminals that misrender the OSC 8 terminator itself. Windows legacy consoles default off; opt in with `true`.
3146 - `tui.max_model_steps` (int, optional, default uncapped): optional model-step ceiling for one ordinary turn. Omission or `0` leaves model steps uncapped; explicit positive values are preserved (`4294967295` is the compatibility value for no limit). Headless `exec` and Fleet workers also have no implicit model-step ceiling; `exec --max-turns N` and positive worker budgets still apply. At exhaustion the turn ends `Failed` with `Maximum model steps reached before completion (limit: N)` after one bounded final-report response when needed. Cumulative wall-clock and per-stream limits remain independent. Active interactive goal turns use `goal.max_steps` instead (also uncapped by default); see the Goal loop section below.
3147 - `tui.turn_wall_clock_secs` (int, optional, default: no limit): cumulative per-turn wall-clock budget in seconds, measured across every model step of one turn (not per request). Time blocked on a human approval is excluded. Omitted or `0` means no limit; positive values are preserved without an added runtime ceiling. When exhausted the turn stops before authorizing another billable request with a message naming the limit and the key to raise.
3148 - `tui.stream_max_resumes` (int, optional, default `3`): turn-level recovery after a proven transient connection failure before request dispatch. `0` disables this additional recovery; values clamp to `0..=10`. Empty or partial streams, sleep and network drops never authorize inference replay; a response-header timeout has its own retry count, `stream.open_retries`.
3149 - `tui.stream_max_transparent_retries` (int, optional, default `2`): retained for configuration compatibility, clamped to `0..=10`. Interrupted streams no longer trigger transparent inference reissues, including before visible content.
3150 - `tui.stream_max_errors` (int, optional, default `5`): retained for configuration compatibility; `0` selects the default and positive values clamp to `1..=50`. Core ends an uncertain stream on its first read error or error frame regardless of this value.
3151 - `tui.stream_open_timeout_secs` (int, optional, default `180`): wait for a streaming request's response headers (connection setup included). A header stall is sent again `stream.open_retries` times (default once, never switching to HTTP/1.1) and then ends with an unknown outcome. Omitted or `0` falls back to `CODEWHALE_STREAM_OPEN_TIMEOUT_SECS`, then the default; values clamp to `5..=600`.
3152 - `tui.connect_timeout_secs` (int, optional, default `30`): TCP/TLS connect timeout for the model HTTP client. Omitted or `0` uses the default; values clamp to `1..=300`.
3153 - `tui.force_http1` (bool, optional, default `false`): pin the model HTTP client to HTTP/1.1, for provider edges or proxies that mishandle long-lived HTTP/2 streams. `CODEWHALE_FORCE_HTTP1=1` does the same; either one pins.
3154 - `tui.stream_max_content_mb` (int, optional, default `10`) and `tui.stream_max_duration_secs` (int, optional, default `1800`): per-step caps on one stream's accumulated content and wall-clock duration. `0` selects the default; values clamp to `1..=512` MB and `10..=86400` seconds.
3155 - `transcript.prose_measure` (positive integer, optional, default absent = full width): wrap cap, in columns, for prose cells — user messages, assistant answers, and reasoning/thinking blocks — in the live transcript (#5436). Absent (or `0`) spends the full content width, consistent with tool/status cells and the #5322 wide-frame decision; the former 105-column prose rail is gone. Set a positive whole number (e.g. `prose_measure = 120` under `[transcript]`) to restore a bounded reading measure on ultrawide terminals. Narrow terminals always keep their content width — the cap clamps from above only. Tool, diff, and status cells never inherit this cap. Invalid values (negative or non-integer) are rejected at startup with a `transcript.prose_measure` config error. Resolved once per render pass, so the main transcript cache and the full-screen overlay always agree on the effective width.
3156 - `hooks` (optional): lifecycle hooks configuration (see `config.example.toml`).
3157 - `features.*` (optional): feature flag overrides (see below).
3158
3159 ### Stream and transport settings
3160
3161 `[stream]` is the canonical table for model-stream policy and its HTTP clients.
3162 `codewhale config dump` and `codewhale config get stream` show effective values
3163 from the runtime resolver, including environment fallbacks and clamps; this does
3164 not persist defaults. Set or unset individual fields with, for example,
3165 `codewhale config set stream.open_timeout_secs 120` and
3166 `codewhale config unset stream.open_timeout_secs`. Read-only `codewhale config`
3167 inspection commands (`config get`, `config dump`, `config list`) also accept
3168 `--set stream.open_timeout_secs=120` using the same validation; runtime
3169 commands (`codewhale`, `exec`, `doctor`) only accept runtime `--set` keys
3170 (`provider`, `model`, `default_text_model`, `verbosity`, `approval_policy`,
3171 `sandbox_mode`, `telemetry`), so single-run stream overrides on a turn use
3172 `CODEWHALE_STREAM_OPEN_TIMEOUT_SECS`, `--profile`, or `codewhale config set`.
3173
3174 | `[stream]` key | Default | Accepted behavior | Legacy `[tui]` fallback |
3175 | --- | --- | --- | --- |
3176 | `open_timeout_secs` | 180 | Positive values clamp to 5–600; 0 or omission falls through to the environment/default | `stream_open_timeout_secs` |
3177 | `open_retries` | 1 | Times one request is sent again after it received no response headers within `open_timeout_secs`; 0 disables, maximum 3 | none |
3178 | `unknown_outcome_retries` | 0 | Opt-in times one request is sent again after a pre-output transport failure or stream closed before `[DONE]`/`finish_reason` with unknown outcome; never replays after partial output or on quota/billing/auth errors; 0 disables, maximum 3 | none |
3179 | `chunk_timeout_secs` | 900 | 0 selects default; positive values clamp to 1–3600 | `stream_chunk_timeout_secs` |
3180 | `max_resumes` | 3 | Proven transient pre-dispatch recovery only; 0 disables, maximum 10 | `stream_max_resumes` |
3181 | `max_transparent_retries` | 2 | Compatibility value; interrupted streams never reissue inference | `stream_max_transparent_retries` |
3182 | `max_stream_errors` | 5 | Compatibility value; Core ends on the first uncertain stream error | `stream_max_errors` |
3183 | `max_duration_secs` | 1800 | Per-stream wall clock; 0 selects default, positive values clamp to 10–86400 | `stream_max_duration_secs` |
3184 | `max_content_mb` | 10 | Per-stream content; 0 selects default, positive values clamp to 1–512 MiB | `stream_max_content_mb` |
3185 | `connect_timeout_secs` | 30 | TCP/TLS setup; 0 selects default, positive values clamp to 1–300 | `connect_timeout_secs` |
3186 | `force_http1` | false | Boolean; a truthy environment pin always enables HTTP/1.1 | `force_http1` |
3187 | `tcp_keepalive_secs` | 30 | Idle time before TCP keepalive probes; 0 disables, positive values clamp to 1–3600 | none |
3188 | `http2_keep_alive_interval_secs` | 15 | PING interval on active HTTP/2 connections; 0 disables, positive values clamp to 1–3600 | none |
3189 | `http2_keep_alive_timeout_secs` | 20 | PING acknowledgement deadline; 0 selects default, positive values clamp to 1–3600 | none |
3190
3191 For each field, an explicit canonical value wins over the legacy `[tui]` field,
3192 including zero or false; an absent canonical field preserves the legacy value.
3193 The existing environment precedence is unchanged: a positive configured header
3194 wait wins over `CODEWHALE_STREAM_OPEN_TIMEOUT_SECS` (then its `DEEPSEEK_` alias);
3195 zero falls through to those variables. An omitted chunk timeout uses
3196 `CODEWHALE_STREAM_IDLE_TIMEOUT_SECS` (then its `DEEPSEEK_` alias), whereas an
3197 explicit zero uses 900. `CODEWHALE_FORCE_HTTP1` (legacy `DEEPSEEK_FORCE_HTTP1`)
3198 is ORed with the selected config flag, so a false config flag cannot defeat a
3199 truthy environment pin. Profile overlays merge canonical fields independently.
3200
3201 HTTP transport values apply to all newly constructed model, catalog and HTTP/1
3202 fallback clients. They do not rebuild an active client, govern MCP/other network
3203 services, or send HTTP/2 PINGs on idle pooled connections. HTTP/2 knobs have no
3204 effect when HTTP/1.1 is pinned. The operating system controls TCP probe details;
3205 these settings do not disable certificate validation. `[retry]` still owns the
3206 HTTP-request backoff schedule independently of stream-level budgets.
3207
3208 ### Workspace notes
3209
3210 `/note` manages a simple notes file in the current workspace at
3211 `.codewhale/notes.md` (legacy `.deepseek/notes.md` is the fallback path when
3212 no `.codewhale/notes.md` exists yet).
3213 Existing `/note <text>` usage still appends a note.
3214 The management forms are:
3215
3216 | Command | Action |
3217 |---|---|
3218 | `/note <text>` | Append a note (legacy shorthand) |
3219 | `/note add <text>` | Append a note explicitly |
3220 | `/note list` | List notes with temporary 1-based numbers |
3221 | `/note show <n>` | Show the full note at number `n` |
3222 | `/note edit <n> <text>` | Replace note `n` with new text |
3223 | `/note remove <n>` | Delete note `n`; `rm` and `delete` are aliases |
3224 | `/note clear` | Empty the workspace notes file |
3225 | `/note path` | Show the resolved workspace notes path |
3226
3227 The numbers shown by `/note list` are not stored in the file; they are derived
3228 from the current order each time notes are read. This keeps the file format
3229 compatible with the existing `---`-separated notes.
3230
3231 ### User memory
3232
3233 User memory is split across one top-level path setting and one opt-in
3234 toggle table:
3235
3236 ```toml
3237 # Anchors the store only — actual writes go to
3238 # ~/.codewhale/memory/global/MEMORY.md (see MEMORY.md).
3239 memory_path = "~/.codewhale/memory.md"
3240
3241 [memory]
3242 enabled = true
3243 ```
3244
3245 Notes:
3246
3247 - `memory_path` stays at the top level beside `skills_dir`; it is not nested
3248 under `[memory]`.
3249 - The configured path is an **anchor**: its parent directory gains
3250 `memory/global/MEMORY.md`, workspace-scoped files, and `index.db`.
3251 Pointing `memory_path` at the native layout path itself would double-nest
3252 (`…/memory/global/memory/global/MEMORY.md`); keep the legacy-style
3253 anchor filename.
3254 - `DEEPSEEK_MEMORY_PATH` overrides the anchor path from the environment.
3255 - `DEEPSEEK_MEMORY=on` (also `1`, `true`, `yes`, `y`, or `enabled`)
3256 flips the feature on without editing `config.toml`.
3257 - The feature is inert when disabled: no file is injected, `# foo`
3258 falls through to normal message submission, and the model does not
3259 see the `remember` tool.
3260 - See [`MEMORY.md`](MEMORY.md) for examples and the full `/memory`
3261 command surface.
3262
3263 ### Goal loop (`[goal]`)
3264
3265 Goals run to their completion gate with no default token, time, or
3266 continuation ceiling (#5052). A token budget, when supplied, is telemetry
3267 unless `[goal] enforce_token_budget` is set. Users who want a circuit breaker
3268 can opt into one:
3269
3270 ```toml
3271 [goal]
3272 # Optional safety backstop on automatic goal continuation passes.
3273 # Default: 0 (unlimited). Set a positive value to opt into a ceiling.
3274 max_continuations = 100
3275
3276 # Optional cancellable quiet period between successful turns. This is useful
3277 # for coordinator goals that should poll on a cadence instead of keeping one
3278 # provider turn open. Default: 0 (continue immediately).
3279 continuation_delay_seconds = 300
3280
3281 # Optional per-turn model-step ceiling while a goal is active (#6512).
3282 # Default: uncapped (0 or absent). Positive values are preserved.
3283 # This bounds each provider turn, never the number of continuation passes.
3284 max_steps = 0
3285
3286 # Optional independent judges (#6013). Default: false (the model's own
3287 # update_goal call is final). When true, one adversarial critique of the claim
3288 # runs before `update_goal` completes (complete_judge) or blocks (blocked_judge)
3289 # the goal. Each judged call is billed as auxiliary usage.
3290 complete_judge = false
3291 blocked_judge = false
3292 ```
3293
3294 The effective delay is capped at 86,400 seconds (24 hours); use an automation
3295 for schedules that are less frequent than once per day.
3296
3297 When an explicit backstop fires, the goal pauses with a status message naming
3298 `[goal] max_continuations` and a warning is logged; resume the goal after
3299 inspecting progress, or raise/disable the backstop.
3300
3301 `[goal] max_steps` governs one engine turn at a time. Like ordinary interactive
3302 turns, omitted or `0` leaves model steps uncapped. Explicit per-invocation
3303 ceilings — `exec --max-turns N`, child-worker caps — always win over it. At exhaustion
3304 it gets one bounded final report and the turn classifies as budget-exhausted. An
3305 unfinished goal then pauses with the BudgetLimit reason instead of re-arming
3306 another goal turn — resume it explicitly after reviewing the report. Wall-clock
3307 and stream protections are separate and still apply.
3308
3309 With `[goal] complete_judge = true`, `update_goal(status: "complete")` spawns one
3310 read-only `verifier` sub-agent to inspect `git status`, `git diff HEAD`, recent
3311 commits, and named files with bounded checks before accepting completion. A
3312 refuted completion claim keeps the goal active, records the verifier's findings
3313 as critical gaps, and feeds prior gaps back by id on the next pass so repeated
3314 gaps still trip the no-progress pause. An unverifiable, malformed, or failed
3315 verdict hands the goal back as a yield instead of burning passes or completing
3316 silently. With `[goal] blocked_judge = true`, a refuted blocker keeps the goal
3317 active, and an unverifiable one hands the goal back as a yield that your next
3318 message resumes, naming the verifier's findings. The verifier gate applies in
3319 every mode, Plan included, and shifts judge usage from an auxiliary call to a
3320 normal child run. A judged claim on a goal that is not active, such as a paused
3321 one, changes nothing.
3322 When a judged claim arrives and sub-agents are unavailable in the session,
3323 nothing is applied and the goal is handed back as a yield. Limits: there is no
3324 goal baseline commit (attribution of older commits is by git log only), restored
3325 goals start with no prior gaps, and approval-gated checks are denied in
3326 sessions where nobody can answer. The operator
3327 `POST /v1/threads/{id}/goal/complete|block` routes and `/goal` commands stay
3328 ungated.
3329
3330 The delay starts only after a successful turn while an explicitly created goal
3331 is still active. `/goal pause`, `/goal done`, `/goal blocked`, `/goal clear`,
3332 Esc, or Ctrl+C cancels a pending continuation before another provider request
3333 starts. Failed turns and policy/route failures never schedule another turn.
3334 Only the numeric cadence is stored in config; no prompt, credential, or secret
3335 is persisted for the loop.
3336
3337 ### Reasoning-only recovery (`[reasoning_only]`)
3338
3339 When a model finishes with only reasoning and no answer or tool call, Codewhale
3340 can request an answer again. A clean stop permits two retries by default:
3341 the first keeps the request unchanged, and later retries carry a request-scoped
3342 nudge. The default nudge is `Continue: give your answer, or make the next tool call.`
3343
3344 ```toml
3345 [reasoning_only]
3346 max_reprompts = 2
3347 on_output_limit = false
3348 ```
3349
3350 Set `on_output_limit = true` to also retry `length`/`max_tokens` stops that
3351 produced no answer or tool call, including providers that did not stream their
3352 hidden reasoning. This option is off by default. Output-limit retries carry the
3353 nudge immediately and share the same `max_reprompts` allowance. Set
3354 `max_reprompts = 0` to disable both reasoning-only and output-limit recovery;
3355 transport and empty-stop recovery have their own existing limits.
3356
3357 This applies to ordinary interactive, exec and Runtime API engines and Fleet
3358 workers. Workers use the captured parent configuration. RLM keeps its separate
3359 completion/FINAL/REPL stop protocol and does not use this option.
3360
3361 Every retry is a fresh request and may repeat the model's reasoning. It does not
3362 carry hidden reasoning forward, raise output limits or bypass route, context,
3363 turn, cancellation or tool-admission controls. Each request can incur provider
3364 cost. Existing output-limit overrides still apply, and request preparation may
3365 reduce or refuse an allowance when input grows. Restart existing engines after
3366 changing these settings.
3367
3368 The nudge appears in one outbound request without joining conversation history
3369 or later resumed model context. Retry status retains its stable protocol prefix
3370 and localizes its human text. Its receipt is visible in the transcript; Fleet
3371 also stores an owner-bound prepared-request receipt in its existing private
3372 artifact before dispatch. A prepared receipt does not claim a completed model
3373 call. Existing version-1 artifacts remain readable.
3374
3375 To customize or disable the nudge:
3376
3377 ```toml
3378 [reasoning_only]
3379 reprompt_message = "Give your answer, or make the next tool call."
3380 ```
3381
3382 An empty `reprompt_message = ""` disables the nudge, including on output-limit
3383 retries; the retry still counts against `max_reprompts` and uses the unchanged
3384 request. Configuration with recovery enabled does not guarantee the model will
3385 complete a long proof within its allowance.
3386
3387 ### Notifications
3388
3389 Notification controls are available in the existing `/config` settings view,
3390 from terminal commands, and through the CLI. All write the same `config.toml`
3391 keys. Terminal changes apply immediately; add `--save` to keep them. CLI writes
3392 apply when the next process loads its configuration.
3393
3394 ```sh
3395 codewhale config set notifications.sound whale
3396 codewhale config set notifications.events.approval-needed false
3397 codewhale config set notifications.quiet true
3398 codewhale config get notifications
3399 codewhale config unset notifications.quiet
3400 ```
3401
3402 ```text
3403 /config notifications sound whale --save
3404 /config notifications condition unfocused --save
3405 /config notifications quiet true
3406 /config notifications status
3407 ```
3408
3409 Nested CLI edits preserve TOML types, unrelated keys and comments. Unset removes
3410 only the selected leaf. `notifications.sound legacy` in the TUI, or CLI unset of
3411 `notifications.sound`, restores previous sound choices. Invalid values are
3412 rejected before file or session changes. In an active TUI profile, saved edits
3413 update its notification table when it owns one; otherwise they update the
3414 inherited root table. The settings detail keeps saved and current values distinct.
3415
3416 ```toml
3417 [notifications]
3418 method = "auto" # auto | osc9 | kitty | ghostty | bel | off
3419 condition = "unfocused" # unfocused | always | never
3420 threshold_secs = 30
3421 include_summary = false
3422 sound = "whale" # optional; sound is opt-in, not enabled by default
3423 quiet = false
3424
3425 [notifications.events]
3426 turn-complete = true
3427 subagent-terminal = true
3428 approval-needed = true
3429 input-needed = true
3430 elevation-needed = true
3431 model-notify = true
3432 ```
3433
3434 `quiet = true` mutes every category without changing saved choices. `method =
3435 "off"` also stops both banner and selected audio. Disabling a category stops its
3436 sound. Attention and duration gates apply before any sink runs. Title animation
3437 completion is silent; only the authorized notification event can request audio.
3438 Successful turn completion is a notification category; failed/cancelled turns do
3439 not create a success notification.
3440
3441 `auto` chooses a recognized terminal protocol or the existing macOS native
3442 fallback; unknown terminals remain unsupported and never invent a bell. `bel`
3443 is an audio-only transport: one selected cue is dispatched, without a second
3444 transport bell. With `sound = "off"`, that transport is silent. `osc9`, `kitty`
3445 and `ghostty` use their terminal notification protocols; tmux passthrough is
3446 preserved. Terminal/OS notification preferences still govern display, attribution
3447 and any sound the host itself adds.
3448
3449 By default the terminal must stay unfocused for two seconds. `condition =
3450 "always"` allows foreground notifications and bypasses the duration threshold;
3451 `"never"` suppresses all delivery. The canonical condition takes precedence over
3452 legacy `[tui].notification_condition`.
3453
3454 The bundled `whale` is a 1.55-second original whale-inspired cue, with no
3455 third-party recording. It remains an opt-in candidate pending listening approval.
3456 WAV playback uses a background worker: macOS `/usr/bin/afplay`, Linux `aplay`
3457 from [ALSA utilities](https://github.com/alsa-project/alsa-utils), or Windows
3458 `PlaySoundW`. A missing player/file or unsupported platform has no fallback bell.
3459 Only one WAV plays at a time. A worker-start receipt is a dispatch attempt, not
3460 proof of audible playback or OS acceptance. The existing macOS `osascript`
3461 banner retains Script Editor attribution; this Core change does not provide a
3462 branded native Apps banner.
3463
3464 #### Previous sound settings
3465
3466 When `notifications.sound` is absent, completion uses a non-off
3467 `completion_sound` selection, and other events use the existing event allow-list.
3468 These are compatibility inputs to the same audio decision, not separate playback
3469 paths. When the global sound is selected, it takes precedence over the previous
3470 completion/event choices. The default remains silent unless a legacy sound or
3471 explicit `bel` transport was already selected.
3472
3473 ```toml
3474 [notifications.event_sound]
3475 enabled = false
3476 events = ["turn-complete", "approval-needed"]
3477 min_interval_ms = 2000
3478 quiet = false
3479 ```
3480
3481 Legacy event cues use one bell for completion, subagent completion, input and
3482 model notices; approval/elevation cues use two. The per-category repeat interval
3483 survives settings refreshes. Old unknown event names are ignored on load; new
3484 CLI/TUI edits require names from the six categories above.
3485
3486 Local approval/input/elevation prompts and error receipts remain available when
3487 external notifications are muted. Action prompts use the selected UI language
3488 and retire when that request settles. Repeated live notices keep their first
3489 expiry; a later routine update does not hide an unresolved warning at completion.
3490 Optional plugin suggestion toasts and contextual tips share one session guidance
3491 budget. `/config contextual_tips off` hides those toasts while preserving
3492 required notices and explicit plugin review requests.
3493
3494 #### What a notification can contain
3495
3496 A desktop notification is a glance surface: on macOS it can appear on the
3497 lock screen, and on every platform it is visible to anyone near the machine.
3498 Codewhale therefore builds notifications from a typed payload with a fixed
3499 per-event disclosure policy rather than from whatever text was on hand:
3500
3501 | Event | Shown | Never shown |
3502 |---|---|---|
3503 | Turn complete | status line (+ elapsed/cost when `include_summary`), preview of the assistant's reply | — |
3504 | Sub-agent finished | status line, agent id, preview of the child's summary line | — |
3505 | Approval needed | the tool name | the tool description, the command, the arguments |
3506 | Input needed | "Answer the question in the terminal to continue" | the question |
3507 | Sandbox elevation needed | the tool name and the denial reason | the command |
3508 | `notify` tool | model-supplied title and body | — |
3509
3510 Every field is capped (80 characters for the status line, 120 for the
3511 identifier, 200 for the preview), stripped of control bytes and escape
3512 sequences, and passed through a redactor that replaces credential-shaped
3513 strings with `[redacted]`, reduces absolute local paths to `…/basename`,
3514 and replaces raw tool JSON with `[details hidden]`. The redactor is
3515 deliberately over-eager: an unbroken 40-character run has no word
3516 structure, so it is redacted even when it is not a secret.
3517
3518 #### macOS: why the banner says "Script Editor"
3519
3520 On macOS terminals that provide no notification escape of their own —
3521 Apple Terminal, the VS Code and JetBrains embedded terminals, plain tmux
3522 without `LC_TERMINAL` — `method = "auto"` falls back to `osascript`'s
3523 `display notification`. That command posts on behalf of the *bundled*
3524 host process, and `/usr/bin/osascript` is unbundled, so macOS attributes
3525 the banner to `com.apple.ScriptEditor2`. That attribution supplies the
3526 Script Editor icon and owns the System Settings → Notifications entry
3527 (alert style, previews, Do Not Disturb). `display notification` has no
3528 icon parameter, so this cannot be fixed from the notification code; it
3529 needs Codewhale to ship a real `.app` bundle. Tracked in
3530 [#4834](https://github.com/codewhale-hq/CodeWhale/issues/4834). In the meantime,
3531 iTerm2, WezTerm, Ghostty, and kitty are matched first and use their own
3532 notification protocols, and `method = "osc9"` / `"bel"` / `"off"` opt out
3533 of the `osascript` path explicitly.
3534
3535 ## Automations in the terminal
3536
3537 Open `/automation`, then choose **New automation** (`n`) or **Edit automation**
3538 (`e`). The form edits the name, multiline prompt, schedule, model, workspace,
3539 and enabled status. `Tab` moves between fields; `Enter` inserts a newline in
3540 the prompt. Schedule presets include daily, weekly, hourly, once, and a custom
3541 RRULE. Time fields accept `HH:MM`; their arrow controls change the time by
3542 15 minutes. Weekly day buttons and model search support mouse and keyboard.
3543
3544 The next-run preview uses the scheduler's local time zone, shown with its UTC
3545 offset. An enabled automation can run after **Save** (`Ctrl+S`); a paused one
3546 has no scheduled next run. **Cancel** (`Esc`) discards the draft. Editing keeps
3547 existing permission settings, custom schedules, and additional workspace
3548 entries unless the corresponding supported field is explicitly changed.
3549 Scheduled automations do not run with Full Access, the trust setting or shell:
3550 one saved earlier with any of them is listed as paused with the reason, and
3551 resumes only after those settings are removed (for example with `PATCH
3552 /v1/automations/{id}` on the Runtime API).
3553
3554 Schedules are evaluated in the machine's local time zone against the wall
3555 clock. A wall time that does not exist on a spring-forward day is skipped and
3556 an ambiguous fall-back time fires once. Occurrences missed while Codewhale was
3557 closed, asleep, or still running the previous occurrence are coalesced: the
3558 next start runs one catch-up occurrence and then continues from the next
3559 future slot, never replaying every missed slot. An occurrence never starts
3560 while an earlier run of the same automation is still queued or running. Each
3561 run is recorded durably with its status, timing and error; a run that needs a
3562 tool approval has no operator to ask and fails once the approval wait expires.
3563
3564 Choosing a concrete model pins both the model and its exact configured
3565 provider, including named custom routes. Later changes to the active provider
3566 do not move that automation's pin. The default-model choice and legacy
3567 definitions without a provider pin keep the runtime's existing default
3568 behavior. New automation records use schema v2 and tasks use v3 so older
3569 runtimes reject records whose provider pins they cannot preserve.
3570
3571 ## Lifecycle Outbox (`[lifecycle_outbox]`)
3572
3573 The lifecycle outbox is an opt-in, machine-readable stream of session,
3574 turn, and sub-agent lifecycle events. With a path configured, Codewhale
3575 appends one JSON line per event to that file — for interactive TUI
3576 sessions *and* headless `codewhale exec` runs — so a supervisor
3577 (terminal multiplexer wrapper, automation harness, alerting setup) can
3578 react to what happened without scraping the screen or installing per-hook
3579 shell commands. Unset or empty `path` = the feature is **off** and
3580 behavior is unchanged.
3581
3582 ```toml
3583 [lifecycle_outbox]
3584 path = "~/.codewhale/notifications/outbox.jsonl" # unset/empty = OFF
3585 webhook_url = "" # optional; POSTs events as JSON when set
3586 webhook_token = "" # optional bearer token for webhook_url
3587 ```
3588
3589 ### Events emitted
3590
3591 | Event | Kind | Fired at |
3592 |---|---|---|
3593 | `turn_start` | `turn.started` | a new turn begins (TUI TurnStarted; `exec` at message dispatch) |
3594 | `turn_end` | `turn.completed` / `turn.failed` / `turn.interrupted` | turn completion, kind projected from the turn status |
3595 | `turn_stalled` | `turn.stalled` | the stall watchdog recovers a wedged turn |
3596 | `subagent_spawn` | `subagent.spawned` | a sub-agent is spawned |
3597 | `subagent_complete` | `subagent.completed` | a sub-agent reaches a terminal state |
3598 | `session_start` | `session.started` | interactive session start |
3599 | `session_end` | `session.ended` | interactive session end |
3600
3601 ### File contract
3602
3603 Each line is a `RuntimeEventEnvelope`:
3604
3605 ```json
3606 {"schema_version": 1, "seq": 3, "event": "turn_start", "kind": "turn.started",
3607 "thread_id": "…", "turn_id": "…", "item_id": null, "timestamp": "…",
3608 "created_at": "…", "payload": {…}}
3609 ```
3610
3611 - `seq` is monotonic per outbox file and recovers from the last written
3612 line when a new process opens the file.
3613 - Lines are written one complete JSON line per append, serialized by an
3614 internal writer task and flushed before the next event; concurrent
3615 sessions writing the same path do not interleave bytes mid-line, but
3616 separate processes each continue from their own recovered `seq`, so seqs
3617 can repeat across processes sharing one file — prefer one file per
3618 process for strict uniqueness.
3619 - Parent directories are created lazily on the first event.
3620 - Payloads are constructed from bounded, pre-redacted fields only — never
3621 raw tool arguments, environment, or full transcript text. Free-form
3622 fields (error messages, previews) are capped at the notification limits
3623 (80 headline / 120 detail / 200 preview characters) and stripped of
3624 control bytes.
3625
3626 ### Webhook delivery
3627
3628 With `webhook_url` set, every event is additionally POSTed as
3629 `{"at": "<ISO 8601 timestamp>", "event": {…}}` with
3630 `Authorization: Bearer <webhook_token>` when a token is configured.
3631 Delivery is best-effort: failures are logged and dropped, never retried
3632 into the agent loop, and a failing webhook never blocks the local file
3633 append.
3634
3635 ## Control Socket (`[control_socket]`)
3636
3637 Per-session control surface for supervised operation: with the feature
3638 enabled, the interactive TUI binds one unix domain socket per *running*
3639 session at `<sessions-dir>/<session-id>/control.sock` (mode `0600`;
3640 `<sessions-dir>` is the same directory the session store uses, typically
3641 `~/.codewhale/sessions`). The socket is removed with the session's
3642 artifact directory, and a stale socket left by a crashed process is taken
3643 over by the next launch. Unset or `enabled = false` = the feature is
3644 **off** (the default) and behavior is unchanged. Unix-only; on other
3645 platforms the key parses but no socket is bound.
3646
3647 ```toml
3648 [control_socket]
3649 enabled = false # default: OFF
3650 ```
3651
3652 The socket speaks newline-framed JSON-RPC, one request per connection:
3653 write one request line, read one response line, close.
3654
3655 ```json
3656 {"id":"1","method":"message","params":{"text":"hello"}}
3657 {"id":"2","method":"interrupt","params":{}}
3658 {"id":"3","method":"status","params":{}}
3659 ```
3660
3661 - `message` — delivers `text` as a structured user message through the
3662 ordinary composer dispatch path; dispatched immediately when idle,
3663 queued when a turn is in flight (the response's `delivery` field says
3664 which).
3665 - `interrupt` — the Esc-shaped cancel of the active turn; `cancelled`
3666 reports whether active work was in flight.
3667 - `status` — answers `turn_state` (`idle` / `in_progress` / `waiting`) and
3668 `goal` (`objective`, `status`, `paused`).
3669
3670 Success responses echo the request id with a `type`-tagged result;
3671 failures carry `error.code` (`invalid_request`, `command_error`,
3672 `timeout`, `server_unavailable`). Requests are bounded at 1 MiB per line
3673 and a handler that does not answer within 5 s is reported as `timeout`.
3674
3675 ## Tool Catalog
3676
3677 Codewhale loads a small core native tool catalog by default and leaves less
3678 common native tools discoverable on demand. Exact (non-wildcard) tool names in
3679 `allowed_tools` or a child's explicit tool scope are also loaded eagerly. To
3680 keep specific deferred tools loaded on every request, add them to
3681 `[tools].always_load`:
3682
3683 ```toml
3684 [tools]
3685 always_load = ["Git", "notify"]
3686 ```
3687
3688 ### Script tools and overrides
3689
3690 Scripts in `~/.codewhale/tools/` (or `[tools].plugin_dir`) that start with a
3691 `# name:` header become model-visible tools, and `/plugin tools` lists them.
3692 The script reads the tool's JSON input on stdin and writes a JSON
3693 `ToolResult` (`{"content": "...", "success": true}`) on stdout.
3694
3695 ```sh
3696 #!/usr/bin/env sh
3697 # name: word_count
3698 # description: Count words in the given text
3699 # schema: {"type":"object","properties":{"text":{"type":"string"}}}
3700 # approval: required
3701 ```
3702
3703 `# approval:` takes `suggest` (the default) or `required`; either way the
3704 tool follows the session's approval setting. A script cannot approve itself:
3705 `approval: auto` is no longer supported, so such a script gets the default,
3706 and the runtime log (`~/.codewhale/logs/`) and `/plugin tools` name it.
3707
3708 A script cannot replace a built-in tool either. A script whose `# name:` is
3709 already registered is not loaded. `[tools.overrides]` may disable a built-in,
3710 or add a script or command tool under a name of its own:
3711
3712 ```toml
3713 [tools.overrides]
3714 "Web" = { type = "disabled" } # turn a built-in off
3715 "audited_shell" = { type = "script", path = "audit-shell.sh" } # a new tool
3716 "Bash" = { type = "script", path = "audit-shell.sh" } # refused: Bash is built in
3717 ```
3718
3719 A `script` or `command` override keyed by a built-in is refused, and the
3720 built-in stays active. A status line names the key once per session, and the
3721 runtime log records it. To route a
3722 built-in through your own wrapper, disable the built-in and register the
3723 wrapper under a new name. An override keyed by a drop-in script's name still
3724 replaces that script. Relative `path` values resolve against the plugin
3725 directory.
3726
3727 ### `request_user_input` limits
3728
3729 `request_user_input` asks the user a short batch of multiple-choice questions.
3730 Both ceilings are configurable (#5949): raise `user_input_max_questions` when a
3731 research or planning workflow legitimately needs more clarifications, lower it
3732 when interactive triage should stay terse.
3733
3734 ```toml
3735 [tools]
3736 user_input_max_questions = 6 # default 6, clamped to 1..=10
3737 user_input_max_options = 4 # default 4, clamped to 2..=10
3738 ```
3739
3740 The effective values are applied in three places at once: the tool's JSON
3741 schema (`minItems` / `maxItems`), its model-visible description, and the
3742 payload validator. A rejected payload names the key to raise, so the model can
3743 either resize the batch or tell the user which setting to change.
3744
3745 ### User-input wait timeout
3746
3747 Questions from `request_user_input` wait until answered or canceled by default
3748 (#6003). An omitted setting or `0` leaves the wait unbounded; a positive value
3749 cancels the question when that many seconds pass, capped at 86,400 (24 hours).
3750 Headless `exec` runs have no
3751 responder, so `request_user_input` is withheld there by default:
3752 the model reports the tool absent and finishes instead of stalling.
3753
3754 ```toml
3755 [tools]
3756 user_input_timeout_seconds = 300 # opt into 5 minutes; omitted or 0 waits indefinitely; maximum 86400
3757 ```
3758
3759 `task_human_wait_cap_seconds` is a separate, fail-safe ceiling for durable
3760 tasks run by the runtime API server. While a task waits on an approval or
3761 user-input answer its wall clock is paused; if nobody answers within this many
3762 seconds the task fails with `human_wait_timeout` and releases its worker.
3763 Omitted or `0` uses 1800 (30 minutes); values are clamped to `1..=86400`.
3764
3765 ```toml
3766 [tools]
3767 task_human_wait_cap_seconds = 3600 # optional; default 1800
3768 ```
3769
3770 `max_parallel_shell_exec` bounds how many shell commands one parallel tool wave
3771 runs at the same time; the rest of the wave waits for a slot. Omitted or `0`
3772 uses 4; values above 32 are clamped to 32.
3773
3774 ```toml
3775 [tools]
3776 max_parallel_shell_exec = 8 # optional; default 4
3777 ```
3778
3779 `user_input_timeout_seconds` governs question waits only. Approvals have their own clock,
3780 `[approval] timeout_seconds`, which waits indefinitely unless you set it.
3781 Wall-clock and stream protections elsewhere are unaffected.
3782
3783 ## Feature Flags
3784
3785 Feature flags live under the `[features]` table and are merged across profiles.
3786 Defaults are enabled for built-in tooling, so you only need to set entries you
3787 want to force on or off.
3788
3789 ```toml
3790 [features]
3791 shell_tool = true
3792 subagents = true
3793 web_search = true # enables deferred Web; the flag name is retained for config compatibility
3794 apply_patch = true
3795 mcp = true
3796 exec_policy = true
3797 code_mode = true # execute_tools composes MCP/plugin/native calls; false defers it behind tool_search
3798 vision_model = false # true routes image analysis to the [vision_model] model (see above)
3799 extension_host = false # experimental: run reviewed plugins' native code (see EXTENSIONS.md)
3800 plugin_creator = true # beta, on by default: built-in plugin_manager tool and Creator mode host module
3801 ```
3802
3803 `code_mode` is on by default: `execute_tools` is advertised from the first
3804 request in place of `tool_search`, and nested calls go through the same
3805 permission gate as direct calls
3806 (see [Tool surface](TOOL_SURFACE.md#code-mode-execute_tools)). Set
3807 `code_mode = false` to defer it behind `tool_search` again.
3808
3809 `extension_host` is experimental and off by default. Turning it on lets reviewed
3810 plugins run their `native` TypeScript/JavaScript tool and slash-command code in
3811 a separate Node (or, opt-in, Bun) process; toggling it in either direction
3812 changes the plugin activation policy, so every plugin is reviewed again after a
3813 restart. Its `[extension_host]` table (`runtime`, `node`, `bun`) and what the
3814 host's sandbox does on each platform are in
3815 [Writing a plugin tool](EXTENSIONS.md).
3816
3817 `plugin_creator` is beta and on by default. Keeping it on enables the
3818 built-in `plugin_manager` tool and Creator mode host module independently of
3819 `extension_host` (when a supported Node.js or Bun runtime is present and
3820 Creator availability admits it). Setting `plugin_creator = false` turns off
3821 the built-in Creator host module and marks Creator mode unavailable.
3822
3823 `[extension_host] mcp_backend` (user config only) chooses the MCP client
3824 independently of the `extension_host` flag: `"host"` (default) uses the official
3825 MCP SDK behind the Rust broker; `"rust"` keeps the previous Rust client for one
3826 release. A host refusal never falls back to Rust. See
3827 [MCP connection lifecycle](MCP.md#connection-lifecycle).
3828
3829 Every flag has a row in [`docs/features.toml`](features.toml), the feature
3830 registry; a test fails when a flag and its row disagree.
3831
3832 You can also override features for a single run:
3833
3834 - `codewhale --enable web_search`
3835 - `codewhale --disable subagents`
3836
3837 Use `codewhale features list` to inspect known flags and their effective state.
3838 The native `/config` view also includes a read-only **Experimental** section
3839 for experimental feature flags. It shows each flag's effective enabled/disabled
3840 state and whether that state comes from the default or a configured override.
3841 Change feature flags in `[features]` or with `--enable` / `--disable`; the
3842 `/config` section is an audit surface, not a stability promise. Goal and
3843 Workflow preview rows may appear there as reserved entries until those workflows
3844 graduate behind real gated flags.
3845
3846 ## Web Search Provider
3847
3848 `web_search` uses keyless Firecrawl by default. Runtime failure or an exhausted
3849 keyless quota degrades visibly through DuckDuckGo and Bing. China deployments
3850 can explicitly select Baidu, Metaso, Volcengine, or a trusted SearXNG endpoint;
3851 Codewhale does not guess geography from locale or model provider.
3852
3853 Configured API providers are attempted first. Runtime failure or an empty
3854 result visibly degrades through DuckDuckGo and then Bing; the structured search
3855 receipt records every hop. Missing configuration and network-policy denials
3856 fail closed without sending the query to another provider.
3857
3858 **Third-party search consent.** `[search] third_party` decides whether a
3859 search may be sent to a third-party search service: every backend except the
3860 active route's provider-native search and a self-hosted `base_url` endpoint
3861 (SearXNG, or a DuckDuckGo-compatible endpoint with `provider = "duckduckgo"`).
3862 Keyless Firecrawl, DuckDuckGo and Bing scraping and the keyed services are
3863 third-party.
3864
3865 - `"ask"` (default): the first search that would use a third-party service in
3866 an interactive session raises a **Third-party web search** card: choose the
3867 search provider agents use (or **Any**), then **Enable** or **Don't use
3868 search**. Enable saves `third_party = "on"` (and `provider` when you choose
3869 one), and the search then gets the approval it would have had with `"on"`:
3870 in a posture that asks before a web search, its own approval card follows.
3871 Don't use search saves `third_party = "off"` and the agent continues without
3872 searching. A remembered approval never answers this card, and a timeout or a
3873 stopped turn saves nothing. If config.toml cannot be written, the choice
3874 still applies for the rest of the session, sub-agents included. In the TUI
3875 the card ignores Enter, its letter shortcuts and clicks for a moment after it
3876 appears, so typing ahead cannot answer it.
3877 - `"on"`: third-party search runs without asking.
3878 - `"off"`: no third-party search service is contacted; provider-native search
3879 and a self-hosted `base_url` still work.
3880
3881 When the key is unset and search is already set up — a pinned `provider`,
3882 `CODEWHALE_SEARCH_PROVIDER`, a Tavily key, `[search] api_key` /
3883 `CODEWHALE_SEARCH_API_KEY`, or `FIRECRAWL_API_KEY` — it behaves as `"on"`.
3884 Unattended runs (`codewhale exec`, automations and other turns with nobody to
3885 answer) never raise the card, and for them `"ask"` behaves as `"on"`.
3886 Sub-agents and Fleet workers never raise it either; a sub-agent of an
3887 interactive session follows the person's answer and, until there is one, does
3888 not contact a third-party search service. `"off"` is honored everywhere. Change it with
3889 `/config search.third_party ask|on|off`; `ask` removes the key. Running
3890 sessions read it again before each web search.
3891
3892 **Provider-native search.** On routes whose provider offers its own web-search
3893 tool (OpenAI, xAI, Anthropic, DeepSeek, Kimi and others), that search can run
3894 ahead of the configured provider. It is a separate model call on the active
3895 route. `[search] native` decides the order:
3896
3897 - unset (default): native search leads only when no search provider is
3898 configured; a provider chosen in `[search] provider`,
3899 `CODEWHALE_SEARCH_PROVIDER`, or a Tavily key wins;
3900 - `native = true`: native search leads even when a provider is pinned;
3901 - `native = false`: native search is never used.
3902
3903 Native citations are link-checked before they are returned. Each cited URL is
3904 requested through the same guarded fetch as `Web` fetch (SSRF, DNS and redirect
3905 checks, `[network]` policy): a `HEAD`, then a one-byte ranged `GET` when `HEAD`
3906 is refused, at most four at a time and five seconds each. The request uses the
3907 address as it will appear in `results`, without userinfo, fragment or
3908 credential-like query parameters; an address whose query string repeats the
3909 search query is not requested and is removed. Only sources that
3910 answer with a 2xx status stay in `results`; the receipt lists each removed one
3911 as `citation_unverified` with its reason. When no citation passes, or when the
3912 query asks for `recency` (no native search tool can enforce a time window), the
3913 search falls through to the configured provider. A citation whose host the
3914 `[network]` policy denies is removed. A citation whose host the policy would
3915 ask you about is not fetched: it stays in `results` and the receipt records it
3916 as `citation_unchecked` until you allow the host.
3917
3918 The provider's prose answer is returned whole in a separate
3919 `unverified_synthesis` field: it is the provider model's summary, and neither
3920 its claims nor its links are checked. Oversized tool output spills to a session
3921 artifact the model can page back.
3922
3923 **Recency and locale.** `recency` and `locale` are forwarded where the
3924 backend's API takes them, and the search receipt reports each as honored or
3925 ignored:
3926
3927 | Backend | Recency | Locale |
3928 | --- | --- | --- |
3929 | Firecrawl | `tbs=qdr:d/w/m/y` | `country` from the region (`de-DE` → `DE`); a bare language is ignored |
3930 | Tavily | `time_range` | not sent (Tavily takes country names) |
3931 | SearXNG | `time_range` | `language`, as given |
3932 | Serply | not sent (undocumented) | `hl` language, `gl` country |
3933 | SearchApi | `time_period=last_day/last_week/last_month/last_year` | `hl` language, `gl` country |
3934 | DeepSeek | not sent | not sent (`localization` takes an IP address) |
3935 | Provider-native | declined; the search falls through to the configured provider | not sent |
3936
3937 Recency is rounded up to the backend's nearest window (day, week, month,
3938 year), so `recency = 10` searches the last month. Other backends ignore both
3939 knobs and say so in the receipt.
3940
3941 For a private/internal search service that serves DuckDuckGo-compatible HTML,
3942 keep `provider = "duckduckgo"` and set `base_url`; Codewhale appends the `q`
3943 query parameter to that endpoint and applies network policy to its host.
3944 Custom endpoints do not fall back to public Bing. `CODEWHALE_SEARCH_BASE_URL`
3945 can override this per process; `DEEPSEEK_SEARCH_BASE_URL` remains accepted as
3946 the legacy alias.
3947
3948 **SearXNG** ([docs](https://docs.searxng.org/dev/search_api.html)) uses the
3949 configured instance's JSON API. Set `provider = "searxng"` and
3950 `base_url = "https://your-searxng.example"`; Codewhale calls
3951 `/search?q=...&format=json`. Codewhale does not use a public SearXNG instance
3952 by default because public instances often disable JSON output or rate-limit API
3953 traffic.
3954
3955 Self-host it as a separate process (Docker is fine); Codewhale never bundles or
3956 manages the search engine itself:
3957
3958 - Enable JSON on the instance (`settings.yml`, `search.formats` must include
3959 `json`) and restart it. An HTML-only instance answers the API with HTTP 403;
3960 Codewhale reports that as a JSON/API-access problem on the SearXNG hop rather
3961 than silently returning no results.
3962 - Bind it to loopback, or to a host and port your network policy allows. The
3963 instance keeps its own engine list, limiter, and limits.
3964 - Point Codewhale at it with `[search] provider = "searxng"` and `base_url`
3965 (required; either the root URL or the `/search` endpoint). No instance ships
3966 as a default, and none is discovered automatically.
3967 - `codewhale doctor --probe-search` sends a transport-only `HEAD` to that
3968 origin — no `q=`, no credentials, no redirects, no audit receipt — so a green
3969 probe proves reachability and network-policy admission, not that JSON is on.
3970
3971 Confirm the JSON API itself before assuming a Codewhale bug:
3972
3973 ```sh
3974 curl -sS "$BASE/search?q=codewhale&format=json" | jq '.results[0] | {title,url,score}'
3975 ```
3976
3977 Codewhale ranks the returned rows by `score`, highest first, and applies
3978 `max_results` to that ranking; rows an instance reports without a usable score
3979 keep their original relative order.
3980
3981 **Metaso** ([metaso.cn](https://metaso.cn)) requires a user-supplied key. Set
3982 `METASO_API_KEY` or `[search] api_key`; Codewhale does not ship a shared key.
3983
3984 **Firecrawl** ([docs](https://docs.firecrawl.dev/sdks/cli)) searches Firecrawl
3985 Cloud without a key using its bounded per-IP daily quota. Set
3986 `FIRECRAWL_API_KEY` or `[search] api_key` for authenticated limits. Codewhale
3987 sends no `Authorization` header in keyless mode.
3988
3989 **Baidu** uses Baidu AI Search at
3990 `https://qianfan.baidubce.com/v2/ai_search/web_search`. Set
3991 `BAIDU_SEARCH_API_KEY` or `[search] api_key`. This is a search-tool backend
3992 only; it does not add a Baidu model provider.
3993
3994 **Sofya** ([sofya.co](https://sofya.co)) returns full extracted page content
3995 rather than snippets. Set `[search] api_key` to your `ay_live_...` key, or the
3996 `SOFYA_API_KEY` env var. This is a search-tool backend only; it does not add a
3997 Sofya model provider.
3998
3999 **Serply** ([serply.io](https://serply.io)) returns Google organic results with
4000 title, URL, and snippet. Set `[search] api_key` to your Serply key, or the
4001 `SERPLY_API_KEY` env var. This is a search-tool backend only; it does not add a
4002 Serply model provider.
4003
4004 **SearchApi** ([searchapi.io](https://www.searchapi.io)) returns Google organic
4005 results with title, URL, and snippet from
4006 `GET https://www.searchapi.io/api/v1/search?engine=google`. Set `[search] api_key`
4007 to your SearchApi key, or the `SEARCHAPI_API_KEY` env var. The API honors `num`
4008 up to 10 and clamps larger values. A query Google answers with nothing comes
4009 back as HTTP 200 without `organic_results`; Codewhale treats that as zero
4010 results (so the usual DuckDuckGo degradation applies), not as an error. Some
4011 lower-ranked rows carry a `google.com/goto?url=...` redirect as their link; they
4012 are passed through unchanged. This is a search-tool backend only; it does not
4013 add a SearchApi model provider.
4014
4015 **DeepSeek** ([docs](https://api-docs.deepseek.com/guides/search)) uses
4016 `POST https://api.deepseek.com/v1/tools/search`. Set `provider = "deepseek"`
4017 (`deep-seek` and `deepseek-search` are also accepted) and supply `[search] api_key`
4018 or the `DEEPSEEK_API_KEY` env var, in that order. The saved DeepSeek model-provider
4019 key is not reused by this search backend. Queries are truncated to 128 Unicode
4020 characters. The backend clamps counts to 1–50; the shared search tool currently
4021 caps requests at 10 results. Query operators such as `site:`, `lang:`,
4022 `after:`, and `before:` are passed through; the `recency` and `locale` knobs are
4023 ignored. Results include title, URL, and snippet, falling back to summary when a
4024 snippet is empty.
4025
4026 **Tavily** ([tavily.com](https://tavily.com)) is selected automatically when a
4027 Tavily key is present and no provider is pinned: `TAVILY_API_KEY` set, or
4028 `[search] api_key` / `CODEWHALE_SEARCH_API_KEY` in the `tvly-` family. Doctor
4029 reports that as `source: tavily key`. Autodetect is runtime-only — Codewhale
4030 never writes `[search] provider` for it, and `TAVILY_API_KEY` is never merged
4031 into `[search] api_key`. An explicit `[search] provider` or
4032 `CODEWHALE_SEARCH_PROVIDER` always wins, so `provider = "firecrawl"` keeps
4033 Firecrawl even with a Tavily key in the environment. Pinned `tavily` accepts
4034 any non-empty `[search] api_key` and is configured by that key or
4035 `TAVILY_API_KEY`; with both empty it fails closed.
4036
4037 ```toml
4038 [search]
4039 provider = "firecrawl" # also duckduckgo | bing | tavily | bocha | metaso | searxng | baidu | volcengine | sofya | serply | deepseek | searchapi
4040 # base_url = "https://search.example/" # optional with provider = "duckduckgo"; required with "searxng"
4041 # api_key = "YOUR_KEY" # optional for firecrawl; required by the other API providers
4042 # native = false # provider-native search: unset = only when no provider is configured
4043 # third_party = "ask" # ask | on | off: may searches go to a third-party service
4044 ```
4045
4046 ## Local Media Attachments
4047
4048 Use `@path/to/file` in the composer to add local text file or directory context
4049 to the next message. Use `/attach <path>` for local image/video media paths, or
4050 `Ctrl+V` to attach an image from a local clipboard or an explicitly forwarded
4051 X11/Wayland clipboard. SSH terminal paste without a forwarded graphical display
4052 is text-only; use the local terminal's paste command (`Cmd+V` on macOS or
4053 `Ctrl+Shift+V` on Linux/Windows), and use `/attach <path>` for remote image
4054 files. OpenSSH loopback X11 displays are detected automatically. For an
4055 explicitly forwarded Wayland or non-loopback X11 display, set
4056 `CODEWHALE_SSH_CLIPBOARD=graphical`; set it to `terminal` to force terminal
4057 transfer instead of an ambient remote display. DeepSeek's public Chat
4058 Completions API currently accepts text message
4059 content, so media attachments are sent as explicit local path references instead
4060 of native image/video payloads.
4061 Attachment rows appear above the composer before submit; move to the start of
4062 the composer, press `↑` to select an attachment row, then press `Backspace` or
4063 `Delete` to remove it without editing the sample text by hand.
4064
4065 ## Managed Configuration and Requirements
4066
4067 codewhale supports a policy layering model:
4068
4069 1. user config + profile + env overrides
4070 2. managed config (if present)
4071 3. requirements validation (if present)
4072
4073 By default on Unix:
4074 - managed config: `/etc/deepseek/managed_config.toml`
4075 - requirements: `/etc/deepseek/requirements.toml`
4076
4077 Requirements file shape:
4078
4079 ```toml
4080 allowed_approval_policies = ["on-request", "untrusted", "never"]
4081 allowed_sandbox_modes = ["read-only", "workspace-write"]
4082 ```
4083
4084 If configured values violate requirements, startup fails with a descriptive error.
4085
4086 Any `sandbox_denied_read_paths` set in managed (or user) configuration apply to
4087 Codewhale's built-in read-side tools (listed under the read deny-list above) and
4088 to sandboxed shell commands only. Full
4089 Access with its default `danger-full-access` sandbox (not a narrower configured
4090 `sandbox_mode`), `external-sandbox` and a missing wrapper run shell
4091 commands without the local sandbox wrapper, so the read deny-list does not stop
4092 shell reads there, and it does not apply to MCP servers.
4093
4094 ## Notes On `codewhale doctor`
4095
4096 `codewhale doctor` follows the same config resolution rules as the rest of the
4097 TUI. That means `--config`, `CODEWHALE_CONFIG_PATH`, and the legacy
4098 `DEEPSEEK_CONFIG_PATH` are respected, and MCP/skills
4099 checks use the resolved `mcp_config_path` / `skills_dir` (including env overrides).
4100
4101 To bootstrap missing MCP/skills paths, run `codewhale setup --all`. You can
4102 also run `codewhale setup --skills --local` to create the owned project
4103 `.codewhale/skills` directory. Project skills load after workspace trust.
4104
4105 Plain `codewhale doctor` prints a short verdict: whether Codewhale is ready,
4106 what works, what needs attention and the next step. `codewhale doctor --full`
4107 prints every check (versions, installations, paths, sessions, setup state, API
4108 keys, MCP servers, skills, tools, plugins, storage, tool dependencies and
4109 platform); `--all` adds every resolved path and secret-backend detail. The
4110 `--check-updates`, `--probe-mcp`, `--probe-search` and `--fix` flags print the
4111 full report, because their results live in its sections. `--brief` asks for the
4112 short verdict explicitly, keeps it with `--fix` (the repair plan follows), and
4113 is rejected with `--full`, `--all`, `--check-updates`, `--probe-mcp` and
4114 `--probe-search`. With `--installs` it prints only what needs attention.
4115
4116 Plain `codewhale doctor`, `codewhale doctor --full` and
4117 `codewhale doctor --json` are structural and offline by default. They do not check the release service, hosted provider
4118 APIs, local provider endpoints, or MCP processes, and they do not load a
4119 workspace credential `.env`. Use `--check-updates`,
4120 `--probe-api`, `--probe-local`, or `--probe-mcp` to opt into the corresponding
4121 live boundary; `--probe-local` may start a desktop-managed service such as
4122 Ollama. Only the explicit API/local probe paths may load workspace credential
4123 `.env` values. Live flags conflict with `--json`, so machine-readable doctor
4124 output is always offline. Top-level keys include `version`, `paths`, `secret_backend`,
4125 `config_path`, `config_present`, `workspace`, `api_key.source`,
4126 `api_key.availability`, `base_url`,
4127 `default_text_model`, `mcp`, `skills`, `tools`, `plugins`, `sandbox`,
4128 `platform`, `api_connectivity`, and `capability`. CI consumers should rely on
4129 `api_key.source` (`config_declared`/`env_declared`/`external_auth_declared`/
4130 `secret_store_unprobed`/`secret_store_unavailable`/`oauth_unprobed`/
4131 `external_consent`/`none`/`local_runtime`/`unknown`) and
4132 `api_key.availability`
4133 (`present`/`not_required`/`not_probed`/`unavailable`/`unknown`) rather than parsing the
4134 human-readable `doctor` text. Source is declaration metadata, not proof that a
4135 credential exists or works. Only a non-empty, non-sentinel literal config value
4136 is structurally `present`; no-auth and local routes are `not_required`. Environment,
4137 external-auth, OAuth, consent, and secret-store declarations remain `not_probed`
4138 and cannot make structural Setup or Fleet readiness true. A secret-store sentinel
4139 on a named/custom endpoint that is prohibited from using the shared store is
4140 `secret_store_unavailable`/`unavailable`, while `unknown` remains reserved for
4141 the absence of a supported structural conclusion. Exact and whitespace-wrapped
4142 legacy sentinels are never treated as literal credentials. The structural
4143 loader still honors safe environment routing/model/policy fields, but it never
4144 materializes environment HTTP headers, sandbox API keys, or search API keys;
4145 only an explicit API/local probe switches to the normal credential-loading
4146 path. An opted-in update check also emits only typed generic failures: untrusted
4147 release metadata and transport errors are not echoed.
4148
4149 If configuration loading or validation fails, `doctor --json` returns nonzero
4150 and prints a bounded JSON error envelope with
4151 `status = "error"` and `error.kind = "config_validation"`. It does not emit a
4152 normal route or capability report—or the underlying possibly sensitive error—
4153 for an invalid configuration.
4154
4155 MCP entries are configuration diagnostics unless an explicit MCP command is
4156 run. `mcp.probe_scope` is `configuration`, `mcp.live_health_checked` is false,
4157 and each server separates `checks.configuration` / `checks.command` from
4158 `checks.process_reachable`, `checks.protocol_initialized`, and
4159 `checks.backend_tool_health`. The latter three remain `not_checked` in doctor
4160 output. Run `codewhale mcp validate` to explicitly start enabled servers and
4161 verify protocol initialization/discovery; backend health still requires an
4162 appropriate explicit tool call. Doctor reports only safe structural MCP fields:
4163 URL userinfo/path/query/fragment and raw command arguments, environment values,
4164 header values, and token material are omitted. Provider URLs follow the same
4165 rule and expose only `scheme://host[:explicit-port]`.
4166
4167 The `capability` key contains per-provider capability info derived from
4168 static knowledge (release docs, API guides) rather than live API probes.
4169 Top-level sub-keys: `resolved_provider`, `resolved_model`, `context_window`,
4170 `max_output`, `thinking_supported`, `cache_telemetry_supported`,
4171 and `request_payload_mode`.
4172
4173 Use `capability.context_window` and `capability.max_output` for model-limit
4174 checks in CI scripts; do not treat `capability.max_output` as the per-turn
4175 request budget. Use `capability.thinking_supported` to decide whether to
4176 configure reasoning effort.
4177
4178 ## Setup status, clean, and extension dirs
4179
4180 `codewhale setup` accepts a few flags beyond the existing `--mcp`,
4181 `--skills`, `--local`, `--all`, and `--force`:
4182
4183 - `--status` — print a compact one-screen status (api key, base URL, model,
4184 MCP/skills/tools/plugins counts, sandbox, `.env` presence). Read-only and
4185 network-free; safe to run in CI. If `.env` is missing and `.env.example` is
4186 present in the workspace, the status output points at `cp .env.example .env`.
4187 - `--tools` — scaffold `~/.codewhale/tools/` with a `README.md` describing the
4188 self-describing frontmatter convention (`# name:` / `# description:` /
4189 `# usage:`) and an `example.sh` that follows it. The directory is
4190 intentionally not auto-loaded; wire individual scripts into the agent via
4191 MCP, hooks, or skills.
4192 - `--plugins` — scaffold `~/.codewhale/plugins/` with a `README.md` and an
4193 `example/plugin.toml` plus a namespaced example Skill. Bundles are discovered
4194 read-only, untrusted, and disabled; review them through `/plugin` before
4195 enabling. Bundles activate declared Skills, MCP servers, commands, agent
4196 profiles, and hooks after review. See
4197 [PLUGIN_BUNDLES.md](PLUGIN_BUNDLES.md).
4198 - `--all` now scaffolds MCP + skills + tools + plugins together.
4199 - `--clean` — list `~/.codewhale/sessions/checkpoints/latest.json` and
4200 `offline_queue.json` if they exist. Legacy
4201 `~/.deepseek/sessions/checkpoints/` files are not scanned automatically; set
4202 `CODEWHALE_HOME=~/.deepseek` for a one-off legacy cleanup. Pass `--force` to
4203 actually remove matched files. This never touches real session history or the
4204 task queue.
4205
4206 `--status` and `--clean` are mutually exclusive with the scaffold flags.
4207
4208 ## Why the engine strips XML/`[TOOL_CALL]` text
4209
4210 codewhale sends and receives tool calls only over the API tool channel
4211 (structured `tool_use` / `tool_call` items). The streaming loop in
4212 `crates/engine/src/core/engine.rs` recognizes a fixed set of fake-wrapper start
4213 markers — `[TOOL_CALL]`, `<codewhale:tool_call`, `<tool_call`, `<invoke `,
4214 `<function_calls>` — and scrubs them from visible assistant text without ever
4215 turning them into structured tool calls. When a wrapper is stripped, the loop
4216 emits one compact `status` notice per turn so the user can see why their
4217 visible text shrank. Treat any change that re-enables text-based tool
4218 execution as a regression; the protocol-recovery tests in
4219 `crates/tui/tests/integration/protocol_recovery.rs` lock the contract.
4220
4221 ## Model-bound redaction (`[redaction] model_bound`)
4222
4223 Codewhale masks credential-looking values in tool output **before it is sent
4224 to an upstream model** — the "model boundary". A file read by a tool can
4225 contain a configured API key, a bare provider token, or a credential-shaped
4226 opaque string, and the model must not see those bytes. This backstop is
4227 separate from the display/export scrubbers: it decides what the model itself
4228 can quote back, and it is deliberately conservative (`CredentialShaped`
4229 policy, see `crates/config/src/persistence.rs`), so ordinary code and config
4230 stay byte-exact while keys, JWTs, bearer tokens, PEM blocks, and long opaque
4231 runs are masked.
4232
4233 Turning that masking **off** is a security decision, so it is not a plain
4234 boolean:
4235
4236 ```toml
4237 [redaction]
4238 model_bound = "disabled" # "enabled" (default) | "disabled"
4239 ```
4240
4241 Setting `"disabled"` only records a *request*. It takes effect only when all
4242 of these are true:
4243
4244 1. You restart the interactive TUI.
4245 2. The startup gate appears and you press `1`/`Y` on its first stage
4246 ("confirm and disable"). This only advances to a second, final-confirmation
4247 stage - the gate repeats the red warning and asks "are you really sure?".
4248 3. On that second stage you press `1`/`Y` again. The gate is rendered with the
4249 same explicit-key discipline as workspace trust - `Enter` never confirms by
4250 reflex, and `2`/`U` on the second stage steps back.
4251 4. Only that second confirmation persists a receipt to
4252 `~/.codewhale/redaction-state.json` (next to `config.toml`) and rebuilds
4253 the engine with masking off for the rest of this launch and future ones.
4254
4255 The receipt is bound to the config it was made against and is valid only
4256 while that config still requests `"disabled"`. Setting `model_bound` back
4257 to `"enabled"` - or rewriting `config.toml` in any way after the
4258 confirmation - invalidates it, so requesting `"disabled"` again later
4259 asks for a fresh confirmation on the next launch. The receipt checks both the
4260 config contents and modification time; missing, unreadable, or malformed config
4261 and older receipts without this binding keep masking enabled. Legacy-home
4262 installs store the receipt beside their resolved config file.
4263
4264 Until a confirmation exists, the effective mode is always `"enabled"`:
4265
4266 - Choosing `2`/`U` ("keep masking on") leaves the config field untouched, so
4267 the next launch asks again. Edit the field back to `"enabled"` to stop being
4268 asked.
4269 - Non-interactive entry points (`codewhale exec`, hooks, automations, headless
4270 agents) never confirm anything and never apply an unconfirmed request.
4271 - Routing/classification summaries and durable goal-state text keep their own
4272 always-on redaction regardless of this switch; the opt-out exists so the
4273 model can quote file bytes for exact edits, not to relax stored state.
4274
4275 The config value itself is forgiving: `true`/`false`, `"on"`/`"off"`, and
4276 `"enabled"`/`"disabled"` (any casing) all parse, with `false`/`"off"` meaning
4277 `"disabled"`.
4278
4279 A confirmed opt-out still sends your configured API keys to the provider you
4280 are already talking to. Only use it when the model must read and edit files
4281 that contain real credentials.
4282
4283 ### Stored sessions
4284
4285 The masking runs once, when tool output enters the transcript, so saved
4286 session files (`~/.codewhale/sessions/*.json` and their checkpoints) and
4287 Runtime API thread items (their text and tool metadata) do not store a
4288 credential-shaped value from tool output. With the confirmed opt-out above,
4289 tool output is stored as the model saw it.
4290
4291 Not yet masked: large outputs spilled to `~/.codewhale/tool_outputs`, shell
4292 completion evidence artifacts, and tool-call *inputs* (for example a
4293 `curl -H "Authorization: Bearer …"` command line). `doctor` and
4294 `scrub-secrets` do not check those either.
4295
4296 Sessions saved by builds before this change may still hold credentials in
4297 their tool output; nothing rewrites them automatically. `codewhale doctor --full`
4298 reports them under **Stored Sessions** (it checks the newest 50 files), and
4299 this command finds and masks them across every saved session:
4300
4301 ```sh
4302 codewhale sessions scrub-secrets # report only
4303 codewhale sessions scrub-secrets --apply # rewrite the affected files
4304 ```
4305
4306 `--apply` rewrites each file under the same per-session lock a save takes,
4307 so it never loses a concurrent save. A session that is still open can write
4308 its in-memory copy back on its next save, so close open sessions first, and
4309 rotate any credential that was exposed — masking a stored copy cannot un-leak it.
4310
4310 lines MARKDOWN