claude_agent_sdk/types/
hooks.rs1use crate::error::Result;
2use std::collections::HashMap;
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6
7pub type HookFuture = Pin<Box<dyn Future<Output = Result<serde_json::Value>> + Send>>;
8type HookFn = dyn Fn(serde_json::Value, Option<String>, HookContext) -> HookFuture + Send + Sync;
9
10#[derive(Debug, Clone, Default)]
11pub struct HookContext {}
12
13#[derive(Clone)]
14pub struct HookCallback(Arc<HookFn>);
15
16impl std::fmt::Debug for HookCallback {
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 f.debug_tuple("HookCallback").field(&"<callback>").finish()
19 }
20}
21
22impl HookCallback {
23 pub fn new<F, Fut>(callback: F) -> Self
24 where
25 F: Fn(serde_json::Value, Option<String>, HookContext) -> Fut + Send + Sync + 'static,
26 Fut: Future<Output = Result<serde_json::Value>> + Send + 'static,
27 {
28 Self(Arc::new(move |input, tool_use_id, context| {
29 Box::pin(callback(input, tool_use_id, context))
30 }))
31 }
32
33 pub async fn call(
34 &self,
35 input: serde_json::Value,
36 tool_use_id: Option<String>,
37 context: HookContext,
38 ) -> Result<serde_json::Value> {
39 (self.0)(input, tool_use_id, context).await
40 }
41}
42
43#[derive(Debug, Clone, Default)]
44pub struct HookMatcher {
45 pub matcher: Option<String>,
46 pub hooks: Vec<HookCallback>,
47 pub timeout: Option<f64>,
48}
49
50impl HookMatcher {
51 pub fn new(callback: HookCallback) -> Self {
52 Self {
53 matcher: None,
54 hooks: vec![callback],
55 timeout: None,
56 }
57 }
58
59 pub fn matcher(mut self, matcher: impl Into<String>) -> Self {
60 self.matcher = Some(matcher.into());
61 self
62 }
63
64 pub fn timeout(mut self, timeout: f64) -> Self {
65 self.timeout = Some(timeout);
66 self
67 }
68}
69
70pub type HookMap = HashMap<String, Vec<HookMatcher>>;