1#[path = "hooks/bridge.rs"]
12pub(crate) mod bridge;
13#[path = "hooks/registry.rs"]
14mod registry;
15#[path = "hooks/wave.rs"]
16pub(crate) mod wave;
17
18pub use registry::HookRegistry;
19
20use merry_core::{
21 ErrorInfo, SessionId, SessionUsage, ToolCallArguments, ToolCallId, ToolCallResultStatus,
22 ToolName, ToolOutput,
23};
24use merry_llm::GenerationConfig;
25use serde::{Deserialize, Serialize};
26use std::{collections::BTreeSet, fmt, future::Future, pin::Pin};
27use thiserror::Error;
28use tokio_util::sync::CancellationToken;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum HookPoint {
34 BeforeModelStep,
36 AfterModelStep,
38 BeforeToolCall,
40 AfterToolCall,
42}
43
44impl HookPoint {
45 #[must_use]
47 pub const fn as_str(self) -> &'static str {
48 match self {
49 Self::BeforeModelStep => "before_model_step",
50 Self::AfterModelStep => "after_model_step",
51 Self::BeforeToolCall => "before_tool_call",
52 Self::AfterToolCall => "after_tool_call",
53 }
54 }
55}
56
57impl fmt::Display for HookPoint {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.write_str(self.as_str())
60 }
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
65#[serde(transparent)]
66pub struct HookInvocationId(String);
67
68impl HookInvocationId {
69 pub fn new(value: &str) -> Result<Self, HookError> {
71 if value.trim().is_empty() || value.trim() != value || value.chars().any(char::is_control) {
72 return Err(HookError::InvalidDecision {
73 message: "hook invocation id must be non-blank and free of control characters"
74 .to_owned(),
75 });
76 }
77 Ok(Self(value.to_owned()))
78 }
79
80 pub(crate) fn from_sequence(sequence: u64) -> Self {
81 Self(format!("hook-{sequence}"))
82 }
83
84 #[must_use]
86 pub fn as_str(&self) -> &str {
87 &self.0
88 }
89}
90
91impl fmt::Display for HookInvocationId {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.write_str(&self.0)
94 }
95}
96
97#[derive(Debug, Clone, Default, PartialEq, Eq)]
99pub enum ToolHookFilter {
100 #[default]
102 None,
103 All,
105 Only(BTreeSet<ToolName>),
107}
108
109impl ToolHookFilter {
110 #[must_use]
112 pub fn is_active(&self) -> bool {
113 match self {
114 Self::None => false,
115 Self::All => true,
116 Self::Only(names) => !names.is_empty(),
117 }
118 }
119
120 #[must_use]
122 pub fn matches(&self, tool_name: &ToolName) -> bool {
123 match self {
124 Self::None => false,
125 Self::All => true,
126 Self::Only(names) => names.contains(tool_name),
127 }
128 }
129
130 pub fn union_with(&mut self, other: &Self) {
132 match (&mut *self, other) {
133 (Self::All, _) | (_, Self::None) => {}
134 (_, Self::All) => *self = Self::All,
135 (Self::None, Self::Only(names)) => {
136 if !names.is_empty() {
137 *self = Self::Only(names.clone());
138 }
139 }
140 (Self::Only(existing), Self::Only(names)) => {
141 existing.extend(names.iter().cloned());
142 }
143 }
144 }
145}
146
147#[derive(Debug, Clone, Default, PartialEq, Eq)]
152pub struct HookSubscriptions {
153 before_model_step: bool,
154 after_model_step: bool,
155 before_tool_call: ToolHookFilter,
156 after_tool_call: ToolHookFilter,
157}
158
159impl HookSubscriptions {
160 #[must_use]
162 pub fn none() -> Self {
163 Self::default()
164 }
165
166 #[must_use]
168 pub const fn with_before_model_step(mut self, enabled: bool) -> Self {
169 self.before_model_step = enabled;
170 self
171 }
172
173 #[must_use]
175 pub const fn with_after_model_step(mut self, enabled: bool) -> Self {
176 self.after_model_step = enabled;
177 self
178 }
179
180 #[must_use]
182 pub fn with_before_tool_call(mut self, filter: ToolHookFilter) -> Self {
183 self.before_tool_call = filter;
184 self
185 }
186
187 #[must_use]
189 pub fn with_after_tool_call(mut self, filter: ToolHookFilter) -> Self {
190 self.after_tool_call = filter;
191 self
192 }
193
194 #[must_use]
196 pub fn is_empty(&self) -> bool {
197 !self.before_model_step
198 && !self.after_model_step
199 && !self.before_tool_call.is_active()
200 && !self.after_tool_call.is_active()
201 }
202
203 #[must_use]
205 pub const fn matches_before_model_step(&self) -> bool {
206 self.before_model_step
207 }
208
209 #[must_use]
211 pub const fn matches_after_model_step(&self) -> bool {
212 self.after_model_step
213 }
214
215 #[must_use]
217 pub fn matches_before_tool_call(&self, tool_name: &ToolName) -> bool {
218 self.before_tool_call.matches(tool_name)
219 }
220
221 #[must_use]
223 pub fn matches_after_tool_call(&self, tool_name: &ToolName) -> bool {
224 self.after_tool_call.matches(tool_name)
225 }
226
227 pub fn merge_with(&mut self, other: &Self) {
229 self.before_model_step |= other.before_model_step;
230 self.after_model_step |= other.after_model_step;
231 self.before_tool_call.union_with(&other.before_tool_call);
232 self.after_tool_call.union_with(&other.after_tool_call);
233 }
234}
235
236#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
238pub struct BeforeModelStepContext {
239 pub session_id: SessionId,
241 pub model_turn: usize,
243 pub max_model_turns: usize,
245 pub session_usage: Option<SessionUsage>,
247 pub generation_config: GenerationConfig,
249}
250
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
254pub enum BeforeModelDecision {
255 Continue {
257 #[serde(default)]
259 generation_override: Option<GenerationConfig>,
260 #[serde(default)]
262 dynamic_steering_note: Option<String>,
263 #[serde(default)]
265 force_compact: bool,
266 },
267 StopTurn {
269 reason: String,
271 #[serde(default)]
273 final_output: Option<String>,
274 },
275}
276
277impl BeforeModelDecision {
278 #[must_use]
280 pub fn continue_normally() -> Self {
281 Self::Continue {
282 generation_override: None,
283 dynamic_steering_note: None,
284 force_compact: false,
285 }
286 }
287
288 #[must_use]
290 pub fn stop_turn(reason: impl Into<String>, final_output: Option<String>) -> Self {
291 Self::StopTurn {
292 reason: reason.into(),
293 final_output,
294 }
295 }
296}
297
298#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
300pub struct AfterModelStepContext {
301 pub session_id: SessionId,
303 pub model_turn: usize,
305 pub max_model_turns: usize,
307 pub assistant_text: Option<String>,
309 pub pending_tool_names: Vec<ToolName>,
311 pub is_final_turn: bool,
313 pub session_usage: Option<SessionUsage>,
315}
316
317#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
320pub enum AfterModelDecision {
321 Accept,
323 ContinueWithInput {
325 text: String,
327 },
328 StopTurn {
330 reason: String,
332 #[serde(default)]
334 final_output: Option<String>,
335 },
336}
337
338impl AfterModelDecision {
339 #[must_use]
341 pub const fn accept() -> Self {
342 Self::Accept
343 }
344
345 #[must_use]
347 pub fn continue_with(text: impl Into<String>) -> Self {
348 Self::ContinueWithInput { text: text.into() }
349 }
350
351 #[must_use]
353 pub fn stop_turn(reason: impl Into<String>, final_output: Option<String>) -> Self {
354 Self::StopTurn {
355 reason: reason.into(),
356 final_output,
357 }
358 }
359}
360
361#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
363pub struct BeforeToolCallContext {
364 pub session_id: SessionId,
366 pub model_turn: usize,
368 pub call_id: ToolCallId,
370 pub tool_name: ToolName,
372 pub arguments: ToolCallArguments,
374 pub is_bridge_tool: bool,
376}
377
378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
380#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
381pub enum BeforeToolDecision {
382 Allow,
384 ModifyInput {
386 arguments: ToolCallArguments,
388 },
389 Deny {
391 message: String,
393 },
394 ShortCircuit {
396 output: ToolOutput,
398 },
399 StopTurn {
401 reason: String,
403 #[serde(default)]
405 final_output: Option<String>,
406 },
407}
408
409impl BeforeToolDecision {
410 #[must_use]
412 pub const fn allow() -> Self {
413 Self::Allow
414 }
415
416 #[must_use]
418 pub fn modify_input(arguments: ToolCallArguments) -> Self {
419 Self::ModifyInput { arguments }
420 }
421
422 #[must_use]
424 pub fn deny(message: impl Into<String>) -> Self {
425 Self::Deny {
426 message: message.into(),
427 }
428 }
429
430 #[must_use]
432 pub fn short_circuit(output: ToolOutput) -> Self {
433 Self::ShortCircuit { output }
434 }
435
436 #[must_use]
438 pub fn stop_turn(reason: impl Into<String>, final_output: Option<String>) -> Self {
439 Self::StopTurn {
440 reason: reason.into(),
441 final_output,
442 }
443 }
444}
445
446#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
448pub struct AfterToolCallContext {
449 pub session_id: SessionId,
451 pub model_turn: usize,
453 pub call_id: ToolCallId,
455 pub tool_name: ToolName,
457 pub arguments: ToolCallArguments,
459 pub status: ToolCallResultStatus,
461 pub output: ToolOutput,
463 pub diagnostic: Option<ErrorInfo>,
465 pub is_bridge_tool: bool,
467}
468
469#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
471#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
472pub enum AfterToolDecision {
473 Continue,
475 ModifyOutput {
477 output: ToolOutput,
479 },
480 StopTurn {
482 reason: String,
484 #[serde(default)]
486 final_output: Option<String>,
487 },
488}
489
490impl AfterToolDecision {
491 #[must_use]
493 pub const fn continue_normally() -> Self {
494 Self::Continue
495 }
496
497 #[must_use]
499 pub fn modify_output(output: ToolOutput) -> Self {
500 Self::ModifyOutput { output }
501 }
502
503 #[must_use]
505 pub fn stop_turn(reason: impl Into<String>, final_output: Option<String>) -> Self {
506 Self::StopTurn {
507 reason: reason.into(),
508 final_output,
509 }
510 }
511}
512
513#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
515#[serde(tag = "point", rename_all = "snake_case")]
516pub enum HookRequest {
517 BeforeModelStep(BeforeModelStepContext),
518 AfterModelStep(AfterModelStepContext),
519 BeforeToolCall(BeforeToolCallContext),
520 AfterToolCall(AfterToolCallContext),
521}
522
523impl HookRequest {
524 #[must_use]
526 pub const fn point(&self) -> HookPoint {
527 match self {
528 Self::BeforeModelStep(_) => HookPoint::BeforeModelStep,
529 Self::AfterModelStep(_) => HookPoint::AfterModelStep,
530 Self::BeforeToolCall(_) => HookPoint::BeforeToolCall,
531 Self::AfterToolCall(_) => HookPoint::AfterToolCall,
532 }
533 }
534}
535
536#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
538#[serde(tag = "point", rename_all = "snake_case", deny_unknown_fields)]
539pub enum HookDecision {
540 BeforeModelStep(BeforeModelDecision),
541 AfterModelStep(AfterModelDecision),
542 BeforeToolCall(BeforeToolDecision),
543 AfterToolCall(AfterToolDecision),
544}
545
546impl HookDecision {
547 #[must_use]
549 pub const fn point(&self) -> HookPoint {
550 match self {
551 Self::BeforeModelStep(_) => HookPoint::BeforeModelStep,
552 Self::AfterModelStep(_) => HookPoint::AfterModelStep,
553 Self::BeforeToolCall(_) => HookPoint::BeforeToolCall,
554 Self::AfterToolCall(_) => HookPoint::AfterToolCall,
555 }
556 }
557
558 pub fn sanitize_and_validate(&mut self) -> Result<(), HookError> {
561 match self {
562 Self::BeforeModelStep(decision) => decision.sanitize_and_validate(),
563 Self::AfterModelStep(decision) => decision.sanitize_and_validate(),
564 Self::BeforeToolCall(decision) => decision.sanitize_and_validate(),
565 Self::AfterToolCall(decision) => decision.sanitize_and_validate(),
566 }
567 }
568
569 pub fn validate(&self) -> Result<(), HookError> {
571 match self {
572 Self::BeforeModelStep(BeforeModelDecision::StopTurn { reason, .. })
573 | Self::AfterModelStep(AfterModelDecision::StopTurn { reason, .. })
574 | Self::BeforeToolCall(BeforeToolDecision::StopTurn { reason, .. })
575 | Self::AfterToolCall(AfterToolDecision::StopTurn { reason, .. }) => {
576 validate_nonblank_hook_text("stop_turn reason", reason)
577 }
578 Self::AfterModelStep(AfterModelDecision::ContinueWithInput { text }) => {
579 validate_nonblank_hook_text("continue_with text", text)
580 }
581 Self::BeforeToolCall(BeforeToolDecision::Deny { message }) => {
582 validate_nonblank_hook_text("deny message", message)
583 }
584 Self::BeforeModelStep(BeforeModelDecision::Continue { .. })
585 | Self::AfterModelStep(AfterModelDecision::Accept)
586 | Self::BeforeToolCall(
587 BeforeToolDecision::Allow
588 | BeforeToolDecision::ModifyInput { .. }
589 | BeforeToolDecision::ShortCircuit { .. },
590 )
591 | Self::AfterToolCall(
592 AfterToolDecision::Continue | AfterToolDecision::ModifyOutput { .. },
593 ) => Ok(()),
594 }
595 }
596}
597
598impl BeforeModelDecision {
599 pub(crate) fn sanitize_and_validate(&mut self) -> Result<(), HookError> {
600 match self {
601 Self::Continue {
602 dynamic_steering_note,
603 ..
604 } => {
605 if let Some(note) = dynamic_steering_note.as_mut() {
606 sanitize_hook_text_in_place(note);
607 if note.trim().is_empty() {
608 *dynamic_steering_note = None;
609 }
610 }
611 Ok(())
612 }
613 Self::StopTurn {
614 reason,
615 final_output,
616 } => sanitize_stop_turn(reason, final_output),
617 }
618 }
619}
620
621impl AfterModelDecision {
622 pub(crate) fn sanitize_and_validate(&mut self) -> Result<(), HookError> {
623 match self {
624 Self::Accept => Ok(()),
625 Self::ContinueWithInput { text } => {
626 sanitize_nonblank_hook_text_in_place("continue_with text", text)
627 }
628 Self::StopTurn {
629 reason,
630 final_output,
631 } => sanitize_stop_turn(reason, final_output),
632 }
633 }
634}
635
636impl BeforeToolDecision {
637 pub(crate) fn sanitize_and_validate(&mut self) -> Result<(), HookError> {
638 match self {
639 Self::Allow | Self::ModifyInput { .. } | Self::ShortCircuit { .. } => Ok(()),
640 Self::Deny { message } => sanitize_nonblank_hook_text_in_place("deny message", message),
641 Self::StopTurn {
642 reason,
643 final_output,
644 } => sanitize_stop_turn(reason, final_output),
645 }
646 }
647}
648
649impl AfterToolDecision {
650 pub(crate) fn sanitize_and_validate(&mut self) -> Result<(), HookError> {
651 match self {
652 Self::Continue | Self::ModifyOutput { .. } => Ok(()),
653 Self::StopTurn {
654 reason,
655 final_output,
656 } => sanitize_stop_turn(reason, final_output),
657 }
658 }
659}
660
661fn sanitize_stop_turn(
662 reason: &mut String,
663 final_output: &mut Option<String>,
664) -> Result<(), HookError> {
665 sanitize_nonblank_hook_text_in_place("stop_turn reason", reason)?;
666 if let Some(output) = final_output.as_mut() {
667 sanitize_hook_text_in_place(output);
668 }
669 Ok(())
670}
671
672fn sanitize_hook_text_in_place(value: &mut String) {
673 if let std::borrow::Cow::Owned(cleaned) = crate::user_input::sanitize_freeform_text(value) {
674 *value = cleaned;
675 }
676}
677
678fn sanitize_nonblank_hook_text_in_place(field: &str, value: &mut String) -> Result<(), HookError> {
679 sanitize_hook_text_in_place(value);
680 if value.trim().is_empty() {
681 return Err(HookError::InvalidDecision {
682 message: format!("{field} must not be blank"),
683 });
684 }
685 Ok(())
686}
687
688fn validate_nonblank_hook_text(field: &str, value: &str) -> Result<(), HookError> {
689 let has_visible_content = value
690 .chars()
691 .any(|ch| !ch.is_whitespace() && !crate::user_input::is_stripped_control_char(ch));
692 if !has_visible_content {
693 return Err(HookError::InvalidDecision {
694 message: format!("{field} must not be blank"),
695 });
696 }
697 Ok(())
698}
699
700#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
702pub struct HookInvocation {
703 id: HookInvocationId,
704 request: HookRequest,
705}
706
707impl HookInvocation {
708 #[must_use]
710 pub(crate) fn new(id: HookInvocationId, request: HookRequest) -> Self {
711 Self { id, request }
712 }
713
714 #[must_use]
716 pub fn id(&self) -> &HookInvocationId {
717 &self.id
718 }
719
720 #[must_use]
722 pub fn request(&self) -> &HookRequest {
723 &self.request
724 }
725
726 #[must_use]
728 pub const fn point(&self) -> HookPoint {
729 self.request.point()
730 }
731}
732
733#[derive(Debug, Clone, PartialEq, Eq, Error)]
735pub enum HookError {
736 #[error("hook execution failed: {message}")]
738 Failed { message: String },
739 #[error("hook execution cancelled")]
741 Cancelled,
742 #[error("hook decision point mismatch: expected {expected}, received {actual}")]
744 DecisionTypeMismatch {
745 expected: HookPoint,
746 actual: HookPoint,
747 },
748 #[error("invalid hook decision: {message}")]
750 InvalidDecision { message: String },
751}
752
753pub type HookFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, HookError>> + Send + 'a>>;
755
756pub trait RuntimeHookHandler: Send + Sync {
758 fn subscriptions(&self) -> HookSubscriptions;
760
761 fn before_model_step<'a>(
763 &'a self,
764 _context: BeforeModelStepContext,
765 _cancellation_token: CancellationToken,
766 ) -> HookFuture<'a, BeforeModelDecision> {
767 Box::pin(async { Ok(BeforeModelDecision::continue_normally()) })
768 }
769
770 fn after_model_step<'a>(
772 &'a self,
773 _context: AfterModelStepContext,
774 _cancellation_token: CancellationToken,
775 ) -> HookFuture<'a, AfterModelDecision> {
776 Box::pin(async { Ok(AfterModelDecision::accept()) })
777 }
778
779 fn before_tool_call<'a>(
781 &'a self,
782 _context: BeforeToolCallContext,
783 _cancellation_token: CancellationToken,
784 ) -> HookFuture<'a, BeforeToolDecision> {
785 Box::pin(async { Ok(BeforeToolDecision::allow()) })
786 }
787
788 fn after_tool_call<'a>(
790 &'a self,
791 _context: AfterToolCallContext,
792 _cancellation_token: CancellationToken,
793 ) -> HookFuture<'a, AfterToolDecision> {
794 Box::pin(async { Ok(AfterToolDecision::continue_normally()) })
795 }
796}