claude_code_agent/
hooks.rs1use 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#[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 #[must_use]
46 pub fn new() -> Self {
47 Self::default()
48 }
49
50 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 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 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 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 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 #[must_use]
122 pub fn is_empty(&self) -> bool {
123 self.entries.is_empty()
124 }
125
126 #[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 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}