Skip to main content

merry_runtime/
hooks.rs

1//! Runtime-owned lifecycle hooks and turn-control policy contracts.
2//!
3//! Hooks let Rust applications and foreign-language SDK hosts intercept model
4//! steps and tool executions with typed decisions (`Allow`, `ModifyInput`,
5//! `ModifyOutput`, `Deny`, `ShortCircuit`, `ContinueWithInput`, `StopTurn`).
6//!
7//! Unsubscribed hook points and non-matching tool filters incur zero channel
8//! traffic and zero event emission: the runtime evaluates hooks only when an
9//! installed handler or explicit bridge subscription matches the current point.
10
11#[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/// Lifecycle boundary where a runtime hook can intercept execution.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum HookPoint {
34    /// Before compiling and sending a model request for the next turn.
35    BeforeModelStep,
36    /// After a model step finishes, before tool execution or turn completion.
37    AfterModelStep,
38    /// After tool arguments are received, before executing a tool call.
39    BeforeToolCall,
40    /// After a tool call executes, before committing its durable result.
41    AfterToolCall,
42}
43
44impl HookPoint {
45    /// Returns the stable snake_case protocol label for this hook point.
46    #[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/// Runtime-assigned identifier for one host-bridged hook invocation.
64#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
65#[serde(transparent)]
66pub struct HookInvocationId(String);
67
68impl HookInvocationId {
69    /// Creates a validated hook invocation identifier.
70    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    /// Borrows the identifier text.
85    #[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/// Filter selecting which tools trigger a tool-level hook point.
98#[derive(Debug, Clone, Default, PartialEq, Eq)]
99pub enum ToolHookFilter {
100    /// No tools are subscribed; the hook point is skipped with zero overhead.
101    #[default]
102    None,
103    /// Every tool call triggers the hook point.
104    All,
105    /// Only tool calls whose name appears in this set trigger the hook point.
106    Only(BTreeSet<ToolName>),
107}
108
109impl ToolHookFilter {
110    /// Returns whether the filter subscribes to at least one tool.
111    #[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    /// Returns whether `tool_name` matches this filter.
121    #[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    /// Merges another filter into this filter using set union semantics.
131    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/// Declarative set of hook points and tool filters active for a handler or bridge.
148///
149/// The runtime checks subscriptions before building hook contexts or emitting
150/// host-bridge invocations, so unregistered hooks add zero runtime traffic.
151#[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    /// Creates an empty subscription set with all hook points disabled.
161    #[must_use]
162    pub fn none() -> Self {
163        Self::default()
164    }
165
166    /// Enables or disables `before_model_step` hook dispatch.
167    #[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    /// Enables or disables `after_model_step` hook dispatch.
174    #[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    /// Sets the tool filter for `before_tool_call` hook dispatch.
181    #[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    /// Sets the tool filter for `after_tool_call` hook dispatch.
188    #[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    /// Returns whether no hook points are subscribed.
195    #[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    /// Returns whether `before_model_step` is subscribed.
204    #[must_use]
205    pub const fn matches_before_model_step(&self) -> bool {
206        self.before_model_step
207    }
208
209    /// Returns whether `after_model_step` is subscribed.
210    #[must_use]
211    pub const fn matches_after_model_step(&self) -> bool {
212        self.after_model_step
213    }
214
215    /// Returns whether `before_tool_call` is subscribed for `tool_name`.
216    #[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    /// Returns whether `after_tool_call` is subscribed for `tool_name`.
222    #[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    /// Merges `other` into `self` for composite [`RuntimeHookHandler`] implementations.
228    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/// Read-only context supplied to a `before_model_step` hook.
237#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
238pub struct BeforeModelStepContext {
239    /// Owning session identity.
240    pub session_id: SessionId,
241    /// One-based model turn index about to execute in this run/burst.
242    pub model_turn: usize,
243    /// Configured turn budget for the current loop.
244    pub max_model_turns: usize,
245    /// Latest recorded session usage snapshot, when available.
246    pub session_usage: Option<SessionUsage>,
247    /// Active generation controls that will be sent unless overridden.
248    pub generation_config: GenerationConfig,
249}
250
251/// Decision returned by a `before_model_step` hook.
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
254pub enum BeforeModelDecision {
255    /// Proceed with the model step, with optional per-step dynamic overrides.
256    Continue {
257        /// Optional replacement generation controls for this single model step.
258        #[serde(default)]
259        generation_override: Option<GenerationConfig>,
260        /// Optional dynamic steering note appended after the cached prefix.
261        #[serde(default)]
262        dynamic_steering_note: Option<String>,
263        /// Requests a best-effort compaction pass before sending this step.
264        #[serde(default)]
265        force_compact: bool,
266    },
267    /// Stop the current turn cleanly without calling the model provider.
268    StopTurn {
269        /// Actionable human-readable reason recorded in loop status.
270        reason: String,
271        /// Optional explicit final text returned to the caller.
272        #[serde(default)]
273        final_output: Option<String>,
274    },
275}
276
277impl BeforeModelDecision {
278    /// Proceeds with no modifications.
279    #[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    /// Stops the current turn before calling the model.
289    #[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/// Read-only context supplied to an `after_model_step` hook.
299#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
300pub struct AfterModelStepContext {
301    /// Owning session identity.
302    pub session_id: SessionId,
303    /// One-based model turn index that just finished.
304    pub model_turn: usize,
305    /// Configured turn budget for the current loop.
306    pub max_model_turns: usize,
307    /// Assistant text produced during this step, when present.
308    pub assistant_text: Option<String>,
309    /// Ordered tool names requested by the model in this step (empty if final).
310    pub pending_tool_names: Vec<ToolName>,
311    /// Whether the model completed without requesting further tool calls.
312    pub is_final_turn: bool,
313    /// Latest recorded session usage snapshot, when available.
314    pub session_usage: Option<SessionUsage>,
315}
316
317/// Decision returned by an `after_model_step` hook.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
320pub enum AfterModelDecision {
321    /// Accept the model step outcome and follow default runtime control flow.
322    Accept,
323    /// Continue the loop with a dynamic control note even when the model wanted to stop.
324    ContinueWithInput {
325        /// Non-blank feedback text delivered as a dynamic loop-control message.
326        text: String,
327    },
328    /// Stop the current turn cleanly (settling any pending tool calls first).
329    StopTurn {
330        /// Actionable human-readable reason recorded in loop status.
331        reason: String,
332        /// Optional explicit final output overriding the model's step text.
333        #[serde(default)]
334        final_output: Option<String>,
335    },
336}
337
338impl AfterModelDecision {
339    /// Accepts default runtime control flow.
340    #[must_use]
341    pub const fn accept() -> Self {
342        Self::Accept
343    }
344
345    /// Forces another model turn with feedback text.
346    #[must_use]
347    pub fn continue_with(text: impl Into<String>) -> Self {
348        Self::ContinueWithInput { text: text.into() }
349    }
350
351    /// Stops the current turn cleanly.
352    #[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/// Read-only context supplied to a `before_tool_call` hook.
362#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
363pub struct BeforeToolCallContext {
364    /// Owning session identity.
365    pub session_id: SessionId,
366    /// One-based model turn index that produced this tool call.
367    pub model_turn: usize,
368    /// Model-assigned tool call identifier.
369    pub call_id: ToolCallId,
370    /// Tool name requested by the model.
371    pub tool_name: ToolName,
372    /// JSON object arguments for this tool call.
373    pub arguments: ToolCallArguments,
374    /// Whether this tool executes on the host bridge rather than inside Rust runtime.
375    pub is_bridge_tool: bool,
376}
377
378/// Decision returned by a `before_tool_call` hook.
379#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
380#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
381pub enum BeforeToolDecision {
382    /// Proceed with the tool call unchanged.
383    Allow,
384    /// Replace the tool call arguments before execution (re-validated against schema).
385    ModifyInput {
386        /// Replacement JSON object arguments.
387        arguments: ToolCallArguments,
388    },
389    /// Skip execution and record a failed tool result so the model can recover.
390    Deny {
391        /// Denial message surfaced to the model as a failed tool result.
392        message: String,
393    },
394    /// Skip execution and record a synthetic succeeded tool output.
395    ShortCircuit {
396        /// Synthetic tool output recorded as the call's durable result.
397        output: ToolOutput,
398    },
399    /// Skip this call and all remaining calls in the batch, settling them cleanly and stopping the turn.
400    StopTurn {
401        /// Actionable human-readable reason recorded in loop status.
402        reason: String,
403        /// Optional explicit final text returned to the caller.
404        #[serde(default)]
405        final_output: Option<String>,
406    },
407}
408
409impl BeforeToolDecision {
410    /// Allows the tool call to proceed unchanged.
411    #[must_use]
412    pub const fn allow() -> Self {
413        Self::Allow
414    }
415
416    /// Replaces tool call arguments before execution.
417    #[must_use]
418    pub fn modify_input(arguments: ToolCallArguments) -> Self {
419        Self::ModifyInput { arguments }
420    }
421
422    /// Denies the tool call and returns `message` to the model.
423    #[must_use]
424    pub fn deny(message: impl Into<String>) -> Self {
425        Self::Deny {
426            message: message.into(),
427        }
428    }
429
430    /// Skips execution and returns `output` as a succeeded tool result.
431    #[must_use]
432    pub fn short_circuit(output: ToolOutput) -> Self {
433        Self::ShortCircuit { output }
434    }
435
436    /// Stops the current turn cleanly without executing the tool.
437    #[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/// Read-only context supplied to an `after_tool_call` hook.
447#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
448pub struct AfterToolCallContext {
449    /// Owning session identity.
450    pub session_id: SessionId,
451    /// One-based model turn index that produced this tool call.
452    pub model_turn: usize,
453    /// Model-assigned tool call identifier.
454    pub call_id: ToolCallId,
455    /// Tool name that executed.
456    pub tool_name: ToolName,
457    /// Effective JSON object arguments used for execution.
458    pub arguments: ToolCallArguments,
459    /// Execution result status.
460    pub status: ToolCallResultStatus,
461    /// Output produced by the tool.
462    pub output: ToolOutput,
463    /// Optional structured diagnostic when status is failed.
464    pub diagnostic: Option<ErrorInfo>,
465    /// Whether this tool executed on the host bridge.
466    pub is_bridge_tool: bool,
467}
468
469/// Decision returned by an `after_tool_call` hook.
470#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
471#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
472pub enum AfterToolDecision {
473    /// Keep the recorded tool result unchanged and continue the turn.
474    Continue,
475    /// Replace the tool output before committing it to the durable session transcript.
476    ModifyOutput {
477        /// Replacement tool output.
478        output: ToolOutput,
479    },
480    /// Commit this tool result, settle any remaining pending calls cleanly, and stop the turn.
481    StopTurn {
482        /// Actionable human-readable reason recorded in loop status.
483        reason: String,
484        /// Optional explicit final text returned to the caller.
485        #[serde(default)]
486        final_output: Option<String>,
487    },
488}
489
490impl AfterToolDecision {
491    /// Keeps the tool output unchanged.
492    #[must_use]
493    pub const fn continue_normally() -> Self {
494        Self::Continue
495    }
496
497    /// Replaces the tool output before durable commit.
498    #[must_use]
499    pub fn modify_output(output: ToolOutput) -> Self {
500        Self::ModifyOutput { output }
501    }
502
503    /// Stops the current turn cleanly after committing this tool result.
504    #[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/// Typed hook request payload sent over the host bridge when subscribed.
514#[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    /// Returns the lifecycle point corresponding to this request.
525    #[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/// Typed hook decision returned over the host bridge.
537#[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    /// Returns the lifecycle point corresponding to this decision.
548    #[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    /// Sanitizes freeform decision text in place and validates non-blank
559    /// invariants for decisions crossing external boundaries.
560    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    /// Validates non-blank text invariants for decisions crossing external boundaries.
570    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/// One pending host-bridged hook invocation awaiting a decision.
701#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
702pub struct HookInvocation {
703    id: HookInvocationId,
704    request: HookRequest,
705}
706
707impl HookInvocation {
708    /// Creates a new hook invocation envelope.
709    #[must_use]
710    pub(crate) fn new(id: HookInvocationId, request: HookRequest) -> Self {
711        Self { id, request }
712    }
713
714    /// Returns the runtime-assigned invocation identifier.
715    #[must_use]
716    pub fn id(&self) -> &HookInvocationId {
717        &self.id
718    }
719
720    /// Returns the typed hook request payload.
721    #[must_use]
722    pub fn request(&self) -> &HookRequest {
723        &self.request
724    }
725
726    /// Returns the lifecycle point of this invocation.
727    #[must_use]
728    pub const fn point(&self) -> HookPoint {
729        self.request.point()
730    }
731}
732
733/// Errors produced by hook execution or invalid hook decisions.
734#[derive(Debug, Clone, PartialEq, Eq, Error)]
735pub enum HookError {
736    /// Hook execution failed (fail-closed).
737    #[error("hook execution failed: {message}")]
738    Failed { message: String },
739    /// Hook execution was cancelled cooperatively.
740    #[error("hook execution cancelled")]
741    Cancelled,
742    /// Host returned a decision variant for the wrong hook point.
743    #[error("hook decision point mismatch: expected {expected}, received {actual}")]
744    DecisionTypeMismatch {
745        expected: HookPoint,
746        actual: HookPoint,
747    },
748    /// Hook decision payload violated a contract invariant.
749    #[error("invalid hook decision: {message}")]
750    InvalidDecision { message: String },
751}
752
753/// Boxed async future returned by object-safe runtime hook handlers.
754pub type HookFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, HookError>> + Send + 'a>>;
755
756/// Object-safe async hook handler evaluated in-process by the Rust runtime.
757pub trait RuntimeHookHandler: Send + Sync {
758    /// Declares which hook points and tool names this handler cares about.
759    fn subscriptions(&self) -> HookSubscriptions;
760
761    /// Intercepts execution before a model step is compiled and sent.
762    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    /// Intercepts execution after a model step finishes.
771    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    /// Intercepts a tool call before execution.
780    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    /// Intercepts a tool call after execution, before durable commit.
789    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}