返回 CodeWhale
hooks.rs
根目录 / crates / config / src / hooks.rs
1 use serde::{Deserialize, Serialize};
2 use std::path::PathBuf;
3
4 /// Events that can trigger hook execution
5 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
6 #[serde(rename_all = "snake_case")]
7 pub enum HookEvent {
8 /// Triggered when a new session starts
9 SessionStart,
10 /// Triggered when a session ends (quit, Ctrl+C)
11 SessionEnd,
12 /// Triggered before a user message is sent to the LLM
13 MessageSubmit,
14 /// Triggered before a tool is executed
15 ToolCallBefore,
16 /// Triggered after a tool completes (success or failure)
17 ToolCallAfter,
18 /// Triggered when the user changes modes (Plan, Act, Operate)
19 ModeChange,
20 /// Triggered when an error occurs
21 OnError,
22 /// Triggered after a turn completes and post-turn state has been updated
23 TurnEnd,
24 /// Triggered when a sub-agent is spawned
25 SubagentSpawn,
26 /// Triggered when a sub-agent reaches a terminal state
27 SubagentComplete,
28 /// Triggered immediately before each `exec_shell` invocation. The hook's
29 /// stdout is parsed as `KEY=VALUE\n` lines and merged on top of the
30 /// shell command's environment — useful for ephemeral credentials,
31 /// per-skill PATH adjustments, or short-lived tokens (#456). Hooks that
32 /// fail or time out are logged but do *not* abort the shell call; they
33 /// simply contribute no env vars.
34 ShellEnv,
35 /// Triggered when the session becomes idle after real work: a turn
36 /// finished (or a wait ended) and no prompt, approval, or continuation
37 /// is outstanding (#6004). Transient tool errors never fire this by
38 /// themselves; it marks "agent done, waiting for the next instruction".
39 SessionIdle,
40 /// Triggered when a turn ends in a terminal failure (#6004). Transient
41 /// tool failures that the agent absorbs never fire this; only a turn
42 /// whose final status is failed does. Hook authors that want opencode's
43 /// grace-period semantics should debounce inside the hook.
44 SessionError,
45 /// Triggered when the agent starts waiting on the person: an approval
46 /// prompt opens, a `request_user_input` question is presented, or a goal
47 /// continuation is parked between passes (#6004). The payload's `reason`
48 /// field is `approval`, `user_input`, or `goal_continuation`.
49 WaitingForUser,
50 /// Triggered when idle or waiting transitions to active work (#6004).
51 /// Startup and repeated observations of the same state stay silent.
52 SessionBusy,
53 PreCompact,
54 }
55
56 /// Every event name the runtime actually fires, in the order `/hooks events`
57 /// and `codewhale docs-manifest` list them. Tests assert this is exhaustive so
58 /// a new variant cannot ship without a documented firing point.
59 pub const ALL_HOOK_EVENTS: [HookEvent; 16] = [
60 HookEvent::SessionStart,
61 HookEvent::SessionEnd,
62 HookEvent::TurnEnd,
63 HookEvent::MessageSubmit,
64 HookEvent::ToolCallBefore,
65 HookEvent::ToolCallAfter,
66 HookEvent::ModeChange,
67 HookEvent::OnError,
68 HookEvent::SubagentSpawn,
69 HookEvent::SubagentComplete,
70 HookEvent::ShellEnv,
71 HookEvent::SessionIdle,
72 HookEvent::SessionError,
73 HookEvent::WaitingForUser,
74 HookEvent::SessionBusy,
75 HookEvent::PreCompact,
76 ];
77
78 /// How much a hook's result can change what Codewhale does next.
79 ///
80 /// This is the steering allowlist. "Observer" is a statement about
81 /// Codewhale's control flow only — an observer hook is still an arbitrary
82 /// shell command and can have any external side effect it likes.
83 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
84 pub enum HookSteering {
85 /// stdout/exit code can replace or block the submitted text.
86 TransformsSubmittedText,
87 /// stdout/exit code can allow, deny, ask, rewrite input, or add context.
88 DecidesToolCall,
89 /// stdout contributes `KEY=VALUE` pairs to one `exec_shell` invocation.
90 ContributesShellEnv,
91 /// stdout is ignored and the result cannot change Codewhale's behavior.
92 Observer,
93 }
94
95 impl HookEvent {
96 /// Get string representation for environment variable
97 #[must_use]
98 pub fn as_str(self) -> &'static str {
99 match self {
100 HookEvent::SessionStart => "session_start",
101 HookEvent::SessionEnd => "session_end",
102 HookEvent::MessageSubmit => "message_submit",
103 HookEvent::ToolCallBefore => "tool_call_before",
104 HookEvent::ToolCallAfter => "tool_call_after",
105 HookEvent::ModeChange => "mode_change",
106 HookEvent::OnError => "on_error",
107 HookEvent::TurnEnd => "turn_end",
108 HookEvent::SubagentSpawn => "subagent_spawn",
109 HookEvent::SubagentComplete => "subagent_complete",
110 HookEvent::ShellEnv => "shell_env",
111 HookEvent::SessionIdle => "session_idle",
112 HookEvent::SessionError => "session_error",
113 HookEvent::WaitingForUser => "waiting_for_user",
114 HookEvent::SessionBusy => "session_busy",
115 HookEvent::PreCompact => "pre_compact",
116 }
117 }
118
119 /// The steering contract for this event, as implemented.
120 #[must_use]
121 pub fn steering(self) -> HookSteering {
122 match self {
123 HookEvent::MessageSubmit => HookSteering::TransformsSubmittedText,
124 HookEvent::ToolCallBefore => HookSteering::DecidesToolCall,
125 HookEvent::ShellEnv => HookSteering::ContributesShellEnv,
126 HookEvent::SessionStart
127 | HookEvent::SessionEnd
128 | HookEvent::ToolCallAfter
129 | HookEvent::ModeChange
130 | HookEvent::OnError
131 | HookEvent::TurnEnd
132 | HookEvent::SubagentSpawn
133 | HookEvent::SubagentComplete
134 | HookEvent::SessionIdle
135 | HookEvent::SessionError
136 | HookEvent::SessionBusy
137 | HookEvent::WaitingForUser
138 | HookEvent::PreCompact => HookSteering::Observer,
139 }
140 }
141
142 /// Whether a hook result for this event can change Codewhale's own
143 /// behavior. Never read this as "side-effect free" — see [`HookSteering`].
144 #[must_use]
145 pub fn can_steer(self) -> bool {
146 !matches!(self.steering(), HookSteering::Observer)
147 }
148
149 /// Whether this event's context carries a tool name/arguments, so
150 /// `tool_name` / `tool_category` conditions can ever match.
151 ///
152 /// `on_error` is included because the tool-failure path in
153 /// `tui/tool_routing.rs` fires it with the tool name, call id, and result
154 /// attached. An `on_error` firing that has no tool behind it (a transport
155 /// or capacity error) simply does not match a tool predicate — it is
156 /// skipped at dispatch, not rejected at load.
157 #[must_use]
158 pub fn provides_tool_identity(self) -> bool {
159 matches!(
160 self,
161 HookEvent::ToolCallBefore
162 | HookEvent::ToolCallAfter
163 | HookEvent::ShellEnv
164 | HookEvent::OnError
165 )
166 }
167
168 /// Whether this event's context can carry a real process exit code, so
169 /// `exit_code` conditions can ever match. `tool_call_after` observes every
170 /// completed tool and `on_error` observes the failing ones; in both cases
171 /// the code is only present when the tool actually reported one
172 /// (`exec_shell` and friends).
173 #[must_use]
174 pub fn provides_exit_code(self) -> bool {
175 matches!(self, HookEvent::ToolCallAfter | HookEvent::OnError)
176 }
177
178 /// Whether this event's context carries a mode label, so `mode`
179 /// conditions can ever match. `shell_env` fires inside the `exec_shell`
180 /// tool with a deliberately narrow context and has no mode.
181 #[must_use]
182 pub fn provides_mode(self) -> bool {
183 !matches!(self, HookEvent::ShellEnv)
184 }
185
186 /// Whether `background = true` is honored as actual scheduling for this
187 /// event. Events whose result is part of the contract are always run in
188 /// the foreground, so declaring them background is a config error rather
189 /// than a scheduling choice.
190 #[must_use]
191 pub fn honors_background(self) -> bool {
192 !matches!(self, HookEvent::ShellEnv)
193 }
194 }
195
196 /// Condition for when a hook should run
197 #[derive(Debug, Clone, Serialize, Deserialize)]
198 #[serde(tag = "type", rename_all = "snake_case")]
199 #[derive(Default)]
200 pub enum HookCondition {
201 /// Always run this hook
202 #[default]
203 Always,
204 /// Only run for specific tool names
205 ToolName {
206 /// Tool name to match (e.g., "`exec_shell`", "`write_file`")
207 name: String,
208 },
209 /// Only run for specific tool categories
210 ToolCategory {
211 /// Category: "safe", "`file_write`", "shell"
212 category: String,
213 },
214 /// Only run in specific modes
215 Mode {
216 /// Mode: "plan", "agent", "yolo"
217 mode: String,
218 },
219 /// Only run when exit code matches (for `ToolCallAfter` / `OnError`)
220 ExitCode {
221 /// Exit code to match.
222 ///
223 /// `i64`, not `i32`: a Windows crash code such as `3221225477`
224 /// (`0xC0000005`, access violation) is a real code a shell tool
225 /// reports, and narrowing it would silently turn the predicate into
226 /// one that can never match.
227 code: i64,
228 },
229 /// Combine multiple conditions with AND
230 All { conditions: Vec<HookCondition> },
231 /// Combine multiple conditions with OR
232 Any { conditions: Vec<HookCondition> },
233 }
234
235 #[derive(Debug, Clone)]
236 pub struct NativeShellHook {
237 pub owner: crate::OwnerRef,
238 pub scope: Option<crate::EntryRef>,
239 pub handle: u64,
240 pub dialect: String,
241 pub point: String,
242 pub matcher: Option<String>,
243 }
244
245 /// A single hook definition
246 #[derive(Debug, Clone, Serialize, Deserialize)]
247 pub struct Hook {
248 #[serde(skip)]
249 pub native_shell: Option<NativeShellHook>,
250 /// The event that triggers this hook
251 pub event: HookEvent,
252
253 /// Shell command to execute (platform shell: `sh -c` on Unix, `cmd /C` on Windows)
254 pub command: String,
255
256 /// Optional condition for when this hook should run
257 #[serde(default)]
258 pub condition: Option<HookCondition>,
259
260 /// Timeout in seconds (default: 30)
261 #[serde(default = "default_timeout")]
262 pub timeout_secs: u64,
263
264 /// Run in background (don't wait for completion)
265 #[serde(default)]
266 pub background: bool,
267
268 /// Continue if this hook fails (default: true)
269 #[serde(default = "default_continue_on_error")]
270 pub continue_on_error: bool,
271
272 /// Optional name for logging/debugging
273 #[serde(default)]
274 pub name: Option<String>,
275
276 /// Content- and generation-bound authority for a plugin-contributed hook.
277 /// Never accepted from TOML; only the reviewed staged adapter may attach
278 /// it after parsing immutable bytes.
279 #[serde(skip)]
280 pub plugin_authority: Option<crate::PluginAuthority>,
281
282 /// Exact-byte project approval attached by the loader; never read from TOML.
283 #[serde(skip)]
284 pub project_authority: Option<crate::ProjectHookAuthority>,
285 }
286
287 fn default_timeout() -> u64 {
288 30
289 }
290
291 fn default_continue_on_error() -> bool {
292 true
293 }
294
295 impl Hook {
296 /// Create a new hook with minimal configuration
297 pub fn new(event: HookEvent, command: &str) -> Self {
298 Self {
299 event,
300 command: command.to_string(),
301 condition: None,
302 timeout_secs: 30,
303 background: false,
304 continue_on_error: true,
305 name: None,
306 plugin_authority: None,
307 project_authority: None,
308 native_shell: None,
309 }
310 }
311
312 /// Builder: set condition
313 pub fn with_condition(mut self, condition: HookCondition) -> Self {
314 self.condition = Some(condition);
315 self
316 }
317
318 /// Builder: set timeout
319 pub fn with_timeout(mut self, secs: u64) -> Self {
320 self.timeout_secs = secs;
321 self
322 }
323
324 /// Builder: run in background
325 pub fn background(mut self) -> Self {
326 self.background = true;
327 self
328 }
329
330 /// Builder: set name
331 pub fn with_name(mut self, name: &str) -> Self {
332 self.name = Some(name.to_string());
333 self
334 }
335 }
336
337 /// A configured hook that can never behave the way it is written.
338 ///
339 /// Reported by [`HooksConfig::validate`] and, for rejections, surfaced in
340 /// `/hooks list` so a broken hook is visible instead of silently inert.
341 #[derive(Debug, Clone, PartialEq, Eq)]
342 pub struct HookConfigProblem {
343 /// Hook `name`, or `None` for an unnamed entry.
344 pub name: Option<String>,
345 /// The event the hook is registered for, or `None` when the problem is
346 /// with a setting in the `[hooks]` table itself rather than with one
347 /// entry — `default_timeout_secs` governs every hook, so pinning its
348 /// rejection on an arbitrary hook would misreport the blast radius.
349 pub event: Option<HookEvent>,
350 /// What is wrong, in one line, with no paths or payload content.
351 pub detail: String,
352 /// `true` when the hook is dropped at load and will never run.
353 pub rejected: bool,
354 }
355
356 /// Configuration for hooks (loaded from config.toml)
357 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
358 pub struct HooksConfig {
359 /// List of hooks to execute
360 #[serde(default)]
361 pub hooks: Vec<Hook>,
362
363 /// Global enable/disable for all hooks
364 #[serde(default = "default_enabled")]
365 pub enabled: bool,
366
367 /// Global timeout override. When set this **replaces** every hook's own
368 /// `timeout_secs` rather than only filling in for hooks that omit one —
369 /// see `HookExecutor::execute_sync_inner`. Documented as-implemented in
370 /// `docs/HOOKS.md`; leave unset for per-hook timeouts.
371 #[serde(default)]
372 pub default_timeout_secs: Option<u64>,
373
374 /// Working directory for hook execution (default: workspace)
375 #[serde(default)]
376 pub working_dir: Option<PathBuf>,
377
378 /// Problems found by [`HooksConfig::validate`] at load time. Never read
379 /// from or written to `config.toml`; populated by
380 /// the host loader so `/hooks` can show a rejected
381 /// hook instead of leaving it silently inert.
382 #[serde(skip)]
383 pub problems: Vec<HookConfigProblem>,
384 }
385
386 fn default_enabled() -> bool {
387 true
388 }
389
390 impl HooksConfig {
391 /// Report every configured hook that cannot behave as written.
392 ///
393 /// A condition that references context the event never carries can never
394 /// match, so a hook wearing one is inert — the dangerous version of that
395 /// is a `deny` gate the operator believes is armed. Those are reported as
396 /// `rejected` and dropped by the host loader rather than left
397 /// to fail silently at dispatch time. Problems that only affect how a
398 /// hook is scheduled are reported as warnings and the hook still runs.
399 #[must_use]
400 pub fn validate(&self) -> Vec<HookConfigProblem> {
401 self.validate_settings()
402 .into_iter()
403 .chain(self.validate_indexed().into_iter().map(|(_, p)| p))
404 .collect()
405 }
406
407 /// Problems with the `[hooks]` table itself, independent of any entry.
408 ///
409 /// `default_timeout_secs = 0` is the one that matters: it *replaces* every
410 /// hook's own `timeout_secs`, so the per-hook `timeout_secs = 0` rejection
411 /// does nothing to stop one line from killing every hook in the config
412 /// before it can produce output — including a `tool_call_before` gate,
413 /// which then fails closed on every tool call.
414 pub fn validate_settings(&self) -> Vec<HookConfigProblem> {
415 let mut problems = Vec::new();
416 if self.default_timeout_secs == Some(0) {
417 problems.push(HookConfigProblem {
418 name: None,
419 event: None,
420 detail: "`default_timeout_secs = 0` would expire every hook immediately; \
421 the override is ignored and per-hook `timeout_secs` applies"
422 .to_string(),
423 rejected: true,
424 });
425 }
426 problems
427 }
428
429 /// [`Self::validate`], but each problem is paired with the index of the
430 /// entry that produced it.
431 ///
432 /// The index is the hook's identity for rejection purposes. Keying on
433 /// `(name, event)` instead would make one invalid unnamed `session_start`
434 /// entry delete *every* unnamed `session_start` entry, and one invalid
435 /// `gate` delete every other hook also called `gate` — innocent hooks
436 /// dropped because they share a label with a broken one.
437 pub fn validate_indexed(&self) -> Vec<(usize, HookConfigProblem)> {
438 let mut problems = Vec::new();
439 for (index, hook) in self.hooks.iter().enumerate() {
440 let mut condition_rejections = Vec::new();
441 collect_condition_problems(hook.event, hook.condition.as_ref(), &mut |detail| {
442 condition_rejections.push(detail);
443 });
444
445 let mut push = |detail: String, rejected: bool| {
446 problems.push((
447 index,
448 HookConfigProblem {
449 name: hook.name.clone(),
450 event: Some(hook.event),
451 detail,
452 rejected,
453 },
454 ));
455 };
456 // A condition that can never match makes the hook inert, so it is
457 // dropped; the rest only affect how the hook is scheduled, so the
458 // hook still runs and the problem is a warning.
459 for detail in condition_rejections {
460 push(detail, true);
461 }
462
463 if hook.background && !hook.event.honors_background() {
464 push(
465 format!(
466 "`background = true` is not honored for `{}`; its stdout is the \
467 contract, so it always runs in the foreground",
468 hook.event.as_str()
469 ),
470 false,
471 );
472 } else if hook.background && hook.event.can_steer() {
473 push(
474 format!(
475 "`background = true` makes this `{}` hook observer-only — it is \
476 submitted and never awaited, so it cannot steer the turn",
477 hook.event.as_str()
478 ),
479 false,
480 );
481 }
482
483 if hook.timeout_secs == 0 {
484 push(
485 "`timeout_secs = 0` expires immediately; the command is killed \
486 before it can produce output"
487 .to_string(),
488 true,
489 );
490 }
491
492 if hook.command.trim().is_empty() {
493 push("`command` is empty".to_string(), true);
494 }
495 }
496 problems
497 }
498
499 /// Get hooks for a specific event
500 pub fn hooks_for_event(&self, event: HookEvent) -> Vec<&Hook> {
501 if !self.enabled {
502 return Vec::new();
503 }
504 self.hooks.iter().filter(|h| h.event == event).collect()
505 }
506
507 /// The timeout the runtime will actually apply to `hook`.
508 ///
509 /// `[hooks].default_timeout_secs` *replaces* the per-hook value when set.
510 /// This is the single owner of that rule: the executor enforces it and
511 /// `/hooks list` displays it, so the listing cannot advertise a per-hook
512 /// number the runtime will not use.
513 #[must_use]
514 pub fn effective_timeout_secs(&self, hook: &Hook) -> u64 {
515 // `filter`, not `unwrap_or`: `apply_validation` already strips a zero
516 // override at load, but a `HooksConfig` can also be built in code, and
517 // a zero here means "kill every hook before it speaks".
518 self.default_timeout_secs
519 .filter(|secs| *secs > 0)
520 .unwrap_or(hook.timeout_secs)
521 }
522
523 /// `true` when `[hooks].default_timeout_secs` is overriding per-hook
524 /// timeouts, so surfaces can name the provenance of the number they show.
525 #[must_use]
526 pub fn timeout_is_overridden(&self) -> bool {
527 // An ignored zero override is not provenance: `/hooks list` must not
528 // credit a number to a setting the runtime refused to apply.
529 self.default_timeout_secs.is_some_and(|secs| secs > 0)
530 }
531 }
532
533 /// Walk a condition tree and report every predicate the event can never
534 /// satisfy. `all` / `any` are walked so a nested unsupported predicate is
535 /// caught rather than hidden behind a combinator.
536 fn collect_condition_problems(
537 event: HookEvent,
538 condition: Option<&HookCondition>,
539 reject: &mut impl FnMut(String),
540 ) {
541 let Some(condition) = condition else {
542 return;
543 };
544 match condition {
545 HookCondition::Always => {}
546 HookCondition::ToolName { .. } | HookCondition::ToolCategory { .. } => {
547 if !event.provides_tool_identity() {
548 reject(format!(
549 "`{}` never carries a tool name, so this tool condition can never match",
550 event.as_str()
551 ));
552 }
553 }
554 HookCondition::Mode { .. } => {
555 if !event.provides_mode() {
556 reject(format!(
557 "`{}` runs with a narrow context that has no mode, so a `mode` \
558 condition can never match; scope it with `tool_name` or \
559 `tool_category` instead",
560 event.as_str()
561 ));
562 }
563 }
564 HookCondition::ExitCode { .. } => {
565 if !event.provides_exit_code() {
566 reject(format!(
567 "`{}` has no completed process to read an exit code from; \
568 `exit_code` conditions are only supported on `tool_call_after` \
569 and `on_error`",
570 event.as_str()
571 ));
572 }
573 }
574 HookCondition::All { conditions } | HookCondition::Any { conditions } => {
575 for nested in conditions {
576 // Reborrow rather than pass `reject` itself: `&mut F` also
577 // implements `FnMut`, so passing it directly would recurse in
578 // the type parameter and never finish monomorphizing.
579 collect_condition_problems(event, Some(nested), &mut *reject);
580 }
581 }
582 }
583 }
584
584 lines RUST