Skip to main content

strands/hooks/
registry.rs

1//! The typed hook registry.
2//!
3//! Each event type has its own list of callbacks. Sequential events borrow the agent
4//! (`BeforeInvocationEvent<'a>`), so the registry is keyed by a `'static` marker: the event type
5//! with `'static` for its lifetime (`BeforeInvocationEvent<'static>`). Per-tool events are
6//! `'static` already and are their own marker. Callers never name markers except in
7//! [`HookRegistry::add_async_hook`]'s turbofish, where `BeforeInvocationEvent<'_>` works.
8
9use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
10use std::sync::{Arc, PoisonError, RwLock, Weak};
11
12use async_trait::async_trait;
13use futures::future::BoxFuture;
14
15use super::events::{
16    AfterInvocationEvent, AfterModelCallEvent, AfterToolCallEvent, AfterToolsEvent, AgentResultEvent,
17    BeforeInvocationEvent, BeforeModelCallEvent, BeforeToolCallEvent, BeforeToolsEvent, ContentBlockEvent,
18    InitializedEvent, InterruptEvent, MessageAddedEvent, ModelMessageEvent, ModelStreamUpdateEvent, ToolResultEvent,
19    ToolStreamUpdateEvent,
20};
21use super::types::{HookCallbackOptions, HookCleanup};
22use crate::error::{BoxError, Error, Result};
23use crate::interrupt::{Interrupt, InterruptError};
24
25type HookResult = std::result::Result<(), BoxError>;
26type SyncCallback<K> = Arc<dyn for<'a, 'b> Fn(&'b mut <K as HookEvent>::Event<'a>) -> HookResult + Send + Sync>;
27type AsyncCallback<K> =
28    Arc<dyn for<'a, 'b> Fn(&'b mut <K as HookEvent>::Event<'a>) -> BoxFuture<'b, HookResult> + Send + Sync>;
29
30mod private {
31    use super::{HookEvent, HookRegistry, Slot};
32
33    /// Seals [`HookEvent`] to the SDK's events and finds an event's slot in the registry.
34    pub trait Sealed: Sized + 'static {
35        #[doc(hidden)]
36        fn slot(registry: &HookRegistry) -> &Slot<Self>
37        where
38            Self: HookEvent;
39    }
40
41    /// Seals [`HookOutput`](super::HookOutput).
42    pub trait SealedOutput {}
43
44    impl SealedOutput for () {}
45    impl<E> SealedOutput for Result<(), E> {}
46
47    /// Only the SDK can name it, so only the SDK implements the conversion traits.
48    #[derive(Debug)]
49    pub struct Token;
50}
51
52/// A hook event type, as the registry keys it (sealed).
53///
54/// Implemented by `'static` markers: per-tool events themselves and the `'static` form of
55/// borrowing events, such as `BeforeInvocationEvent<'static>`. `Event<'a>` is the event type
56/// callbacks receive.
57pub trait HookEvent: private::Sealed {
58    /// The event type for an agent borrow of lifetime `'a`.
59    type Event<'a>: Send;
60
61    /// Whether callbacks with the same order run in reverse registration order (`After*` events).
62    #[doc(hidden)]
63    const REVERSE: bool = false;
64
65    /// Takes the interrupts raised on the event (only interruptible events raise any).
66    #[doc(hidden)]
67    fn take_interrupts(_event: &mut Self::Event<'_>) -> Vec<Interrupt> {
68        Vec::new()
69    }
70}
71
72/// Maps a concrete hook event type of any lifetime to its [`HookEvent`] marker.
73#[doc(hidden)]
74pub trait EventKind<'a>: Send + Sized {
75    /// The marker.
76    type Kind: HookEvent<Event<'a> = Self>;
77}
78
79/// What a hook returns (sealed): `()`, or `Result<(), E>` for any `E: Into<BoxError>`.
80///
81/// An `Err` fails the invocation with that error; the callbacks after it do not run. An
82/// [`InterruptError`], such as the one the events' `interrupt` returns, is not a failure: it stops
83/// the agent for human input once every callback has run.
84pub trait HookOutput: private::SealedOutput {
85    #[doc(hidden)]
86    fn into_hook_result(self) -> HookResult;
87}
88
89impl HookOutput for () {
90    fn into_hook_result(self) -> HookResult {
91        Ok(())
92    }
93}
94
95impl<E: Into<BoxError>> HookOutput for std::result::Result<(), E> {
96    fn into_hook_result(self) -> HookResult {
97        self.map_err(Into::into)
98    }
99}
100
101/// A plain closure usable as a hook for the event `K` (`HookCallback`), sealed.
102///
103/// Implemented for every `Fn(&mut Event) -> R + Send + Sync + 'static` where `R` is a
104/// [`HookOutput`]. Annotate the closure argument (`|event: &mut BeforeToolCallEvent| ..`) so the
105/// event type can be inferred.
106pub trait IntoSyncHook<K: HookEvent> {
107    #[doc(hidden)]
108    fn into_callback(self, token: private::Token) -> SyncCallback<K>;
109}
110
111/// An async closure usable as a hook for the event `K`: it returns `Box::pin(async move { .. })`
112/// whose output is a [`HookOutput`].
113///
114/// Implemented for every such closure; name the event with
115/// [`add_async_hook::<E>`](HookRegistry::add_async_hook).
116pub trait IntoAsyncHook<K: HookEvent>:
117    for<'a, 'b> Fn(&'b mut K::Event<'a>) -> BoxFuture<'b, <Self as IntoAsyncHook<K>>::Output> + Send + Sync + 'static
118{
119    /// What the closure's future returns.
120    type Output: HookOutput;
121}
122
123impl<K, F, R> IntoAsyncHook<K> for F
124where
125    K: HookEvent,
126    F: for<'a, 'b> Fn(&'b mut K::Event<'a>) -> BoxFuture<'b, R> + Send + Sync + 'static,
127    R: HookOutput,
128{
129    type Output = R;
130}
131
132/// A [`Hook`] implementation usable for the event `K`, sealed.
133///
134/// Implemented for every `H: Hook<Event>`. When a type implements [`Hook`] for several events,
135/// name the event: `add_hook_impl::<BeforeToolCallEvent>(hook)`.
136pub trait IntoHookImpl<K: HookEvent> {
137    #[doc(hidden)]
138    fn into_callback(self, token: private::Token) -> AsyncCallback<K>;
139}
140
141/// A reusable or stateful hook (`HookCallback` as an object).
142///
143/// Return `Ok(())`, or an error to fail the invocation (see [`HookOutput`]). Implementations
144/// for events that borrow the agent name the lifetime: `impl<'a> Hook<BeforeInvocationEvent<'a>>`
145/// with `event: &mut BeforeInvocationEvent<'a>`; eliding it (`Hook<BeforeInvocationEvent<'_>>`)
146/// implements the trait for one lifetime only, and registration then fails to compile.
147///
148/// ```
149/// use strands::BoxError;
150/// use strands::hooks::{BeforeInvocationEvent, BeforeToolCallEvent, Hook, HookRegistry};
151///
152/// struct Audit;
153///
154/// #[strands::async_trait]
155/// impl<'a> Hook<BeforeInvocationEvent<'a>> for Audit {
156///     async fn handle(&self, event: &mut BeforeInvocationEvent<'a>) -> Result<(), BoxError> {
157///         event.set_cancel("closed for maintenance");
158///         Ok(())
159///     }
160/// }
161///
162/// #[strands::async_trait]
163/// impl Hook<BeforeToolCallEvent> for Audit {
164///     async fn handle(&self, event: &mut BeforeToolCallEvent) -> Result<(), BoxError> {
165///         if event.tool_use().name == "shell" {
166///             return Err("shell is disabled".into());
167///         }
168///         Ok(())
169///     }
170/// }
171///
172/// let hooks = HookRegistry::new();
173/// hooks.add_hook_impl::<BeforeInvocationEvent<'_>>(Audit);
174/// hooks.add_hook_impl::<BeforeToolCallEvent>(Audit);
175/// ```
176#[async_trait]
177pub trait Hook<E: Send>: Send + Sync + 'static {
178    /// Handles the event.
179    ///
180    /// # Errors
181    ///
182    /// Any error fails the invocation; an [`InterruptError`] stops it for human input.
183    async fn handle(&self, event: &mut E) -> std::result::Result<(), BoxError>;
184}
185
186enum Callback<K: HookEvent> {
187    Sync(SyncCallback<K>),
188    Async(AsyncCallback<K>),
189}
190
191impl<K: HookEvent> Clone for Callback<K> {
192    fn clone(&self) -> Self {
193        match self {
194            Self::Sync(callback) => Self::Sync(callback.clone()),
195            Self::Async(callback) => Self::Async(callback.clone()),
196        }
197    }
198}
199
200struct Entry<K: HookEvent> {
201    id: u64,
202    order: i32,
203    callback: Callback<K>,
204}
205
206/// The callbacks registered for one event type.
207#[doc(hidden)]
208pub struct Slot<K: HookEvent> {
209    entries: Arc<RwLock<Vec<Entry<K>>>>,
210}
211
212impl<K: HookEvent> Default for Slot<K> {
213    fn default() -> Self {
214        Self {
215            entries: Arc::default(),
216        }
217    }
218}
219
220impl<K: HookEvent> Slot<K> {
221    fn insert(&self, id: u64, order: i32, callback: Callback<K>) -> HookCleanup {
222        let mut entries = self.entries.write().unwrap_or_else(PoisonError::into_inner);
223        let at = entries
224            .iter()
225            .position(|entry| entry.order > order)
226            .unwrap_or(entries.len());
227        entries.insert(at, Entry { id, order, callback });
228        drop(entries);
229        let weak: Weak<RwLock<Vec<Entry<K>>>> = Arc::downgrade(&self.entries);
230        HookCleanup::new(move || {
231            let Some(entries) = weak.upgrade() else {
232                return;
233            };
234            entries
235                .write()
236                .unwrap_or_else(PoisonError::into_inner)
237                .retain(|entry| entry.id != id);
238        })
239    }
240
241    /// The callbacks in call order, copied out so none run under the lock.
242    fn callbacks(&self) -> Vec<Callback<K>> {
243        let entries = self.entries.read().unwrap_or_else(PoisonError::into_inner);
244        if !K::REVERSE {
245            return entries.iter().map(|entry| entry.callback.clone()).collect();
246        }
247        let mut reversed: Vec<(i32, Callback<K>)> = entries
248            .iter()
249            .rev()
250            .map(|entry| (entry.order, entry.callback.clone()))
251            .collect();
252        reversed.sort_by_key(|(order, _)| *order);
253        reversed.into_iter().map(|(_, callback)| callback).collect()
254    }
255
256    fn len(&self) -> usize {
257        self.entries.read().unwrap_or_else(PoisonError::into_inner).len()
258    }
259
260    #[cfg(test)]
261    fn orders(&self) -> Vec<i32> {
262        let entries = self.entries.read().unwrap_or_else(PoisonError::into_inner);
263        entries.iter().map(|entry| entry.order).collect()
264    }
265}
266
267macro_rules! hook_events {
268    (
269        borrowing { $($borrowing:ident => $borrowing_slot:ident $(, $borrowing_flag:ident)*;)* }
270        owned { $($owned:ident => $owned_slot:ident $(, $owned_flag:ident)*;)* }
271    ) => {
272        /// Registry of hook callbacks, one ordered list per event type (`HookRegistry`).
273        ///
274        /// Callbacks run in ascending `order`; within one order they run in registration order,
275        /// reversed on `After*` events. Registration and removal take a short lock; callbacks
276        /// run outside it, so a callback may register or remove hooks.
277        #[derive(Default)]
278        pub struct HookRegistry {
279            next_id: AtomicU64,
280            $($borrowing_slot: Slot<$borrowing<'static>>,)*
281            $($owned_slot: Slot<$owned>,)*
282        }
283
284        impl HookRegistry {
285            /// The number of callbacks registered across all events.
286            #[must_use]
287            pub fn len(&self) -> usize {
288                0 $(+ self.$borrowing_slot.len())* $(+ self.$owned_slot.len())*
289            }
290        }
291
292        $(
293            impl private::Sealed for $borrowing<'static> {
294                fn slot(registry: &HookRegistry) -> &Slot<Self> {
295                    &registry.$borrowing_slot
296                }
297            }
298
299            impl HookEvent for $borrowing<'static> {
300                type Event<'a> = $borrowing<'a>;
301                $(hook_events!(@flag $borrowing_flag);)*
302            }
303
304            impl<'a> EventKind<'a> for $borrowing<'a> {
305                type Kind = $borrowing<'static>;
306            }
307
308            impl<F, R> IntoSyncHook<$borrowing<'static>> for F
309            where
310                F: for<'a, 'b> Fn(&'b mut $borrowing<'a>) -> R + Send + Sync + 'static,
311                R: HookOutput,
312            {
313                fn into_callback(self, _: private::Token) -> SyncCallback<$borrowing<'static>> {
314                    Arc::new(move |event| self(event).into_hook_result())
315                }
316            }
317
318            impl<H> IntoHookImpl<$borrowing<'static>> for H
319            where
320                H: for<'a> Hook<$borrowing<'a>>,
321            {
322                fn into_callback(self, _: private::Token) -> AsyncCallback<$borrowing<'static>> {
323                    let hook = Arc::new(self);
324                    Arc::new(move |event| {
325                        let hook = hook.clone();
326                        Box::pin(async move { hook.handle(event).await })
327                    })
328                }
329            }
330        )*
331
332        $(
333            impl private::Sealed for $owned {
334                fn slot(registry: &HookRegistry) -> &Slot<Self> {
335                    &registry.$owned_slot
336                }
337            }
338
339            impl HookEvent for $owned {
340                type Event<'a> = $owned;
341                $(hook_events!(@flag $owned_flag);)*
342            }
343
344            impl<'a> EventKind<'a> for $owned {
345                type Kind = $owned;
346            }
347
348            impl<F, R> IntoSyncHook<$owned> for F
349            where
350                F: for<'b> Fn(&'b mut $owned) -> R + Send + Sync + 'static,
351                R: HookOutput,
352            {
353                fn into_callback(self, _: private::Token) -> SyncCallback<$owned> {
354                    Arc::new(move |event| self(event).into_hook_result())
355                }
356            }
357
358            impl<H> IntoHookImpl<$owned> for H
359            where
360                H: Hook<$owned>,
361            {
362                fn into_callback(self, _: private::Token) -> AsyncCallback<$owned> {
363                    let hook = Arc::new(self);
364                    Arc::new(move |event| {
365                        let hook = hook.clone();
366                        Box::pin(async move { hook.handle(event).await })
367                    })
368                }
369            }
370        )*
371    };
372    (@flag reverse) => {
373        const REVERSE: bool = true;
374    };
375    (@flag interruptible) => {
376        fn take_interrupts(event: &mut Self::Event<'_>) -> Vec<Interrupt> {
377            event.take_interrupts()
378        }
379    };
380}
381
382hook_events! {
383    borrowing {
384        InitializedEvent => initialized;
385        BeforeInvocationEvent => before_invocation;
386        AfterInvocationEvent => after_invocation, reverse;
387        MessageAddedEvent => message_added;
388        BeforeModelCallEvent => before_model_call;
389        AfterModelCallEvent => after_model_call, reverse;
390        ModelStreamUpdateEvent => model_stream_update;
391        ContentBlockEvent => content_block;
392        ModelMessageEvent => model_message;
393        BeforeToolsEvent => before_tools, interruptible;
394        AfterToolsEvent => after_tools, reverse;
395        AgentResultEvent => agent_result;
396        InterruptEvent => interrupt;
397    }
398    owned {
399        BeforeToolCallEvent => before_tool_call, interruptible;
400        AfterToolCallEvent => after_tool_call, reverse;
401        ToolStreamUpdateEvent => tool_stream_update;
402        ToolResultEvent => tool_result;
403    }
404}
405
406impl HookRegistry {
407    /// Creates an empty registry.
408    pub fn new() -> Self {
409        Self::default()
410    }
411
412    /// Whether no callbacks are registered.
413    #[must_use]
414    pub fn is_empty(&self) -> bool {
415        self.len() == 0
416    }
417
418    fn insert<K: HookEvent>(&self, order: i32, callback: Callback<K>) -> HookCleanup {
419        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
420        K::slot(self).insert(id, order, callback)
421    }
422
423    /// Registers a plain closure. Annotate the argument so the event type is
424    /// inferred. The closure returns `()` or a `Result` (see [`HookOutput`]).
425    ///
426    /// ```
427    /// use strands::hooks::{BeforeInvocationEvent, BeforeToolCallEvent, HookRegistry};
428    ///
429    /// let registry = HookRegistry::new();
430    /// let cleanup = registry.add_hook(|event: &mut BeforeToolCallEvent| {
431    ///     if event.tool_use().name == "shell" {
432    ///         event.set_cancel("shell is disabled");
433    ///     }
434    /// });
435    /// cleanup.remove();
436    /// registry.add_hook(|event: &mut BeforeInvocationEvent<'_>| -> Result<(), strands::Error> {
437    ///     let limit: Option<u32> = event.agent().app_state().get("limit")?;
438    ///     if limit == Some(0) {
439    ///         event.set_cancel("limit reached");
440    ///     }
441    ///     Ok(())
442    /// });
443    /// ```
444    pub fn add_hook<K: HookEvent>(&self, callback: impl IntoSyncHook<K>) -> HookCleanup {
445        self.add_hook_with(callback, HookCallbackOptions::default())
446    }
447
448    /// Registers a plain closure with options such as the order.
449    pub fn add_hook_with<K: HookEvent>(
450        &self,
451        callback: impl IntoSyncHook<K>,
452        options: HookCallbackOptions,
453    ) -> HookCleanup {
454        self.insert(options.order, Callback::Sync(callback.into_callback(private::Token)))
455    }
456
457    /// Registers a closure that awaits while borrowing the event. Name the event type, and return
458    /// `Box::pin(async move { .. })`; the block's value is `()` or a `Result` (see
459    /// [`HookOutput`]).
460    ///
461    /// ```
462    /// use strands::BoxError;
463    /// use strands::hooks::{BeforeInvocationEvent, BeforeToolCallEvent, HookRegistry};
464    ///
465    /// let registry = HookRegistry::new();
466    /// registry.add_async_hook::<BeforeToolCallEvent>(|event| {
467    ///     Box::pin(async move {
468    ///         tokio::task::yield_now().await;
469    ///         event.set_cancel(true);
470    ///     })
471    /// });
472    /// registry.add_async_hook::<BeforeInvocationEvent<'_>>(|event| {
473    ///     Box::pin(async move {
474    ///         let turns: Option<u32> = event.agent().app_state().get("turns")?;
475    ///         if turns.is_some() {
476    ///             event.agent_mut().messages_mut().clear();
477    ///         }
478    ///         Ok::<(), BoxError>(())
479    ///     })
480    /// });
481    /// ```
482    pub fn add_async_hook<K: HookEvent>(&self, callback: impl IntoAsyncHook<K>) -> HookCleanup {
483        self.add_async_hook_with::<K>(callback, HookCallbackOptions::default())
484    }
485
486    /// Registers an async closure with options such as the order.
487    pub fn add_async_hook_with<K: HookEvent>(
488        &self,
489        callback: impl IntoAsyncHook<K>,
490        options: HookCallbackOptions,
491    ) -> HookCleanup {
492        let callback: AsyncCallback<K> = Arc::new(move |event| {
493            let future = callback(event);
494            Box::pin(async move { future.await.into_hook_result() })
495        });
496        self.insert(options.order, Callback::Async(callback))
497    }
498
499    /// Registers a [`Hook`] implementation.
500    pub fn add_hook_impl<K: HookEvent>(&self, hook: impl IntoHookImpl<K>) -> HookCleanup {
501        self.add_hook_impl_with(hook, HookCallbackOptions::default())
502    }
503
504    /// Registers a [`Hook`] implementation with options such as the order.
505    pub fn add_hook_impl_with<K: HookEvent>(
506        &self,
507        hook: impl IntoHookImpl<K>,
508        options: HookCallbackOptions,
509    ) -> HookCleanup {
510        self.insert(options.order, Callback::Async(hook.into_callback(private::Token)))
511    }
512
513    /// Runs every callback for `event` in order. Interrupts, raised on the
514    /// event or returned as an [`InterruptError`], are collected across callbacks; any other error
515    /// stops at once.
516    ///
517    /// # Errors
518    ///
519    /// The first callback error; [`Error::Interrupt`] with every raised interrupt once all
520    /// callbacks ran; `interrupt_names=<a, b> | duplicate interrupt names` when two raised
521    /// interrupts share a name.
522    /// The orders of the callbacks registered for `K`, in registration-sorted order.
523    #[cfg(test)]
524    pub(crate) fn orders<K: HookEvent>(&self) -> Vec<i32> {
525        K::slot(self).orders()
526    }
527
528    pub(crate) fn invoke<'f, 'a, E: EventKind<'a>>(&'f self, event: &'f mut E) -> BoxFuture<'f, Result<()>>
529    where
530        'a: 'f,
531    {
532        self.invoke_from::<<E as EventKind<'a>>::Kind>(event, 0, None)
533    }
534
535    /// [`invoke`](Self::invoke) that skips the `progress` callbacks that already ran and counts
536    /// each one that finishes, so a run cut short by a dropped stream resumes at the callback it
537    /// interrupted. A callback that fails is not counted. The caller resets `progress` once the
538    /// event is done.
539    pub(crate) fn invoke_tracked<'f, 'a, E: EventKind<'a>>(
540        &'f self,
541        event: &'f mut E,
542        progress: &'f AtomicUsize,
543    ) -> BoxFuture<'f, Result<()>>
544    where
545        'a: 'f,
546    {
547        let start = progress.load(Ordering::SeqCst);
548        self.invoke_from::<<E as EventKind<'a>>::Kind>(event, start, Some(progress))
549    }
550
551    fn invoke_from<'f, 'a, K: HookEvent>(
552        &'f self,
553        event: &'f mut K::Event<'a>,
554        start: usize,
555        progress: Option<&'f AtomicUsize>,
556    ) -> BoxFuture<'f, Result<()>>
557    where
558        'a: 'f,
559    {
560        let callbacks = K::slot(self).callbacks();
561        Box::pin(async move {
562            let mut returned = Vec::new();
563            for (index, callback) in callbacks.into_iter().enumerate().skip(start) {
564                let outcome = match callback {
565                    Callback::Sync(callback) => callback(event),
566                    Callback::Async(callback) => callback(event).await,
567                };
568                let finished = match outcome {
569                    Ok(()) => Ok(()),
570                    Err(error) => match Error::from_boxed(error) {
571                        Error::Interrupt(interrupts) => {
572                            returned.extend(interrupts.into_interrupts());
573                            Ok(())
574                        }
575                        error => Err(error),
576                    },
577                };
578                finished?;
579                if let Some(progress) = progress {
580                    progress.store(index + 1, Ordering::SeqCst);
581                }
582            }
583            let mut interrupts = K::take_interrupts(event);
584            for interrupt in returned {
585                if !interrupts.iter().any(|recorded| recorded.id == interrupt.id) {
586                    interrupts.push(interrupt);
587                }
588            }
589            if interrupts.is_empty() {
590                return Ok(());
591            }
592            check_duplicate_names(&interrupts)?;
593            Err(Error::Interrupt(InterruptError::new(interrupts)))
594        })
595    }
596}
597
598fn check_duplicate_names(interrupts: &[Interrupt]) -> Result<()> {
599    let mut duplicates: Vec<&str> = Vec::new();
600    for (index, interrupt) in interrupts.iter().enumerate() {
601        let repeated = interrupts[..index].iter().any(|earlier| earlier.name == interrupt.name);
602        if repeated && !duplicates.contains(&interrupt.name.as_str()) {
603            duplicates.push(&interrupt.name);
604        }
605    }
606    if duplicates.is_empty() {
607        return Ok(());
608    }
609    Err(Error::other(format!(
610        "interrupt_names=<{}> | duplicate interrupt names",
611        duplicates.join(", ")
612    )))
613}
614
615impl std::fmt::Debug for HookRegistry {
616    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
617        f.debug_struct("HookRegistry").field("len", &self.len()).finish()
618    }
619}
620
621#[cfg(test)]
622mod tests;