Skip to main content

claude_code_agent/
hooks.rs

1//! Hook registry — async Rust closures for all 33 hook event types.
2//!
3//! Build it before spawning and pass it in `SessionOptions::hooks`: the CLI
4//! learns which hooks exist only from the `initialize` request, so hooks
5//! registered after spawn would never fire.
6//!
7//! Each `on()` call becomes one matcher with one callback id `hook_<n>`; when
8//! the hook fires the CLI sends `hook_callback { callback_id: "hook_<n>" }`.
9//! Source: `claude_agent_sdk` 0.1.48 _internal/query.py:128–147, :285–300
10use std::collections::HashMap;
11use std::fmt;
12use std::future::Future;
13use std::pin::Pin;
14use std::sync::Arc;
15
16use crate::protocol::{HookEventKind, HookEventPayload, HookMatcherConfig, HookOutput};
17
18type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
19type HookFn = Arc<dyn Fn(HookEventPayload) -> BoxFuture<HookOutput> + Send + Sync>;
20
21#[derive(Clone)]
22struct Entry {
23    event: HookEventKind,
24    matcher: Option<String>,
25    timeout_s: Option<u32>,
26    handler: HookFn,
27}
28
29/// Registry of async hook handlers. Cheap to clone.
30#[derive(Clone, Default)]
31pub struct HookRegistry {
32    entries: Vec<Entry>,
33}
34
35impl fmt::Debug for HookRegistry {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.debug_list()
38            .entries(self.entries.iter().map(|e| (&e.event, &e.matcher)))
39            .finish()
40    }
41}
42
43impl HookRegistry {
44    /// An empty registry.
45    #[must_use]
46    pub fn new() -> Self {
47        Self::default()
48    }
49
50    /// Register an async closure for a hook event.
51    ///
52    /// `matcher` filters by tool name for tool events (regex, e.g. `"Bash|Edit"`);
53    /// `None` matches everything.
54    ///
55    /// ```rust,no_run
56    /// # use claude_code_agent::HookRegistry;
57    /// # use claude_code_agent::protocol::{HookEventKind, HookOutput};
58    /// let mut hooks = HookRegistry::new();
59    /// hooks.on(HookEventKind::PreToolUse, Some("Bash"), |payload| async move {
60    ///     HookOutput::block("Bash is disabled")
61    /// });
62    /// ```
63    pub fn on<F, Fut>(&mut self, event: HookEventKind, matcher: Option<&str>, handler: F) -> &mut Self
64    where
65        F: Fn(HookEventPayload) -> Fut + Send + Sync + 'static,
66        Fut: Future<Output = HookOutput> + Send + 'static,
67    {
68        self.on_with_timeout(event, matcher, None, handler)
69    }
70
71    /// Same as `on`, with a per-hook timeout in seconds enforced by the CLI.
72    pub fn on_with_timeout<F, Fut>(
73        &mut self,
74        event: HookEventKind,
75        matcher: Option<&str>,
76        timeout_s: Option<u32>,
77        handler: F,
78    ) -> &mut Self
79    where
80        F: Fn(HookEventPayload) -> Fut + Send + Sync + 'static,
81        Fut: Future<Output = HookOutput> + Send + 'static,
82    {
83        let handler: HookFn = Arc::new(move |p| Box::pin(handler(p)));
84        self.entries.push(Entry {
85            event,
86            matcher: matcher.map(str::to_owned),
87            timeout_s,
88            handler,
89        });
90        self
91    }
92
93    /// `on(PreToolUse, None, f)`: runs before every tool call.
94    pub fn on_pre_tool_use<F, Fut>(&mut self, f: F) -> &mut Self
95    where
96        F: Fn(HookEventPayload) -> Fut + Send + Sync + 'static,
97        Fut: Future<Output = HookOutput> + Send + 'static,
98    {
99        self.on(HookEventKind::PreToolUse, None, f)
100    }
101
102    /// `on(Stop, None, f)`.
103    pub fn on_stop<F, Fut>(&mut self, f: F) -> &mut Self
104    where
105        F: Fn(HookEventPayload) -> Fut + Send + Sync + 'static,
106        Fut: Future<Output = HookOutput> + Send + 'static,
107    {
108        self.on(HookEventKind::Stop, None, f)
109    }
110
111    /// `on(UserPromptSubmit, None, f)`.
112    pub fn on_user_prompt_submit<F, Fut>(&mut self, f: F) -> &mut Self
113    where
114        F: Fn(HookEventPayload) -> Fut + Send + Sync + 'static,
115        Fut: Future<Output = HookOutput> + Send + 'static,
116    {
117        self.on(HookEventKind::UserPromptSubmit, None, f)
118    }
119
120    /// Whether no hook is registered.
121    #[must_use]
122    pub fn is_empty(&self) -> bool {
123        self.entries.is_empty()
124    }
125
126    /// The `hooks` field of the initialize request.
127    #[must_use]
128    pub fn initialize_config(&self) -> Option<HashMap<HookEventKind, Vec<HookMatcherConfig>>> {
129        if self.entries.is_empty() {
130            return None;
131        }
132        let mut config: HashMap<HookEventKind, Vec<HookMatcherConfig>> = HashMap::new();
133        for (i, e) in self.entries.iter().enumerate() {
134            config.entry(e.event).or_default().push(HookMatcherConfig {
135                matcher: e.matcher.clone(),
136                hook_callback_ids: vec![callback_id(i)],
137                timeout: e.timeout_s,
138            });
139        }
140        Some(config)
141    }
142
143    /// Run the handler registered under `callback_id`.
144    /// Returns `None` when the id is unknown.
145    pub async fn dispatch(&self, callback_id: &str, payload: HookEventPayload) -> Option<HookOutput> {
146        let index: usize = callback_id.strip_prefix("hook_")?.parse().ok()?;
147        let entry = self.entries.get(index)?;
148        Some((entry.handler)(payload).await)
149    }
150}
151
152fn callback_id(index: usize) -> String {
153    format!("hook_{index}")
154}