返回 CodeWhale
HOOKS.md
根目录 / docs / HOOKS.md
1 # Hooks
2 > 阅读简体中文版:[zh_hans/HOOKS.md](zh_hans/HOOKS.md)
3
4 Everything you add to Codewhale is a plugin. A hook in `config.toml` or a
5 project `hooks.toml` is a plugin of the kind **Hook**, and a plugin bundle can
6 also carry hooks. Hooks are managed under Plugins → Hooks in the
7 terminal and Customize › Hooks on the desktop. Configuration and
8 the `/hooks` commands are unchanged.
9
10 Hooks run a shell command when the Codewhale **TUI** reaches a lifecycle
11 point. They are plain processes: they receive context through environment
12 variables, some receive a JSON payload on stdin, and three of them can steer
13 what Codewhale does next.
14
15 This page is the authoritative reference for what is implemented today.
16 Configuration syntax that overlaps with the rest of `config.toml` lives in
17 [CONFIGURATION.md](CONFIGURATION.md); this file is the event-by-event
18 contract.
19
20 ## Scope
21
22 Hooks fire in the interactive TUI and in the engine turn loop, which the
23 Runtime API threads behind the desktop app and web drive as well.
24
25 | Surface | Fires hooks |
26 | --- | --- |
27 | `codewhale` / `codew` interactive TUI | yes |
28 | `codewhale exec` (headless one-shot) | opt-in: `--hooks` fires `tool_call_before` for the root agent's calls, and `shell_env` |
29 | Runtime API threads (desktop app, web) | yes: `tool_call_before` for the root agent's calls, `shell_env`, `tool_call_after`, `on_error`; `GET /v1/hooks` lists the set |
30 | the `codewhale` CLI dispatcher and its subcommands | no |
31 | app-server / ACP | no |
32 | the `workflow` tool and sub-agent *internals* | no — but the TUI fires `subagent_spawn` / `subagent_complete` around them |
33 | public API | there is none |
34
35 The `crates/hooks` event-sink crate in this repository is an unrelated
36 internal mechanism. It shares no configuration, no event names, and no
37 contract with the hooks described here.
38
39 ### `codewhale exec --hooks`
40
41 Headless runs fire no hooks by default (a CI job should not start paging an
42 on-call rotation merely because a config exists). `codewhale exec --hooks`
43 opts the run in. The engine-side events are `tool_call_before` (exit code 2
44 still denies the call; `ask` resolves fail-closed because nothing can prompt
45 headlessly) and `shell_env`. `tool_call_before` fires for the root agent's calls only and its
46 operator hooks do not run for sub-agent tool calls; whether plugin
47 hooks reach sub-agent calls is not determined. UI-driven events such as `session_start`,
48 `message_submit`, and `turn_end` do not fire because they live in the
49 interactive shell, not the turn loop. Fleet worker subprocesses never fire
50 operator hooks. Independently of this flag, `permissions.toml` typed rules
51 already apply to `exec` (and `deny` rules reach sub-agents too): the run drives
52 the same turn loop, and a `deny` blocks in every mode.
53
54 ## Quick start
55
56 ```toml
57 # ~/.codewhale/config.toml
58 [hooks]
59 enabled = true
60
61 [[hooks.hooks]]
62 name = "announce"
63 event = "session_start"
64 command = "echo 'Codewhale session started'"
65 ```
66
67 Run `/hooks` in the TUI to list what is configured, whether the global switch
68 is on, and any entry that was rejected at load. Run `/hooks events` for the
69 event names.
70
71 ## Configuration
72
73 ```toml
74 [hooks]
75 enabled = true # global switch; false suppresses every hook
76 default_timeout_secs = 30 # see the timeout note below
77 working_dir = "/path/to/dir" # default: the session workspace
78
79 [[hooks.hooks]]
80 event = "tool_call_before" # required; one of the 16 names below
81 command = "~/.codewhale/hooks/gate.sh" # required; `sh -c` on Unix, `cmd /C` on Windows
82 name = "gate" # optional label for /hooks and log lines
83 timeout_secs = 30 # optional, default 30
84 background = false # optional; foreground inside the hook worker
85 continue_on_error = true # optional, default true
86 condition = { type = "tool_name", name = "bash" } # optional
87 ```
88
89 `timeout_secs` note, stated as implemented: when `[hooks].default_timeout_secs`
90 is set it **overrides** every hook's own `timeout_secs`, it does not merely
91 supply a default for hooks that omit one. Leave it unset if you want per-hook
92 timeouts to apply. `/hooks list` shows the timeout the runtime will actually
93 apply, and names the override when one is in force.
94
95 `default_timeout_secs = 0` is **rejected at load**. Because the value replaces
96 every hook's own `timeout_secs`, a zero there would expire every hook in the
97 config immediately — including a `tool_call_before` gate, which then denies
98 every matching tool call. The override is ignored, per-hook `timeout_secs`
99 applies, the hooks themselves still load, and the rejection is reported by
100 `/hooks list` under *configuration problems*. Per-hook `timeout_secs = 0` is
101 rejected too, but that only drops the one hook that wrote it.
102
103 Hooks run with the workspace (or `working_dir`) as the current directory.
104
105 ### Timeouts
106
107 The timeout applies to **foreground and background hooks alike**. When it
108 expires:
109
110 - the hook's whole process group is killed — Unix process groups, Windows Job
111 Objects — so a hook that spawns children does not outlive its budget;
112 - the child is then reaped, so nothing is normally left detached or zombied;
113 - a foreground hook's result is `success = false`, `exit_code = None`, empty
114 `stdout`/`stderr`, and `error = "Hook timed out after Ns"`;
115 - a background hook's timeout is logged at `warn` under the `hooks` target.
116 Nothing is reported to the caller, because the caller stopped waiting the
117 moment it submitted the hook.
118
119 **Termination is best-effort, and the bound that is guaranteed is Codewhale's,
120 not the OS's.** The kill can fail to land — a process wedged in an
121 uninterruptible state on Unix, a `TerminateJobObject` a protected process
122 survives on Windows — and no user-space program can promise otherwise. What
123 Codewhale does guarantee is that it stops waiting: the containment handle is
124 released (which re-signals the Unix process group and closes the kill-on-close
125 Windows Job Object) and the reap gets one short bounded window. If the child
126 still cannot be confirmed dead, that is logged at `warn` and the foreground
127 result says so — `error = "hook could not be reaped after its timeout"` rather
128 than the stronger timeout wording. So a timed-out hook never blocks the turn,
129 but treat "killed" as best-effort rather than absolute.
130
131 ### Background hooks
132
133 `background = true` describes real scheduling, not just a config flag. A
134 background hook is **submitted, never awaited**:
135
136 - it is enqueued without blocking into a fixed 32-entry supervisor queue,
137 drained by two persistent workers that apply the timeout above; saturation
138 or supervisor loss is a failed submission, and no invocation creates its
139 own detached supervisor thread;
140 - it receives the same environment variables and the same stdin JSON payload
141 as the foreground form of that event — the payload contract does not change,
142 only the steering does;
143 - its stdout and stderr are discarded (`Stdio::null()`), so it can never
144 return a verdict;
145 - the `HookResult` the runtime hands its caller is flagged as a background
146 submission and carries no exit code. Steering code reads
147 `observed_exit_code()`, which is `None` for a background hook, so a
148 background hook can never allow, deny, ask, or rewrite anything.
149
150 `shell_env` ignores `background` entirely — its stdout *is* the contract, so
151 it always runs in the foreground. `/hooks list` reports that as a
152 configuration warning, and does not label the hook `[bg]`.
153
154 Observer-only UI events are submitted with non-blocking `try_send` to one
155 32-entry queue drained by two persistent workers. A configured foreground
156 observer is still awaited in config order inside a worker, but the terminal
157 event loop never waits on its process and never creates a thread per event.
158 Queue saturation or dispatcher loss drops that observer event and produces an
159 event-specific error toast that survives an agent's ordinary progress-status
160 update. Steering events retain their gate or transform semantics:
161 fresh/queued `message_submit` dispatch reports through a bounded result
162 channel, same-turn steering runs that transform on the blocking worker before
163 calling the engine steer path, and `tool_call_before` / `shell_env` execute on
164 the engine or tool worker rather than the terminal event loop.
165
166 ### The hook process environment
167
168 A hook command inherits the environment of the Codewhale process, plus the
169 `DEEPSEEK_*` variables for its event. Codewhale does not filter that
170 inheritance, so treat a hook exactly as you would treat any command you type
171 in the same shell that launched Codewhale: whatever is exported there is
172 visible to it.
173
174 This is *not* true of the command a `shell_env` hook feeds — see
175 [`shell_env`](#shell_env) for the bounded allowlist that governs a **local**
176 `exec_shell`, and for what changes when an external sandbox backend is
177 configured instead (the backend owns its base environment, and your
178 `shell_env` values are transmitted to it).
179
180 ### Conditions
181
182 | Condition | Matches | Supported on |
183 | --- | --- | --- |
184 | `{ type = "always" }` | every invocation (also the default when omitted) | every event |
185 | `{ type = "tool_name", name = "bash" }` | exact tool name; `*` globs are supported, e.g. `mcp__*`. The shell tool's spellings `bash`, `Bash`, and `exec_shell` are aliases: a condition naming any one matches all three | `tool_call_before`, `tool_call_after`, `shell_env`, `on_error` |
186 | `{ type = "tool_category", category = "shell" }` | tool category | `tool_call_before`, `tool_call_after`, `shell_env`, `on_error` |
187 | `{ type = "mode", mode = "plan" }` | the context's mode string, case-insensitive | every event **except** `shell_env` |
188 | `{ type = "exit_code", code = 1 }` | the exit code the tool actually reported | `tool_call_after`, `on_error` |
189 | `{ type = "all", conditions = [...] }` | every nested condition | every event |
190 | `{ type = "any", conditions = [...] }` | at least one nested condition | every event |
191
192 Three rules keep conditions from lying:
193
194 - **`exit_code` needs a real exit code.** It matches only when the event
195 actually observed a process exit code — `tool_call_after`, or `on_error` for
196 a tool failure, in both cases for a process-backed tool such as `bash`.
197 A command that exits nonzero reports its code too, even though `bash`
198 returns it as a failed call. A timed-out or killed command usually has no
199 exit code; `DEEPSEEK_TOOL_STATUS` says which it was.
200 A tool that reports no exit code never matches an `exit_code` condition; the
201 condition is not satisfied by a default, a zero, or a success flag. The value
202 is a 64-bit integer, so a Windows crash code such as `3221225477`
203 (`0xC0000005`) is matchable.
204 - **Tool-scoped `on_error` hooks are supported.** `on_error` fires for
205 transport and capacity errors *and* for tool failures; the tool-failure
206 firing carries the tool name, call id, result, and reported exit code. A
207 `tool_name` / `tool_category` / `exit_code` condition on `on_error` is
208 therefore a valid configuration. An `on_error` firing with no tool behind it
209 simply does not match such a condition — it is skipped at dispatch, not
210 rejected at load.
211 - **Unsupported conditions are rejected at load.** A condition that references
212 context its event never carries can never match, and a hook wearing one is
213 silently inert — the dangerous form of that is a `deny` gate the operator
214 believes is armed. Codewhale drops those hooks at load, logs the reason
215 under the `hooks` tracing target, and shows them in `/hooks list` as
216 `rejected:`. Nested predicates inside `all` / `any` are checked too. A hook
217 with `timeout_secs = 0` or an empty `command` is rejected the same way.
218 Rejection is **per entry**: a broken hook never takes another one with it,
219 even when the two share a `name` or are both unnamed.
220
221 ### Project-local hooks
222
223 A repository may ship `<workspace>/.codewhale/hooks.toml` using the same shape,
224 but only its `[[hooks]]` entries are merged — a project file cannot change
225 `enabled`, `default_timeout_secs`, or `working_dir`, which always come from your
226 own config. Because hooks are executable configuration, project hooks load
227 **only** after both workspace trust and separate approval of the exact hooks file
228 in user-owned config. Use `/hooks review` to inspect the commands and digest,
229 then `/hooks approve <digest>` to enable those bytes on the next session. Review
230 any scripts the commands call too. A file change requires another approval.
231 `/hooks revoke` blocks future and queued launches; it does not stop commands
232 already running. Session `/trust on` alone does not enable project hooks.
233 Approved project hooks are appended
234 after global hooks, so they run last and win `updatedInput` ties. A malformed
235 trusted project file logs a warning and Codewhale falls back to global hooks
236 only. Validation runs over the merged set, so a rejected project hook is
237 reported the same way a rejected global one is.
238
239 ## The 16 events
240
241 | Event | Fires | Steering |
242 | --- | --- | --- |
243 | `session_start` | once, after the engine is up and before the first draw | observer |
244 | `session_end` | once, on graceful shutdown | observer |
245 | `turn_end` | after a turn completes and post-turn state is updated | observer |
246 | `message_submit` | before a submitted message reaches history or the model | **can replace or block the text** |
247 | `tool_call_before` | before each root-agent tool call executes (operator hooks do not run for sub-agent tool calls) | **can allow / deny / ask, rewrite input, add context** |
248 | `tool_call_after` | after each tool result settles, including completions the transcript does not redraw | observer |
249 | `mode_change` | on every applied Plan/Work transition (`Act` is a compatibility alias for Work) | observer |
250 | `on_error` | on transport, capacity, and auth errors, and on tool failures | observer |
251 | `subagent_spawn` | when a sub-agent starts | observer |
252 | `subagent_complete` | when a sub-agent completes, fails, or is cancelled | observer |
253 | `shell_env` | immediately before each `exec_shell` invocation | **contributes environment variables** |
254 | `session_idle` | when the session settles back to idle after a turn or a wait — no prompt, approval, or continuation outstanding | observer |
255 | `session_error` | when a turn ends in a terminal failure; transient tool failures the agent absorbs never fire it | observer |
256 | `waiting_for_user` | when the agent starts waiting on you: an approval prompt opens, a `request_user_input` question is presented, or a goal continuation is parked between passes | observer |
257 | `session_busy` | when an idle or waiting session begins or resumes work; startup and repeated observations of the same state stay silent | observer |
258 | `pre_compact` | before context compaction summarizes and trims conversation history | observer |
259
260 `waiting_for_user`'s payload carries `reason`: `approval`, `user_input`, or
261 `goal_continuation`. All three state events carry `from`/`to` transition fields;
262 `session_idle` also carries `last_turn_status` when known, and `session_error` carries
263 the bounded terminal `error` text. Busy, idle, and waiting map onto the session
264 states the control socket's `status` verb already publishes
265 (`idle` / `in_progress` / `waiting`), so a hook and a supervisor never
266 disagree about what the session is doing. Hook authors that want opencode's
267 grace-period semantics for error alerts should debounce inside the hook —
268 `session_error` already excludes absorbed, transient failures, and a turn
269 that fails and is retried by the operator fires again only if the retry also
270 ends failed.
271
272 ### What "observer" means, exactly
273
274 Observer means Codewhale ignores the hook's **result**: stdout is discarded, a
275 non-zero exit is logged as a warning, and nothing about the turn, the tool
276 result, the sub-agent, or the error changes because of it.
277
278 Observer does **not** mean side-effect-free. An observer hook is an arbitrary
279 shell command running with your credentials. It can write files, push commits,
280 page an on-call rotation, or delete the workspace. The only thing it cannot do
281 is change what Codewhale itself does next.
282
283 The steering allowlist is exactly three events — `message_submit`,
284 `tool_call_before`, `shell_env` — and it is asserted by a test over every
285 variant, so a new event defaults to observer.
286
287 ### Session identity
288
289 Every event in one TUI session carries the same `DEEPSEEK_SESSION_ID`. The id
290 is minted once at launch, in the form `sess_xxxxxxxx`, and it survives a
291 workspace switch and a trust decision that adds project hooks — both reload
292 the hook set without starting a new session. Engine-fired `tool_call_before`
293 reports the same id as the UI-fired events, so tool records correlate with the
294 session records around them.
295
296 `session_end` fires after the queued startup-default writes have been drained
297 and while the app is still live, so it observes the settled end state rather
298 than a half-torn-down one.
299
300 ## Environment variables
301
302 Every hook receives the subset of these that applies to its event. The
303 `DEEPSEEK_` prefix is retained for compatibility with hooks written before the
304 rebrand.
305
306 | Variable | Set for | Notes |
307 | --- | --- | --- |
308 | `DEEPSEEK_SESSION_ID` | every event except `shell_env` | `sess_xxxxxxxx`, stable for the whole session |
309 | `DEEPSEEK_WORKSPACE` | every event except `shell_env` | absolute workspace path |
310 | `DEEPSEEK_MODEL` | every event except `shell_env` | active model id |
311 | `DEEPSEEK_MODE` | every event except `shell_env` | see the mode-spelling note below |
312 | `DEEPSEEK_TOTAL_TOKENS` | UI-fired events | session token total at fire time |
313 | `DEEPSEEK_MESSAGE` | `message_submit`, `subagent_*` | truncated at 5 000 bytes with a `...[truncated]` marker |
314 | `DEEPSEEK_ERROR` | `on_error` | error message, truncated at 5 000 bytes |
315 | `DEEPSEEK_PREVIOUS_MODE` | `mode_change` | mode label before the change |
316 | `DEEPSEEK_TOOL_NAME` | `tool_call_before`, `tool_call_after`, `shell_env`, `on_error` (tool failures) | |
317 | `DEEPSEEK_TOOL_CALL_ID` | `tool_call_before`, `tool_call_after`, `on_error` (tool failures) | engine call id; correlates before/after/error for one call |
318 | `DEEPSEEK_TOOL_ARGS` | `tool_call_before`, `shell_env` | tool input JSON preview, capped at 10 000 bytes |
319 | `DEEPSEEK_TOOL_RESULT` | `tool_call_after`, `on_error` (tool failures) | truncated at 10 000 bytes |
320 | `DEEPSEEK_TOOL_SUCCESS` | `tool_call_after`, `on_error` (tool failures) | `true` / `false` |
321 | `DEEPSEEK_TOOL_EXIT_CODE` | `tool_call_after` and `on_error` **when the tool reported one** | absent otherwise — never synthesized; set for a failing command as well as a passing one; 64-bit, so Windows crash codes such as `3221225477` survive |
322 | `DEEPSEEK_TOOL_STATUS` | `tool_call_after` and `on_error` **when a shell tool reported one** | `completed`, `failed`, `timed_out`, `killed`, or `running` (moved to the background); absent for other tools |
323 | `DEEPSEEK_TOOL_EXECUTION_RECEIPT` | `tool_call_after` and `on_error` **for a settled, local, foreground shell run** | complete JSON, at most 32 KiB, or absent; see [Execution receipt](#execution-receipt) |
324 | `DEEPSEEK_SESSION_COST` | when cost is supplied | USD, six decimal places |
325
326 ### Execution receipt
327
328 `DEEPSEEK_TOOL_EXECUTION_RECEIPT` says what a shell tool (`bash`, `Bash`,
329 `exec_shell`) actually ran. The before-hook input is not the same thing: a
330 `tool_call_before` hook can rewrite it. The receipt is built from what the
331 process manager recorded when it spawned the process, after admission and
332 any rewrite.
333
334 ```json
335 {"schema_version":1,"command":"printf hello","cwd":"/absolute/workspace","state":"completed","scope":"local","exit_code":0,"stdout":"hello","stderr":"","stdout_truncated":false,"stderr_truncated":false,"output_kind":"separate"}
336 ```
337
338 | Field | Meaning |
339 | --- | --- |
340 | `command` | the admitted shell source handed to the shell, not the shell executable or its argv wrapper |
341 | `cwd` | the canonical absolute path of the directory the process started in: symlinks are resolved, so a directory has one spelling whether or not the call passed `cwd`; it is resolved before spawn and that same path is handed to the OS |
342 | `state` | `completed` for an observed exit, including a nonzero one; `interrupted` for a signal, kill, cancel, or timeout |
343 | `scope` | always `local` in schema 1 |
344 | `exit_code` | the observed integer, or `null`; never synthesized from `state` |
345 | `stdout`, `stderr` | previews of the tool's retained output, which may already omit early process output; long previews keep their first and last bytes around a `[receipt preview truncated]` marker |
346 | `stdout_truncated`, `stderr_truncated` | `true` when the tool's own output capture or the preview dropped bytes |
347 | `output_kind` | `separate` for `Bash` / `exec_shell`; `combined` for lowercase `bash`, whose stdout and stderr share one pipe — `stdout` then holds the combined preview and `stderr` is empty |
348
349 The rules are conservative:
350
351 - **Exact or absent.** `command` and `cwd` are never truncated. If either is
352 over 8 KiB, contains NUL, or the directory is relative, not UTF-8, or cannot
353 resolve before spawn, the receipt is left out. So is a run whose end the shell
354 tool could not observe (the OS wait itself failed): its state is unknown,
355 and the receipt does not guess it. Previews shrink until the serialized JSON fits 32 KiB;
356 if it still cannot fit, the receipt is left out rather than cut.
357 - **Absence means nothing.** It implies neither success nor failure. An inherited
358 `DEEPSEEK_TOOL_EXECUTION_RECEIPT` is cleared before applying the current call's context.
359 - **Scope.** A receipt is built only while a `tool_call_after` or `on_error`
360 hook is configured, and only for a settled, pipe-backed, unsandboxed, local
361 foreground run. Background launches, a foreground run moved to `/jobs`,
362 PTY (`tty` / `combined_output`) and interactive sessions, OS-sandboxed and
363 external-backend execution, the read-only shell's hardened argv, Windows,
364 a PowerShell shell on any platform (it wraps the source or runs it from a
365 temporary script), and calls refused before execution have none.
366 - **Hooks only.** The receipt is not kept in the durable Runtime API item
367 record; that record already carries the tool output.
368 - It is set for a failed run as well as a passing one, so `on_error` for a
369 failed shell call carries it too. Every other variable is unchanged.
370
371 For `tool_call_after`, the same execution evidence is also delivered as a
372 versioned JSON document on stdin, in foreground and background form:
373
374 ```json
375 {"schema_version":1,"event":"tool_call_after","tool_name":"bash","session_id":"session-id","tool_call_id":"call-id","session_id_truncated":false,"tool_call_id_truncated":false,"tool_name_truncated":false,"execution_receipt":{"schema_version":1,"command":"printf hello","cwd":"/absolute/workspace","command_truncated":false,"cwd_truncated":false,"execution":"started","completion":"completed","exit_code":0,"stdout":"hello","stderr":"","stdout_truncated":false,"stderr_truncated":false,"output_mode":"combined"}}
376 ```
377
378 The stdin projection leaves the environment receipt above unchanged.
379 `completion` is the observed `completed`, `failed`, `killed`, or `timed_out`
380 status; a nonzero exit is `failed`. `exit_code` remains a signed 64-bit integer
381 or `null`. `output_mode` carries the existing receipt's `output_kind`:
382 `separate` or `combined`. With combined output, empty `stderr` does not mean
383 the command wrote nothing to stderr.
384
385 The complete document is capped at 64 KiB. Correlation identifiers are capped
386 at 1,024 UTF-8 bytes plus a truncation marker and carry individual flags;
387 missing identifiers are `null`. The shell name is exact. Execution `command`
388 and `cwd` retain the exact-or-absent rule above, so their truncation flags are
389 always false. Output truncation flags include both capture and preview loss.
390
391 Only a native shell call with a valid, settled receipt gets this stdin
392 document. Unsupported or unobserved paths get no document, and absence still
393 means unknown. Hooks remain observers: their stdout cannot allow, deny, or
394 rewrite the completed call, and background hooks are not awaited. `on_error`
395 continues to receive the environment receipt only.
396
397 **Mode-spelling note.** UI-fired events (`session_start`, `session_end`,
398 `message_submit`, `tool_call_after`, `mode_change`, `on_error`, `turn_end`,
399 `subagent_*`, `session_busy`, `session_idle`, `session_error`, `waiting_for_user`,
400 `pre_compact`)
401 set `DEEPSEEK_MODE` to the hook label: `ACT` in Work mode, `PLAN` in Plan mode.
402 `tool_call_before` fires inside the engine and uses the engine's own mode
403 spelling (`Agent` in Work mode, `Plan`). `mode` conditions compare
404 case-insensitively, so `{ type = "mode", mode = "plan" }` matches both, but a
405 hook that string-matches `$DEEPSEEK_MODE` exactly should accept both spellings.
406 `ACT` and `Agent` are the names Work mode had before it was renamed; they stay
407 so existing hooks keep matching. The retired Operate mode is no longer sent as
408 `OPERATE` or `Operate`; a session that would have used it reports Work mode.
409
410 **`shell_env` is the narrow one.** It receives only `DEEPSEEK_TOOL_NAME` and
411 `DEEPSEEK_TOOL_ARGS` — no session id, workspace, model, or mode. A
412 `{ type = "mode", … }` condition on a `shell_env` hook is therefore rejected at
413 load; scope those with `tool_name` or `tool_category` instead.
414
415 ## Steering events
416
417 ### `message_submit`
418
419 Receives JSON on stdin and may rewrite or block the submitted text.
420
421 ```json
422 {
423 "event": "message_submit",
424 "text": "original user text",
425 "text_bytes": 18,
426 "text_original_bytes": 18,
427 "text_truncated": false,
428 "session_id": "sess_12345678",
429 "workspace": "/path/to/workspace",
430 "mode": "ACT",
431 "model": "deepseek-chat",
432 "total_tokens": 1234
433 }
434 ```
435
436 The complete serialized stdin document is capped at 32 KiB. `text` is the
437 largest deterministic UTF-8 prefix that fits after JSON escaping and bounded
438 metadata are included. `text_original_bytes` records the producer's full byte
439 length, `text_bytes` records the retained prefix, and `text_truncated` states
440 whether they differ. This same boundary applies to immediate input, restored
441 queue entries, merged steers, and text produced by an earlier hook.
442
443 - exit `0` printing `{"text": "..."}` with a non-empty string replaces the text
444 - exit `0` with empty stdout, or JSON without `text`, leaves the text unchanged
445 - `{"text": ""}` or a replacement over 32 000 characters is invalid stdout,
446 logged and ignored
447 - exit `2` blocks the submission before history or dispatch; a structured
448 `reason` field supplies a bounded, redacted message shown in the TUI.
449 Unstructured stdout/stderr/error output is never copied into the denial
450 - other non-zero exits follow `continue_on_error`: `true` warns and continues,
451 `false` blocks the submission
452 - `background = true` makes the hook observer-only — it still receives this
453 bounded payload on stdin, but it cannot transform or block
454
455 Multiple `message_submit` hooks run in config order and each sees the previous
456 hook's output.
457
458 ### `tool_call_before`
459
460 Gates the root agent's tool calls only; operator hooks configured here do not
461 run for sub-agent tool calls, and plugin hooks for sub-agents are not
462 determined (use `permissions.toml` `deny` rules to block tools across sub-agents).
463 Receives the tool context in environment variables and may print a JSON
464 decision on stdout with exit `0`:
465
466 ```json
467 {
468 "decision": "allow",
469 "reason": "human-readable explanation, used for deny",
470 "updatedInput": { "command": "ls -la" },
471 "additionalContext": "text appended to the tool result for the model"
472 }
473 ```
474
475 - `deny` blocks the tool; the model gets a permission-denied result carrying
476 `reason`
477 - `ask` forces the interactive approval prompt in Ask and Auto-Review. Full
478 Access does not open tool-approval prompts, so `ask` does not downgrade it
479 - `updatedInput` must be an object no larger than 32 KiB serialized and
480 replaces the tool input; last hook wins
481 - `additionalContext` is appended to the tool result as `[hook context] ...`;
482 multiple hooks concatenate
483 - `reason` and `additionalContext` are bounded and sanitized before use: each
484 field is capped at 2 000 characters, the concatenated context for one tool
485 call is capped at 8 000, control characters are stripped (so hook stdout
486 cannot repaint the TUI or forge structure in the transcript), and a clipped
487 value carries a `…[truncated]` marker. What a hook adds to the turn's context
488 budget is therefore bounded no matter what it prints
489 - exit `2` is a legacy hard deny and wins regardless of stdout
490 - empty stdout, non-JSON stdout, and JSON without `decision` all mean allow
491 - precedence across matching hooks: no-verdict-with-`continue_on_error = false`
492 > deny > ask > allow
493 - `background = true` hooks are submitted and never awaited, so they have no
494 verdict and cannot steer; Codewhale logs a warning when one is configured
495 for this event
496
497 **A gate that could not answer is not permission.** If a foreground
498 `tool_call_before` hook produces no verdict — it timed out, the process could
499 not be started, or a strict process exited non-zero without an explicit JSON
500 decision — and *that hook* is configured with
501 `continue_on_error = false`, the tool call is denied. Strictness is read off
502 the hook that actually ran, not off the event: a strict `write_file` gate whose
503 condition did not match an `exec_shell` call has no say in whether that call
504 proceeds, and a lenient hook's timeout never denies just because some other
505 strict hook exists in config. Every no-verdict outcome is logged either way.
506
507 The denial message names the hook and the reason and nothing else: the hook
508 name is truncated, the detail is truncated, control characters are stripped,
509 and a spawn failure is reported by error kind (`NotFound`,
510 `PermissionDenied`, …) rather than by echoing the command line or the resolved
511 interpreter path.
512
513 ### `shell_env`
514
515 Runs synchronously before each `exec_shell` and its stdout is parsed as
516 `KEY=VALUE` lines. A leading `export ` is stripped, `#` comment lines and blank
517 lines are skipped, and a matching pair of surrounding single or double quotes is
518 removed from the value. Later hooks override earlier ones. Use it for ephemeral
519 credentials, per-skill `PATH` adjustments, or short-lived tokens.
520
521 `background` is ignored for this event: the hook always runs in the foreground
522 because its stdout is the contract.
523
524 An entry a shell cannot carry is dropped rather than allowed to break the tool
525 call: an empty name, a name containing whitespace, `=`, a control character, or
526 a NUL; a value containing a NUL; a value over 32 KiB; and anything past 256 KiB
527 of accumulated output from one hook. Each drop is logged by key name only. A
528 `shell_env` hook is an ordinary process whose stdout can contain anything —
529 "the hook printed something odd" must never become "the `exec_shell` call
530 aborted".
531
532 **Exactly what the shell command ends up with — local execution.** When
533 `exec_shell` runs the command locally (the default), it does not inherit
534 Codewhale's ambient environment. Its environment is built as:
535
536 1. a sanitized fixed allowlist of parent variables — `PATH`, `HOME`, `USER`,
537 `LANG` and the other `LC_*`/locale entries, `TERM`, `SHELL`, `TMPDIR`,
538 proxy variables, color/terminal entries such as `NO_COLOR`, `CARGO_HOME`/`RUSTUP_HOME`/`RUSTUP_TOOLCHAIN`, the Windows system and MSVC toolchain entries, and other platform keys (the full list lives in `crates/runtime/src/child_env.rs`) — and nothing else. Variables
539 outside that allowlist, including anything that looks like a secret, are
540 dropped;
541 2. then the `KEY=VALUE` pairs your `shell_env` hooks produced, applied on top.
542 These are explicit values you configured, so they win over the allowlist.
543
544 So a `shell_env` hook is the supported way to get a credential into one local
545 `exec_shell` invocation. Ambient secrets exported in the terminal that launched
546 Codewhale are **not** forwarded to a local `exec_shell` on their own.
547
548 **With an external sandbox backend configured, the allowlist above is not the
549 contract.** If `exec_shell` is routed to a configured sandbox/execution
550 backend, Codewhale does not construct the process environment at all: it hands
551 the command and your `shell_env` values to the backend as extra environment
552 variables, and the **backend owns its own base environment**. What is present
553 besides your values — an image's baked-in variables, the backend's own
554 injections, whatever a remote runner exports — is determined by that backend,
555 not by the list above. Do not assume the local allowlist applies there.
556
557 Disclosure, because it is the part that matters for a hook that emits
558 credentials: **`shell_env` values are transmitted to the configured backend.**
559 For a remote or containerized backend that means the values leave this machine
560 and are subject to that backend's logging, retention, and access controls.
561 Codewhale's own audit log still records key names only, but that says nothing
562 about what the backend does with the values. If a `shell_env` hook emits a
563 secret, scope it to a backend you trust with that secret — for example by
564 conditioning the hook, or by not configuring an external backend for sessions
565 where those hooks are active.
566
567 Resolved **key names — never values** — are written to `~/.codewhale/audit.log`
568 so a session can be reconciled afterwards. A hook that fails or times out
569 contributes no variables and does not abort the shell call.
570
571 ```toml
572 [[hooks.hooks]]
573 name = "aws-creds"
574 event = "shell_env"
575 command = "aws-vault export my-profile --format=env"
576 condition = { type = "tool_category", category = "shell" }
577 ```
578
579 ## Structured observer payloads
580
581 `turn_end`, `subagent_spawn`, `subagent_complete`, `session_busy`, `session_idle`,
582 `session_error`, `waiting_for_user`, and `pre_compact` receive JSON on stdin in addition to the
583 environment variables. Their stdout is ignored. Background forms of these
584 events receive the same payload on stdin.
585
586 `tool_call_after` also receives JSON on stdin for a settled native shell call
587 with a tracked [execution receipt](#execution-receipt), in foreground and
588 background form. Other tool calls have no stdin document.
589
590 The remaining observer events — `session_start`, `session_end`,
591 `mode_change`, `on_error` — receive environment variables only, with no stdin
592 payload, in both foreground and background form.
593
594 ### Session state transitions
595
596 The first observed state is recorded silently, whether idle, busy, or waiting.
597 Repeating the same state emits nothing. For a turn that pauses for user input
598 and then completes, the transition hooks receive these payloads in submission
599 order:
600
601 | Event | JSON stdin |
602 | --- | --- |
603 | `session_busy` | `{"from":"idle","to":"in_progress"}` |
604 | `waiting_for_user` | `{"from":"in_progress","to":"waiting","reason":"user_input"}` |
605 | `session_busy` | `{"from":"waiting","to":"in_progress"}` |
606 | `session_idle` | `{"from":"in_progress","to":"idle","last_turn_status":"completed"}` |
607
608 The dispatcher has two workers, so command completion order is not guaranteed.
609 `session_error` is a separate terminal-failure event, with `status` and `error`
610 fields rather than `from` and `to`.
611
612 ### `turn_end`
613
614 Fires after post-turn state, usage totals, cost accounting, notifications,
615 receipts, and queue recovery have been updated, and before queued follow-up
616 dispatch — so the payload can report the queued count without a hook being able
617 to change what is sent next.
618
619 ```json
620 {
621 "event": "turn_end",
622 "session_id": "sess_12345678",
623 "workspace": "/path/to/workspace",
624 "mode": "ACT",
625 "created_at": "2026-07-12T10:30:00+00:00",
626 "model_backed": true,
627 "provider": "deepseek",
628 "billing_surface": null,
629 "model": "deepseek-chat",
630 "turn_id": "turn_12345678",
631 "status": "completed",
632 "error": null,
633 "duration_ms": 1834,
634 "usage": {
635 "input_tokens": 1200,
636 "output_tokens": 180,
637 "prompt_cache_hit_tokens": 900,
638 "prompt_cache_miss_tokens": 300,
639 "prompt_cache_write_tokens": 0,
640 "reasoning_tokens": null,
641 "reasoning_replay_tokens": null
642 },
643 "totals": {
644 "session_tokens": 1380,
645 "conversation_tokens": 1380,
646 "input_tokens": 1200,
647 "output_tokens": 180
648 },
649 "tool_count": 2,
650 "queued_message_count": 1,
651 "stop_hook_active": false
652 }
653 ```
654
655 `created_at` anchors time-window pricing. `provider` and `model` identify the
656 effective route for model-backed turns. `billing_surface` is an optional,
657 non-secret classification of the endpoint that served the turn (recognized
658 StepFun routes emit `stepfun-payg` or `stepfun-plan`); the raw base URL is never
659 written to hook records. Shell-only, manual-compaction, and purge completions
660 have no matching `TurnStarted`, so they report `model_backed: false`, a `null`
661 provider, and a synthetic `lifecycle_<uuid>` turn id. `stop_hook_active` is
662 always `false` today; it reserves room for re-entry protection.
663
664 ### `subagent_spawn` / `subagent_complete`
665
666 ```json
667 {
668 "event": "subagent_complete",
669 "agent_id": "agent_1",
670 "session_id": "sess_12345678",
671 "workspace": "/path/to/workspace",
672 "mode": "ACT",
673 "model": "deepseek-chat",
674 "total_tokens": 1234,
675 "result_preview": "bounded preview of the result",
676 "result_truncated": false,
677 "status": "completed"
678 }
679 ```
680
681 `subagent_spawn` carries `prompt_preview` / `prompt_truncated` instead, and no
682 `status`. Both payloads are bounded on purpose: previews are truncated rather
683 than shipping full prompts or results. These hooks are observer-only — failures
684 do not affect sub-agent scheduling, prompts, or results, and `continue_on_error`
685 has no effect because later matching hooks always run.
686
687 ### `pre_compact`
688
689 Fires before context compaction summarizes and trims conversation history.
690 Observer-only: stdout is ignored and failures do not block compaction.
691
692 ```json
693 {
694 "event": "pre_compact",
695 "trigger": "auto",
696 "message_count": 42,
697 "token_count": 4096,
698 "session_id": "sess_12345678",
699 "workspace": "/path/to/workspace",
700 "mode": "ACT",
701 "model": "deepseek-chat",
702 "total_tokens": 4096
703 }
704 ```
705
706 ## Failure behavior
707
708 - A non-zero exit is logged at `warn` under the `hooks` tracing target with the
709 hook name, event, exit code, duration, and a generic failure category. Raw
710 stdout/stderr/error text is not persisted in the log receipt.
711 - For `execute`-path events, `continue_on_error = false` stops later hooks for
712 that event; except on `tool_call_before` (above) it does not roll back the
713 action that fired them.
714 - Structured observer events (`turn_end`, `subagent_*`, `session_busy`,
715 `session_idle`, `session_error`, `waiting_for_user`, `pre_compact`) always continue to the
716 next matching hook.
717 - Observer events use a bounded persistent dispatcher. Queue-full and
718 dispatcher-unavailable submissions are not retried silently; the TUI keeps
719 an event-specific error toast separate from the ordinary status line.
720 - A hook that exceeds its timeout has its whole process group killed and is
721 then reaped, foreground or background — best-effort, with a bounded reap
722 wait; see [Timeouts](#timeouts).
723
724 ## Security notes
725
726 - Hooks are arbitrary shell commands from your own config; treat
727 `~/.codewhale/config.toml` as executable.
728 - Project-supplied hooks require exact-file approval in addition to workspace trust in
729 user-owned config.
730 - Hook commands inherit Codewhale's own environment. A local `exec_shell` does
731 not — see [`shell_env`](#shell_env).
732 - `shell_env` audit records contain key names only. That covers Codewhale's own
733 logging; with an external sandbox backend configured, the values themselves
734 are transmitted to that backend and are then subject to its handling.
735 - With an external sandbox backend, the local parent-variable allowlist does
736 not apply — the backend owns its base environment.
737 - Payload previews, tool arguments/results, error messages, captured stdout and
738 stderr, replacement messages, and steering objects are bounded so hook input
739 or output cannot become an unbounded copy of the transcript.
740 - Nothing Codewhale persists in a denial echoes the stdin payload, hook
741 environment, raw stdout/stderr/error, command line, or a resolved filesystem
742 path. `/hooks list` shows a sanitized, single-line command preview capped at
743 60 characters; it is not a verbatim copy. Structured denial reasons are
744 bounded and redact path-, argument-, command-, and secret-like tokens,
745 including quoted or `key=value` forms and `Authorization: Bearer …`.
746
746 lines MARKDOWN