Skip to main content

merry_runtime/hooks/
registry.rs

1//! Composable in-process Rust hook registry with middleware chaining.
2
3use super::{
4    AfterModelDecision, AfterModelStepContext, AfterToolCallContext, AfterToolDecision,
5    BeforeModelDecision, BeforeModelStepContext, BeforeToolCallContext, BeforeToolDecision,
6    HookError, HookFuture, HookSubscriptions, RuntimeHookHandler, ToolHookFilter,
7};
8use merry_core::ToolName;
9use merry_llm::GenerationConfig;
10use std::{collections::BTreeSet, fmt, future::Future, sync::Arc};
11use tokio_util::sync::CancellationToken;
12
13type BeforeModelHookFn = Arc<
14    dyn Fn(BeforeModelStepContext, CancellationToken) -> HookFuture<'static, BeforeModelDecision>
15        + Send
16        + Sync,
17>;
18type AfterModelHookFn = Arc<
19    dyn Fn(AfterModelStepContext, CancellationToken) -> HookFuture<'static, AfterModelDecision>
20        + Send
21        + Sync,
22>;
23type BeforeToolHookFn = Arc<
24    dyn Fn(BeforeToolCallContext, CancellationToken) -> HookFuture<'static, BeforeToolDecision>
25        + Send
26        + Sync,
27>;
28type AfterToolHookFn = Arc<
29    dyn Fn(AfterToolCallContext, CancellationToken) -> HookFuture<'static, AfterToolDecision>
30        + Send
31        + Sync,
32>;
33
34#[derive(Clone)]
35struct FilteredToolHook<F> {
36    filter: ToolHookFilter,
37    callback: F,
38}
39
40/// Composable in-process Rust hook registry with middleware chaining and short-circuiting.
41#[derive(Clone, Default)]
42pub struct HookRegistry {
43    before_model: Vec<BeforeModelHookFn>,
44    after_model: Vec<AfterModelHookFn>,
45    before_tool: Vec<FilteredToolHook<BeforeToolHookFn>>,
46    after_tool: Vec<FilteredToolHook<AfterToolHookFn>>,
47}
48
49impl fmt::Debug for HookRegistry {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        f.debug_struct("HookRegistry")
52            .field("before_model_count", &self.before_model.len())
53            .field("after_model_count", &self.after_model.len())
54            .field("before_tool_count", &self.before_tool.len())
55            .field("after_tool_count", &self.after_tool.len())
56            .finish()
57    }
58}
59
60impl HookRegistry {
61    /// Creates an empty hook registry.
62    #[must_use]
63    pub fn new() -> Self {
64        Self::default()
65    }
66
67    /// Returns whether no hooks are registered.
68    #[must_use]
69    pub fn is_empty(&self) -> bool {
70        self.before_model.is_empty()
71            && self.after_model.is_empty()
72            && self.before_tool.is_empty()
73            && self.after_tool.is_empty()
74    }
75
76    /// Registers a `before_model_step` async hook.
77    #[must_use]
78    pub fn before_model_step<F, Fut>(mut self, callback: F) -> Self
79    where
80        F: Fn(BeforeModelStepContext) -> Fut + Send + Sync + 'static,
81        Fut: Future<Output = BeforeModelDecision> + Send + 'static,
82    {
83        self.before_model.push(Arc::new(move |ctx, _token| {
84            let fut = callback(ctx);
85            Box::pin(async move { Ok(fut.await) })
86        }));
87        self
88    }
89
90    /// Registers an `after_model_step` async hook.
91    #[must_use]
92    pub fn after_model_step<F, Fut>(mut self, callback: F) -> Self
93    where
94        F: Fn(AfterModelStepContext) -> Fut + Send + Sync + 'static,
95        Fut: Future<Output = AfterModelDecision> + Send + 'static,
96    {
97        self.after_model.push(Arc::new(move |ctx, _token| {
98            let fut = callback(ctx);
99            Box::pin(async move { Ok(fut.await) })
100        }));
101        self
102    }
103
104    /// Registers a `before_tool_call` async hook matching all tools.
105    #[must_use]
106    pub fn before_tool_call<F, Fut>(mut self, callback: F) -> Self
107    where
108        F: Fn(BeforeToolCallContext) -> Fut + Send + Sync + 'static,
109        Fut: Future<Output = BeforeToolDecision> + Send + 'static,
110    {
111        self.before_tool.push(FilteredToolHook {
112            filter: ToolHookFilter::All,
113            callback: Arc::new(move |ctx, _token| {
114                let fut = callback(ctx);
115                Box::pin(async move { Ok(fut.await) })
116            }),
117        });
118        self
119    }
120
121    /// Registers a `before_tool_call` async hook matching only `tools`.
122    #[must_use]
123    pub fn before_tool_call_for<I, F, Fut>(mut self, tools: I, callback: F) -> Self
124    where
125        I: IntoIterator<Item = ToolName>,
126        F: Fn(BeforeToolCallContext) -> Fut + Send + Sync + 'static,
127        Fut: Future<Output = BeforeToolDecision> + Send + 'static,
128    {
129        let set: BTreeSet<ToolName> = tools.into_iter().collect();
130        self.before_tool.push(FilteredToolHook {
131            filter: if set.is_empty() {
132                ToolHookFilter::None
133            } else {
134                ToolHookFilter::Only(set)
135            },
136            callback: Arc::new(move |ctx, _token| {
137                let fut = callback(ctx);
138                Box::pin(async move { Ok(fut.await) })
139            }),
140        });
141        self
142    }
143
144    /// Registers an `after_tool_call` async hook matching all tools.
145    #[must_use]
146    pub fn after_tool_call<F, Fut>(mut self, callback: F) -> Self
147    where
148        F: Fn(AfterToolCallContext) -> Fut + Send + Sync + 'static,
149        Fut: Future<Output = AfterToolDecision> + Send + 'static,
150    {
151        self.after_tool.push(FilteredToolHook {
152            filter: ToolHookFilter::All,
153            callback: Arc::new(move |ctx, _token| {
154                let fut = callback(ctx);
155                Box::pin(async move { Ok(fut.await) })
156            }),
157        });
158        self
159    }
160
161    /// Registers an `after_tool_call` async hook matching only `tools`.
162    #[must_use]
163    pub fn after_tool_call_for<I, F, Fut>(mut self, tools: I, callback: F) -> Self
164    where
165        I: IntoIterator<Item = ToolName>,
166        F: Fn(AfterToolCallContext) -> Fut + Send + Sync + 'static,
167        Fut: Future<Output = AfterToolDecision> + Send + 'static,
168    {
169        let set: BTreeSet<ToolName> = tools.into_iter().collect();
170        self.after_tool.push(FilteredToolHook {
171            filter: if set.is_empty() {
172                ToolHookFilter::None
173            } else {
174                ToolHookFilter::Only(set)
175            },
176            callback: Arc::new(move |ctx, _token| {
177                let fut = callback(ctx);
178                Box::pin(async move { Ok(fut.await) })
179            }),
180        });
181        self
182    }
183}
184
185impl RuntimeHookHandler for HookRegistry {
186    fn subscriptions(&self) -> HookSubscriptions {
187        let mut before_tool = ToolHookFilter::None;
188        for entry in &self.before_tool {
189            before_tool.union_with(&entry.filter);
190        }
191        let mut after_tool = ToolHookFilter::None;
192        for entry in &self.after_tool {
193            after_tool.union_with(&entry.filter);
194        }
195        HookSubscriptions::none()
196            .with_before_model_step(!self.before_model.is_empty())
197            .with_after_model_step(!self.after_model.is_empty())
198            .with_before_tool_call(before_tool)
199            .with_after_tool_call(after_tool)
200    }
201
202    fn before_model_step<'a>(
203        &'a self,
204        context: BeforeModelStepContext,
205        cancellation_token: CancellationToken,
206    ) -> HookFuture<'a, BeforeModelDecision> {
207        Box::pin(async move {
208            let mut merged_generation: Option<GenerationConfig> = None;
209            let mut notes: Vec<String> = Vec::new();
210            let mut force_compact = false;
211            let mut current = Some(context);
212            let total = self.before_model.len();
213
214            for (idx, hook) in self.before_model.iter().enumerate() {
215                if cancellation_token.is_cancelled() {
216                    return Err(HookError::Cancelled);
217                }
218                let is_last = idx + 1 == total;
219                let Some(hook_ctx) = (if is_last {
220                    current.take()
221                } else {
222                    current.clone()
223                }) else {
224                    break;
225                };
226                let mut decision = tokio::select! {
227                    biased;
228                    () = cancellation_token.cancelled() => return Err(HookError::Cancelled),
229                    result = hook(hook_ctx, cancellation_token.clone()) => result?,
230                };
231                decision.sanitize_and_validate()?;
232                match decision {
233                    BeforeModelDecision::Continue {
234                        generation_override,
235                        dynamic_steering_note,
236                        force_compact: compact,
237                    } => {
238                        if let Some(generation_cfg) = generation_override {
239                            if let Some(ctx) = current.as_mut() {
240                                ctx.generation_config = generation_cfg.clone();
241                            }
242                            merged_generation = Some(generation_cfg);
243                        }
244                        if let Some(note) = dynamic_steering_note {
245                            notes.push(note);
246                        }
247                        force_compact |= compact;
248                    }
249                    stop @ BeforeModelDecision::StopTurn { .. } => return Ok(stop),
250                }
251            }
252
253            Ok(BeforeModelDecision::Continue {
254                generation_override: merged_generation,
255                dynamic_steering_note: (!notes.is_empty()).then(|| notes.join("\n\n")),
256                force_compact,
257            })
258        })
259    }
260
261    fn after_model_step<'a>(
262        &'a self,
263        context: AfterModelStepContext,
264        cancellation_token: CancellationToken,
265    ) -> HookFuture<'a, AfterModelDecision> {
266        Box::pin(async move {
267            let mut current = Some(context);
268            let total = self.after_model.len();
269
270            for (idx, hook) in self.after_model.iter().enumerate() {
271                if cancellation_token.is_cancelled() {
272                    return Err(HookError::Cancelled);
273                }
274                let is_last = idx + 1 == total;
275                let Some(hook_ctx) = (if is_last {
276                    current.take()
277                } else {
278                    current.clone()
279                }) else {
280                    break;
281                };
282                let mut decision = tokio::select! {
283                    biased;
284                    () = cancellation_token.cancelled() => return Err(HookError::Cancelled),
285                    result = hook(hook_ctx, cancellation_token.clone()) => result?,
286                };
287                decision.sanitize_and_validate()?;
288                match decision {
289                    AfterModelDecision::Accept => {}
290                    short_circuit => return Ok(short_circuit),
291                }
292            }
293            Ok(AfterModelDecision::Accept)
294        })
295    }
296
297    fn before_tool_call<'a>(
298        &'a self,
299        mut context: BeforeToolCallContext,
300        cancellation_token: CancellationToken,
301    ) -> HookFuture<'a, BeforeToolDecision> {
302        Box::pin(async move {
303            let matching: Vec<&BeforeToolHookFn> = self
304                .before_tool
305                .iter()
306                .filter(|entry| entry.filter.matches(&context.tool_name))
307                .map(|entry| &entry.callback)
308                .collect();
309            let mut modified = false;
310            let total = matching.len();
311
312            for (idx, hook) in matching.into_iter().enumerate() {
313                if cancellation_token.is_cancelled() {
314                    return Err(HookError::Cancelled);
315                }
316                let is_last = idx + 1 == total;
317                if is_last {
318                    let saved_args = modified.then(|| context.arguments.clone());
319                    let mut decision = tokio::select! {
320                        biased;
321                        () = cancellation_token.cancelled() => return Err(HookError::Cancelled),
322                        result = hook(context, cancellation_token.clone()) => result?,
323                    };
324                    decision.sanitize_and_validate()?;
325                    return Ok(match decision {
326                        BeforeToolDecision::Allow => match saved_args {
327                            Some(arguments) => BeforeToolDecision::ModifyInput { arguments },
328                            None => BeforeToolDecision::Allow,
329                        },
330                        other => other,
331                    });
332                }
333
334                let mut decision = tokio::select! {
335                    biased;
336                    () = cancellation_token.cancelled() => return Err(HookError::Cancelled),
337                    result = hook(context.clone(), cancellation_token.clone()) => result?,
338                };
339                decision.sanitize_and_validate()?;
340                match decision {
341                    BeforeToolDecision::Allow => {}
342                    BeforeToolDecision::ModifyInput { arguments } => {
343                        context.arguments = arguments;
344                        modified = true;
345                    }
346                    short_circuit => return Ok(short_circuit),
347                }
348            }
349            Ok(BeforeToolDecision::Allow)
350        })
351    }
352
353    fn after_tool_call<'a>(
354        &'a self,
355        mut context: AfterToolCallContext,
356        cancellation_token: CancellationToken,
357    ) -> HookFuture<'a, AfterToolDecision> {
358        Box::pin(async move {
359            let matching: Vec<&AfterToolHookFn> = self
360                .after_tool
361                .iter()
362                .filter(|entry| entry.filter.matches(&context.tool_name))
363                .map(|entry| &entry.callback)
364                .collect();
365            let mut modified = false;
366            let total = matching.len();
367
368            for (idx, hook) in matching.into_iter().enumerate() {
369                if cancellation_token.is_cancelled() {
370                    return Err(HookError::Cancelled);
371                }
372                let is_last = idx + 1 == total;
373                if is_last {
374                    let saved_output = modified.then(|| context.output.clone());
375                    let mut decision = tokio::select! {
376                        biased;
377                        () = cancellation_token.cancelled() => return Err(HookError::Cancelled),
378                        result = hook(context, cancellation_token.clone()) => result?,
379                    };
380                    decision.sanitize_and_validate()?;
381                    return Ok(match decision {
382                        AfterToolDecision::Continue => match saved_output {
383                            Some(output) => AfterToolDecision::ModifyOutput { output },
384                            None => AfterToolDecision::Continue,
385                        },
386                        other => other,
387                    });
388                }
389
390                let mut decision = tokio::select! {
391                    biased;
392                    () = cancellation_token.cancelled() => return Err(HookError::Cancelled),
393                    result = hook(context.clone(), cancellation_token.clone()) => result?,
394                };
395                decision.sanitize_and_validate()?;
396                match decision {
397                    AfterToolDecision::Continue => {}
398                    AfterToolDecision::ModifyOutput { output } => {
399                        context.output = output;
400                        modified = true;
401                    }
402                    stop @ AfterToolDecision::StopTurn { .. } => return Ok(stop),
403                }
404            }
405            Ok(AfterToolDecision::Continue)
406        })
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413    use crate::hooks::HookDecision;
414
415    #[test]
416    fn hook_subscriptions_merge_combines_points_and_tool_filters() {
417        let alpha = ToolName::new("alpha").expect("valid tool name");
418        let beta = ToolName::new("beta").expect("valid tool name");
419        let gamma = ToolName::new("gamma").expect("valid tool name");
420
421        let mut left = HookSubscriptions::none()
422            .with_before_model_step(true)
423            .with_before_tool_call(ToolHookFilter::Only(BTreeSet::from([alpha.clone()])));
424        let right = HookSubscriptions::none()
425            .with_after_model_step(true)
426            .with_before_tool_call(ToolHookFilter::Only(BTreeSet::from([beta.clone()])))
427            .with_after_tool_call(ToolHookFilter::All);
428
429        left.merge_with(&right);
430
431        assert!(left.matches_before_model_step());
432        assert!(left.matches_after_model_step());
433        assert!(left.matches_before_tool_call(&alpha));
434        assert!(left.matches_before_tool_call(&beta));
435        assert!(!left.matches_before_tool_call(&gamma));
436        assert!(left.matches_after_tool_call(&gamma));
437    }
438
439    #[test]
440    fn hook_decision_validation_rejects_blank_required_fields() {
441        assert!(
442            HookDecision::BeforeModelStep(BeforeModelDecision::stop_turn("   ", None))
443                .validate()
444                .is_err()
445        );
446        assert!(
447            HookDecision::AfterModelStep(AfterModelDecision::continue_with(" \t "))
448                .validate()
449                .is_err()
450        );
451        assert!(
452            HookDecision::BeforeToolCall(BeforeToolDecision::deny(""))
453                .validate()
454                .is_err()
455        );
456        assert!(
457            HookDecision::AfterToolCall(AfterToolDecision::stop_turn("\0\x07", None))
458                .validate()
459                .is_err()
460        );
461        let mut dirty =
462            HookDecision::AfterToolCall(AfterToolDecision::stop_turn("dirty\0\x07reason", None));
463        dirty
464            .sanitize_and_validate()
465            .expect("dirty hook reason should sanitize cleanly");
466        assert_eq!(
467            dirty,
468            HookDecision::AfterToolCall(AfterToolDecision::stop_turn("dirtyreason", None))
469        );
470        assert!(
471            HookDecision::AfterModelStep(AfterModelDecision::continue_with("refine answer"))
472                .validate()
473                .is_ok()
474        );
475    }
476
477    #[tokio::test]
478    async fn native_hook_registry_sanitizes_dirty_decisions_across_points() {
479        let registry = HookRegistry::new()
480            .before_model_step(|_ctx| async {
481                BeforeModelDecision::stop_turn(
482                    "stop\x07\r\nreason\0",
483                    Some("final\x07\r\noutput\0".to_owned()),
484                )
485            })
486            .after_model_step(|_ctx| async {
487                AfterModelDecision::continue_with("keep\x07\r\ngoing\0")
488            });
489
490        let session_id = merry_core::SessionId::new("hook-sanitize").expect("valid session id");
491        let before = RuntimeHookHandler::before_model_step(
492            &registry,
493            BeforeModelStepContext {
494                session_id: session_id.clone(),
495                model_turn: 1,
496                max_model_turns: 4,
497                session_usage: None,
498                generation_config: merry_llm::GenerationConfig::default(),
499            },
500            CancellationToken::new(),
501        )
502        .await
503        .expect("before hook should sanitize");
504        assert_eq!(
505            before,
506            BeforeModelDecision::stop_turn("stop\nreason", Some("final\noutput".to_owned()))
507        );
508
509        let after = RuntimeHookHandler::after_model_step(
510            &registry,
511            AfterModelStepContext {
512                session_id,
513                model_turn: 1,
514                max_model_turns: 4,
515                assistant_text: None,
516                pending_tool_names: Vec::new(),
517                is_final_turn: true,
518                session_usage: None,
519            },
520            CancellationToken::new(),
521        )
522        .await
523        .expect("after hook should sanitize");
524        assert_eq!(after, AfterModelDecision::continue_with("keep\ngoing"));
525    }
526}