1use 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 pub trait Sealed: Sized + 'static {
35 #[doc(hidden)]
36 fn slot(registry: &HookRegistry) -> &Slot<Self>
37 where
38 Self: HookEvent;
39 }
40
41 pub trait SealedOutput {}
43
44 impl SealedOutput for () {}
45 impl<E> SealedOutput for Result<(), E> {}
46
47 #[derive(Debug)]
49 pub struct Token;
50}
51
52pub trait HookEvent: private::Sealed {
58 type Event<'a>: Send;
60
61 #[doc(hidden)]
63 const REVERSE: bool = false;
64
65 #[doc(hidden)]
67 fn take_interrupts(_event: &mut Self::Event<'_>) -> Vec<Interrupt> {
68 Vec::new()
69 }
70}
71
72#[doc(hidden)]
74pub trait EventKind<'a>: Send + Sized {
75 type Kind: HookEvent<Event<'a> = Self>;
77}
78
79pub 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
101pub trait IntoSyncHook<K: HookEvent> {
107 #[doc(hidden)]
108 fn into_callback(self, token: private::Token) -> SyncCallback<K>;
109}
110
111pub 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 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
132pub trait IntoHookImpl<K: HookEvent> {
137 #[doc(hidden)]
138 fn into_callback(self, token: private::Token) -> AsyncCallback<K>;
139}
140
141#[async_trait]
177pub trait Hook<E: Send>: Send + Sync + 'static {
178 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#[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 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 #[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 #[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 ®istry.$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 ®istry.$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 pub fn new() -> Self {
409 Self::default()
410 }
411
412 #[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 pub fn add_hook<K: HookEvent>(&self, callback: impl IntoSyncHook<K>) -> HookCleanup {
445 self.add_hook_with(callback, HookCallbackOptions::default())
446 }
447
448 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 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 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 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 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 #[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 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;