Skip to main content

base/interface/
hooks.rs

1//! Lifecycle hooks as the engine sees them: the events, the payload a hook is
2//! sent, the merged answer of one run, and the trait the session holds. The
3//! runner that parses the settings' `hooks` and runs commands, prompts, HTTP
4//! and agents is the `hooks` crate's (`hooks::Factory`); [`NoHooks`] is what a
5//! session runs on without it. What each event carries and what an answer can
6//! do there is documented by `hooks::catalog`.
7
8use std::path::PathBuf;
9use std::sync::Arc;
10
11use async_trait::async_trait;
12use serde::{Deserialize, Serialize};
13use tokio_util::sync::CancellationToken;
14
15use super::budget_policy::SpendNode;
16use super::exec::{Network, Process};
17use crate::telemetry::TelemetrySink;
18
19/// The events a settings file keys hooks by.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
21pub enum HookEvent {
22    PreToolUse,
23    PostToolUse,
24    PostToolUseFailure,
25    TurnStart,
26    TurnComplete,
27    SessionStart,
28    SessionEnd,
29    Stop,
30    StopFailure,
31    UserPromptSubmit,
32    PreCompact,
33    PostCompact,
34    PermissionRequested,
35    PermissionDenied,
36    Setup,
37    Notification,
38    SubagentStop,
39    SubagentStart,
40    TeammateIdle,
41    TaskCreated,
42    TaskCompleted,
43    Elicitation,
44    ElicitationResult,
45    WorktreeCreate,
46    WorktreeRemove,
47    InstructionsLoaded,
48    CwdChanged,
49    FileChanged,
50    PostSampling,
51}
52
53impl HookEvent {
54    /// Every variant, in declaration order.
55    pub const ALL: [HookEvent; 29] = [
56        HookEvent::PreToolUse,
57        HookEvent::PostToolUse,
58        HookEvent::PostToolUseFailure,
59        HookEvent::TurnStart,
60        HookEvent::TurnComplete,
61        HookEvent::SessionStart,
62        HookEvent::SessionEnd,
63        HookEvent::Stop,
64        HookEvent::StopFailure,
65        HookEvent::UserPromptSubmit,
66        HookEvent::PreCompact,
67        HookEvent::PostCompact,
68        HookEvent::PermissionRequested,
69        HookEvent::PermissionDenied,
70        HookEvent::Setup,
71        HookEvent::Notification,
72        HookEvent::SubagentStop,
73        HookEvent::SubagentStart,
74        HookEvent::TeammateIdle,
75        HookEvent::TaskCreated,
76        HookEvent::TaskCompleted,
77        HookEvent::Elicitation,
78        HookEvent::ElicitationResult,
79        HookEvent::WorktreeCreate,
80        HookEvent::WorktreeRemove,
81        HookEvent::InstructionsLoaded,
82        HookEvent::CwdChanged,
83        HookEvent::FileChanged,
84        HookEvent::PostSampling,
85    ];
86
87    /// The name a settings file keys the event by, and the payload's
88    /// `hook_event_name`.
89    pub fn name(self) -> String {
90        format!("{self:?}")
91    }
92}
93
94/// What a hook is sent. Which optional fields are set depends on the event.
95#[derive(Debug, Clone, Serialize, Default)]
96pub struct HookInput {
97    pub hook_event_name: String,
98    pub session_id: String,
99    pub cwd: String,
100    pub permission_mode: String,
101    /// How many delegations deep the session is; `0` for the root.
102    pub depth: u32,
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub tool_name: Option<String>,
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub tool_input: Option<serde_json::Value>,
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub tool_use_id: Option<String>,
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub tool_result: Option<serde_json::Value>,
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub is_error: Option<bool>,
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub user_prompt: Option<String>,
115    /// `"turn"` opens a turn, `"steer"` joins the running one.
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub delivery: Option<String>,
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub turn_id: Option<String>,
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub stop_reason: Option<String>,
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub agent_type: Option<String>,
124    #[serde(skip_serializing_if = "Option::is_none")]
125    pub reason: Option<String>,
126    #[serde(skip_serializing_if = "Option::is_none")]
127    pub source: Option<String>,
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub stop_hook_active: Option<bool>,
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub team_name: Option<String>,
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub teammate_name: Option<String>,
134    /// The turn a hook that calls a model spends into. Never sent to a hook.
135    #[serde(skip)]
136    pub spend: Option<Arc<SpendNode>>,
137}
138
139/// The fields every payload of a session carries, read when the hook fires:
140/// the permission mode changes under a session, so a snapshot would go stale.
141pub type HookAmbient = Arc<dyn Fn() -> HookInput + Send + Sync>;
142
143impl HookInput {
144    /// The payload of `event`; callers set what their event carries on top.
145    pub fn lifecycle(
146        event: impl Into<String>,
147        session_id: impl Into<String>,
148        cwd: impl Into<String>,
149        permission_mode: impl Into<String>,
150    ) -> Self {
151        Self {
152            hook_event_name: event.into(),
153            session_id: session_id.into(),
154            cwd: cwd.into(),
155            permission_mode: permission_mode.into(),
156            ..Default::default()
157        }
158    }
159
160    pub fn with_depth(mut self, depth: u32) -> Self {
161        self.depth = depth;
162        self
163    }
164
165    pub fn with_turn_id(mut self, turn_id: impl Into<String>) -> Self {
166        self.turn_id = Some(turn_id.into());
167        self
168    }
169
170    pub fn with_stop_reason(mut self, reason: impl Into<String>) -> Self {
171        self.stop_reason = Some(reason.into());
172        self
173    }
174
175    pub fn with_agent_type(mut self, agent_type: Option<String>) -> Self {
176        self.agent_type = agent_type;
177        self
178    }
179
180    pub fn with_tool(mut self, name: impl Into<String>, input: serde_json::Value) -> Self {
181        self.tool_name = Some(name.into());
182        self.tool_input = Some(input);
183        self
184    }
185
186    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
187        self.reason = Some(reason.into());
188        self
189    }
190
191    pub fn with_source(mut self, source: impl Into<String>) -> Self {
192        self.source = Some(source.into());
193        self
194    }
195
196    pub fn spending_into(mut self, spend: Option<Arc<SpendNode>>) -> Self {
197        self.spend = spend;
198        self
199    }
200
201    pub fn with_team(
202        mut self,
203        team_name: impl Into<String>,
204        teammate_name: impl Into<String>,
205    ) -> Self {
206        self.team_name = Some(team_name.into());
207        self.teammate_name = Some(teammate_name.into());
208        self
209    }
210
211    /// `ambient`'s session, cwd, permission mode, depth and spend under
212    /// `event`.
213    pub fn from_ambient(ambient: &HookAmbient, event: impl Into<String>) -> Self {
214        Self::lifecycle_of(ambient(), event)
215    }
216
217    /// `base`'s session, cwd, permission mode, depth and spend under `event`.
218    pub fn lifecycle_of(base: HookInput, event: impl Into<String>) -> Self {
219        Self::lifecycle(event, base.session_id, base.cwd, base.permission_mode)
220            .with_depth(base.depth)
221            .spending_into(base.spend)
222    }
223}
224
225/// A hook refused the action.
226#[derive(Debug, Clone, Default, PartialEq, Eq)]
227pub struct HookBlock {
228    pub message: Option<String>,
229}
230
231/// What one run of an event's hooks came to, merged.
232#[derive(Debug, Clone, Default)]
233pub struct HookVerdict {
234    pub blocked: Option<HookBlock>,
235    /// A hook answered a permission question in advance.
236    pub approved: bool,
237    /// A hook asked to end the turn.
238    pub discontinued: bool,
239    pub discontinue_message: Option<String>,
240    /// The input the action goes on with, where the event reads a rewrite.
241    pub updated_input: Option<serde_json::Value>,
242    /// System reminders for the model; empty when blocked or where the event
243    /// takes none.
244    pub context: Vec<String>,
245}
246
247/// A session's hooks; one is shared by a session and its delegates.
248#[async_trait]
249pub trait Hooks: Send + Sync {
250    fn has_hooks_for(&self, event: HookEvent) -> bool;
251
252    /// Run `event`'s hooks on `input`; once `stop` is cancelled those still
253    /// running are stopped.
254    async fn run(
255        &self,
256        event: HookEvent,
257        input: &HookInput,
258        stop: &CancellationToken,
259    ) -> HookVerdict;
260
261    /// Start the `FileChanged` watcher on `paths`, payloads from `ambient`.
262    /// Called by the root session only.
263    fn start_watching(&self, _paths: &[PathBuf], _ambient: HookAmbient) -> Result<(), String> {
264        Ok(())
265    }
266
267    /// Add `paths` to a watcher already started; nothing when none was.
268    fn watch_files(&self, _paths: &[PathBuf]) -> Result<(), String> {
269        Ok(())
270    }
271
272    /// Re-run the hooks waiting to be woken once their wake signal came, on
273    /// payloads from `ambient`.
274    async fn check_rewakes(&self, _stop: &CancellationToken, _ambient: HookInput) {}
275
276    /// The host calls of `session_id`, one of the sessions these hooks serve,
277    /// for the hooks host connections answer.
278    fn route_host_calls(&self, _session_id: &str, _calls: &Arc<dyn super::host_call::HostCalls>) {}
279}
280
281/// No hooks: nothing runs, nothing is refused.
282pub struct NoHooks;
283
284#[async_trait]
285impl Hooks for NoHooks {
286    fn has_hooks_for(&self, _: HookEvent) -> bool {
287        false
288    }
289
290    async fn run(&self, _: HookEvent, _: &HookInput, _: &CancellationToken) -> HookVerdict {
291        HookVerdict::default()
292    }
293}
294
295/// Runs a `"type": "prompt"` hook: the model's answer, as the JSON text of a
296/// hook response. Returns soon once `stop` is cancelled.
297#[async_trait]
298pub trait PromptHookExecutor: Send + Sync {
299    async fn execute(
300        &self,
301        prompt: &str,
302        model: Option<&str>,
303        payload: &HookInput,
304        stop: &CancellationToken,
305    ) -> Result<String, String>;
306}
307
308/// Runs a `"type": "agent"` hook: the agent's `{"ok": bool, "reason": ...}`
309/// as JSON text. The agent stops when `stop` does.
310#[async_trait]
311pub trait AgentHookExecutor: Send + Sync {
312    async fn execute(
313        &self,
314        prompt: &str,
315        model: Option<&str>,
316        payload: &HookInput,
317        stop: &CancellationToken,
318    ) -> Result<String, AgentHookError>;
319}
320
321#[derive(Debug, Clone, PartialEq, Eq)]
322pub enum AgentHookError {
323    /// The event is a hook agent's own, or one of its descendants': agent
324    /// hooks do not judge those, so the hook does not apply rather than fail.
325    NotJudged,
326    Failed(String),
327}
328
329/// What a session's own hooks are built from.
330pub struct HookSession {
331    pub session_id: String,
332    /// The settings' `hooks`, an untrusted project's already withheld.
333    pub config: Option<serde_json::Value>,
334    /// Where a command hook's bare script name is looked up, in order.
335    pub search_dirs: Vec<PathBuf>,
336    pub project_untrusted: bool,
337    pub process: Arc<dyn Process>,
338    pub network: Arc<dyn Network>,
339    pub prompts: Arc<dyn PromptHookExecutor>,
340    pub agents: Arc<dyn AgentHookExecutor>,
341    pub telemetry: Arc<dyn TelemetrySink>,
342    /// Signalled when background work ends, to re-run waiting rewake hooks.
343    pub wake: Option<tokio::sync::mpsc::UnboundedReceiver<()>>,
344}
345
346pub trait HooksFactory: Send + Sync {
347    fn build(&self, session: HookSession) -> Arc<dyn Hooks>;
348}
349
350/// Whether a settings `hooks` section asks for any hook: anything but
351/// nothing, `null`, or events each with an empty list.
352pub fn configures_hooks(config: Option<&serde_json::Value>) -> bool {
353    use serde_json::Value;
354    match config {
355        None | Some(Value::Null) => false,
356        Some(Value::Object(events)) => events
357            .values()
358            .any(|hooks| !matches!(hooks, Value::Array(list) if list.is_empty())),
359        Some(_) => true,
360    }
361}