1use 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#[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 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 pub fn name(self) -> String {
90 format!("{self:?}")
91 }
92}
93
94#[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 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 #[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 #[serde(skip)]
136 pub spend: Option<Arc<SpendNode>>,
137}
138
139pub type HookAmbient = Arc<dyn Fn() -> HookInput + Send + Sync>;
142
143impl HookInput {
144 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 pub fn from_ambient(ambient: &HookAmbient, event: impl Into<String>) -> Self {
214 Self::lifecycle_of(ambient(), event)
215 }
216
217 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
227pub struct HookBlock {
228 pub message: Option<String>,
229}
230
231#[derive(Debug, Clone, Default)]
233pub struct HookVerdict {
234 pub blocked: Option<HookBlock>,
235 pub approved: bool,
237 pub discontinued: bool,
239 pub discontinue_message: Option<String>,
240 pub updated_input: Option<serde_json::Value>,
242 pub context: Vec<String>,
245}
246
247#[async_trait]
249pub trait Hooks: Send + Sync {
250 fn has_hooks_for(&self, event: HookEvent) -> bool;
251
252 async fn run(
255 &self,
256 event: HookEvent,
257 input: &HookInput,
258 stop: &CancellationToken,
259 ) -> HookVerdict;
260
261 fn start_watching(&self, _paths: &[PathBuf], _ambient: HookAmbient) -> Result<(), String> {
264 Ok(())
265 }
266
267 fn watch_files(&self, _paths: &[PathBuf]) -> Result<(), String> {
269 Ok(())
270 }
271
272 async fn check_rewakes(&self, _stop: &CancellationToken, _ambient: HookInput) {}
275
276 fn route_host_calls(&self, _session_id: &str, _calls: &Arc<dyn super::host_call::HostCalls>) {}
279}
280
281pub 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#[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#[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 NotJudged,
326 Failed(String),
327}
328
329pub struct HookSession {
331 pub session_id: String,
332 pub config: Option<serde_json::Value>,
334 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 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
350pub 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}