strands/hooks/types.rs
1//! Hook registration options and handles.
2
3use std::fmt;
4use std::sync::Arc;
5
6/// Presets for hook execution order (`HookOrder`). Lower values run first.
7///
8/// Any `i32` is a valid order; the presets are reference points. [`SDK_FIRST`](Self::SDK_FIRST)
9/// and [`SDK_LAST`](Self::SDK_LAST) mark where the SDK's own hooks run, so hooks can be placed
10/// around them: `HookOrder::SDK_FIRST - 1` runs before the SDK's earliest hooks.
11#[derive(Debug)]
12#[non_exhaustive]
13pub enum HookOrder {}
14
15impl HookOrder {
16 /// Where the SDK's earliest hooks run.
17 pub const SDK_FIRST: i32 = -100;
18 /// Where output interventions run.
19 pub const INTERVENTION_OUTPUT: i32 = -90;
20 /// The order of hooks registered without options.
21 pub const DEFAULT: i32 = 0;
22 /// Where model routing runs.
23 pub const MODEL_ROUTING: i32 = 50;
24 /// Where input interventions run.
25 pub const INTERVENTION_INPUT: i32 = 90;
26 /// Where the SDK's latest hooks run.
27 pub const SDK_LAST: i32 = 100;
28}
29
30/// Options for registering a hook (`HookCallbackOptions`).
31///
32/// ```
33/// use strands::hooks::{HookCallbackOptions, HookOrder};
34///
35/// let options = HookCallbackOptions { order: HookOrder::SDK_FIRST - 1 };
36/// assert_eq!(HookCallbackOptions::default().order, HookOrder::DEFAULT);
37/// # let _ = options;
38/// ```
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bon::Builder)]
40pub struct HookCallbackOptions {
41 /// Execution order; lower runs first. Defaults to [`HookOrder::DEFAULT`].
42 #[builder(default)]
43 pub order: i32,
44}
45
46/// Removes a registered hook (`HookCleanup`).
47///
48/// [`remove`](Self::remove) is idempotent and does not affect other registrations, including other
49/// registrations of the same callback. Dropping the handle keeps the hook registered.
50#[derive(Clone)]
51pub struct HookCleanup {
52 remove: Arc<dyn Fn() + Send + Sync>,
53}
54
55impl HookCleanup {
56 pub(crate) fn new(remove: impl Fn() + Send + Sync + 'static) -> Self {
57 Self {
58 remove: Arc::new(remove),
59 }
60 }
61
62 /// Unregisters the hook. Calling it again does nothing.
63 pub fn remove(&self) {
64 (self.remove)();
65 }
66}
67
68impl fmt::Debug for HookCleanup {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 f.debug_struct("HookCleanup").finish_non_exhaustive()
71 }
72}