Skip to main content

reef_core/runtime/
hook.rs

1//! Capability-scoped hooks and immutable registration.
2//!
3//! The inventory is fixed data rather than prose: `HOOK_INVENTORY` names every
4//! callback with its family, scope and decision. The gate pins that inventory and
5//! the lifecycle-name mapping; production dispatch remains typed code, tracked by
6//! the dispatcher references beside the inventory rather than inferred by the gate.
7//! ADR-003 fixes the inventory. Waiters, producer authority, session leases, and
8//! tool-execution internals are intentionally absent from every hook scope.
9//!
10//! # Synchronous cooperative callbacks
11//!
12//! Every hook method is synchronous. Within one boundary, registrations run in
13//! deterministic order, and that boundary does not advance until each applicable
14//! callback returns. Cancellation is checked around callbacks but cannot preempt one
15//! that is currently executing, so
16//! a callback must not block forever or wait for work that needs the same runtime
17//! thread to advance. [`ToolHooks::after_tool_commit`] runs on the blocking pool, but
18//! the Run still joins it before completing; moving it off a runtime worker does not
19//! turn it into a detached callback.
20//!
21//! Work whose answer controls the current boundary must remain synchronous here or
22//! use the asynchronous rail that owns that work, such as a
23//! [`tool::Executor`](crate::runtime::tool::Executor),
24//! [`tool::Provider`](crate::runtime::tool::Provider), or
25//! [`model::Client`] wrapper. Passive observation may
26//! instead be made asynchronous in the composition layer: an [`ObserverHooks`]
27//! implementation copies the facts it needs into an owned message, submits that
28//! message to a non-blocking queue, and returns. Queue capacity, overflow, ordering,
29//! error reporting, shutdown draining, and process isolation are policies of that
30//! adapter, not `agent::Config`. A borrowed hook scope must never escape the callback.
31
32use std::cell::RefCell;
33use std::error::Error;
34use std::fmt;
35use std::panic::{AssertUnwindSafe, catch_unwind};
36use std::sync::Arc;
37
38use crate::cancel::Token;
39
40use crate::audit;
41use crate::redact::Presence;
42use crate::runtime::event::StopCode;
43use crate::runtime::model::{self, CompletionReason, Info, Request, RequestPlan};
44use crate::runtime::session::InputTarget;
45use crate::runtime::tool::{CallDisposition, StepToolSnapshot};
46use crate::state::run_state::{self};
47use crate::state::session_state::{self, CallbackWritePermit};
48use crate::transcript::item::{Assistant, Item};
49use crate::transcript::store::{
50    self, Appender, Replacer, Snapshot, SnapshotReader, Store, Version,
51};
52use crate::value::content::Part;
53use crate::value::lifecycle::{Coord, Outcome};
54use crate::value::tool_call::{ToolCall, ToolResult};
55
56/// A callback family implemented by one narrow trait.
57#[cfg(test)]
58#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
59#[non_exhaustive]
60pub(crate) enum HookFamily {
61    /// Run preparation, continuation, and natural finalization.
62    Run,
63    /// Injected-input admission.
64    Input,
65    /// Turn and Step boundaries.
66    TurnStep,
67    /// Model request/output boundaries.
68    Model,
69    /// Tool-call and tool-result boundaries.
70    Tool,
71    /// Passive observations.
72    Observer,
73    /// Transcript pre-commit reservation.
74    Transcript,
75    /// Agent teardown, separate from runtime hooks.
76    AgentTeardown,
77}
78
79/// The fourteen capability-scoped context shapes in the immutable baseline.
80#[cfg(test)]
81#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
82#[non_exhaustive]
83pub(crate) enum ScopeKind {
84    /// Run preparation.
85    Prepare,
86    /// Natural Run finalization.
87    Finalize,
88    /// Prospective-Turn stop decision.
89    Continue,
90    /// Injected-input admission.
91    InputAdmit,
92    /// Turn boundary.
93    Turn,
94    /// Writable Step preparation.
95    BeforeStep,
96    /// Read-only completed Step.
97    AfterStep,
98    /// Before model invocation.
99    BeforeModel,
100    /// After model output assembly.
101    AfterModel,
102    /// Before tool admission.
103    ToolCall,
104    /// Before tool-result commit.
105    ToolResult,
106    /// After durable tool execution.
107    AfterToolCommit,
108    /// Passive observation with audit-only emission.
109    Observer,
110    /// Fully read-only, non-emitting callback.
111    Read,
112}
113
114/// The closed decision families, one per callback whose return steers the runtime.
115///
116/// Two of the nine are additions this implementation makes over the shape it
117/// inherited: [`DecisionKind::Prepare`] and [`DecisionKind::Finalize`] exist for
118/// one reason stated twice. Composing initial input and composing continuation
119/// input through a bare part list cannot tell "I have no opinion" apart from
120/// "replace what everyone before me composed with nothing".
121#[cfg(test)]
122#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
123#[non_exhaustive]
124pub(crate) enum DecisionKind {
125    /// Model request control.
126    BeforeModel,
127    /// Model output rewrite.
128    AfterModel,
129    /// Tool-call control.
130    ToolCall,
131    /// Tool-result rewrite.
132    ToolResult,
133    /// Injected-input admission.
134    InputAdmit,
135    /// Run continuation or the sole hook stop request.
136    Continue,
137    /// Step completion and optional Turn close.
138    AfterStep,
139    /// Initial input composition.
140    Prepare,
141    /// Natural-completion continuation composition.
142    Finalize,
143}
144
145/// One mechanically reviewable callback-to-capability mapping.
146#[cfg(test)]
147#[derive(Clone, Copy, Debug, Eq, PartialEq)]
148#[non_exhaustive]
149pub(crate) struct HookSpec {
150    /// Stable callback spelling; crate-private dispatch key, not a public
151    /// contract. The `On*` strings are internal inventory IDs.
152    pub(crate) name: &'static str,
153    /// Narrow trait family which owns the callback.
154    pub(crate) family: HookFamily,
155    /// Scope, or `None` when the callback has no runtime scope.
156    pub(crate) scope: Option<ScopeKind>,
157    /// Closed decision, or `None` when the return is observation/items/reservation.
158    pub(crate) decision: Option<DecisionKind>,
159}
160
161#[cfg(test)]
162pub(crate) const fn hook(
163    name: &'static str,
164    family: HookFamily,
165    scope: Option<ScopeKind>,
166    decision: Option<DecisionKind>,
167) -> HookSpec {
168    HookSpec {
169        name,
170        family,
171        scope,
172        decision,
173    }
174}
175
176/// The complete callback inventory: every runtime callback plus Agent teardown.
177///
178/// The `On*` strings are crate-private dispatch keys (internal IDs), not a
179/// public contract. Consumers implement the family traits; they never name
180/// these spellings.
181///
182/// This is a slice rather than a fixed-size array on purpose. The number of
183/// callbacks is data, not type: baking it into the signature would make every
184/// added or removed hook a breaking change for callers that never counted them.
185///
186/// Dispatcher trace for review:
187///
188/// - `OnPrepareRun` / `OnFinalizeRun` / `OnContinueRun`:
189///   `invoke_prepare` / `invoke_compose_continuation` / `invoke_decide_stop`;
190/// - input, Turn, Step, and model entries: their corresponding
191///   `RegistrationAdapter::invoke_*` methods;
192/// - `OnBeforeToolCall` / `OnBeforeToolResult` / `OnAfterToolExecute`:
193///   `invoke_before_tool_call` / `invoke_before_tool_result` / `invoke_after_tool_commit`;
194/// - lifecycle entries: `lifecycle_hook_name` plus `invoke_lifecycle`;
195/// - other observers: `invoke_run_admitted`, `invoke_model_event`, `invoke_audit_event`;
196/// - transcript and Agent-owned teardown: `invoke_reserve` and [`RuntimeRegistry::close`].
197///
198/// The inventory gate intentionally verifies this data and the lifecycle mapping,
199/// not reachability of those production call sites. Removing or adding a callback
200/// therefore requires updating this trace and reviewing its caller as well.
201#[cfg(test)]
202pub(crate) const HOOK_INVENTORY: &[HookSpec] = &[
203    hook(
204        "OnPrepareRun",
205        HookFamily::Run,
206        Some(ScopeKind::Prepare),
207        Some(DecisionKind::Prepare),
208    ),
209    hook(
210        "OnFinalizeRun",
211        HookFamily::Run,
212        Some(ScopeKind::Finalize),
213        Some(DecisionKind::Finalize),
214    ),
215    hook(
216        "OnRunAdmitted",
217        HookFamily::Observer,
218        Some(ScopeKind::Read),
219        None,
220    ),
221    hook(
222        "OnBeforeToolCall",
223        HookFamily::Tool,
224        Some(ScopeKind::ToolCall),
225        Some(DecisionKind::ToolCall),
226    ),
227    hook(
228        "OnBeforeToolResult",
229        HookFamily::Tool,
230        Some(ScopeKind::ToolResult),
231        Some(DecisionKind::ToolResult),
232    ),
233    hook(
234        "OnAfterToolExecute",
235        HookFamily::Tool,
236        Some(ScopeKind::AfterToolCommit),
237        None,
238    ),
239    hook(
240        "OnBeforeModel",
241        HookFamily::Model,
242        Some(ScopeKind::BeforeModel),
243        Some(DecisionKind::BeforeModel),
244    ),
245    hook(
246        "OnAfterModel",
247        HookFamily::Model,
248        Some(ScopeKind::AfterModel),
249        Some(DecisionKind::AfterModel),
250    ),
251    hook(
252        "OnBeforeInputAdmit",
253        HookFamily::Input,
254        Some(ScopeKind::InputAdmit),
255        Some(DecisionKind::InputAdmit),
256    ),
257    hook(
258        "OnBeforeTurn",
259        HookFamily::TurnStep,
260        Some(ScopeKind::Turn),
261        None,
262    ),
263    hook(
264        "OnAfterTurn",
265        HookFamily::TurnStep,
266        Some(ScopeKind::Turn),
267        None,
268    ),
269    hook(
270        "OnBeforeStep",
271        HookFamily::TurnStep,
272        Some(ScopeKind::BeforeStep),
273        None,
274    ),
275    hook(
276        "OnAfterStep",
277        HookFamily::TurnStep,
278        Some(ScopeKind::AfterStep),
279        Some(DecisionKind::AfterStep),
280    ),
281    hook("OnClose", HookFamily::AgentTeardown, None, None),
282    hook(
283        "OnContinueRun",
284        HookFamily::Run,
285        Some(ScopeKind::Continue),
286        Some(DecisionKind::Continue),
287    ),
288    hook(
289        "OnRunStart",
290        HookFamily::Observer,
291        Some(ScopeKind::Observer),
292        None,
293    ),
294    hook(
295        "OnRunEnd",
296        HookFamily::Observer,
297        Some(ScopeKind::Observer),
298        None,
299    ),
300    hook(
301        "OnTurnStart",
302        HookFamily::Observer,
303        Some(ScopeKind::Observer),
304        None,
305    ),
306    hook(
307        "OnTurnEnd",
308        HookFamily::Observer,
309        Some(ScopeKind::Observer),
310        None,
311    ),
312    hook(
313        "OnStepStart",
314        HookFamily::Observer,
315        Some(ScopeKind::Observer),
316        None,
317    ),
318    hook(
319        "OnStepEnd",
320        HookFamily::Observer,
321        Some(ScopeKind::Observer),
322        None,
323    ),
324    hook(
325        "OnGenerationStart",
326        HookFamily::Observer,
327        Some(ScopeKind::Observer),
328        None,
329    ),
330    hook(
331        "OnGenerationEnd",
332        HookFamily::Observer,
333        Some(ScopeKind::Observer),
334        None,
335    ),
336    hook(
337        "OnToolCallStart",
338        HookFamily::Observer,
339        Some(ScopeKind::Observer),
340        None,
341    ),
342    hook(
343        "OnToolCallEnd",
344        HookFamily::Observer,
345        Some(ScopeKind::Observer),
346        None,
347    ),
348    hook(
349        "OnModelEvent",
350        HookFamily::Observer,
351        Some(ScopeKind::Observer),
352        None,
353    ),
354    hook(
355        "OnAuditEvent",
356        HookFamily::Observer,
357        Some(ScopeKind::Read),
358        None,
359    ),
360    hook(
361        "OnTranscriptMutation",
362        HookFamily::Transcript,
363        Some(ScopeKind::Read),
364        None,
365    ),
366];
367
368/// Boxed hook callback error which preserves the concrete source for downcast.
369///
370/// # Effect on the Run
371///
372/// Returning one of these is a decision that the Run should not continue, not a
373/// hint that something went wrong. Reef never retries a callback, substitutes a
374/// default decision, or carries on with the remaining registrations: the failing
375/// boundary short-circuits, and whatever it had composed, staged, or planned is
376/// discarded rather than half-applied. Peers registered after the failure are not
377/// called, and peers that already ran do not have their contributions kept.
378///
379/// The failure always reaches the caller with the failing registration's name
380/// attached, as an [`AttributedError`]. Where it surfaces depends only on which
381/// boundary was running:
382///
383/// - At Run admission, as
384///   [`StartError::Prepare`](crate::runtime::agent::StartError::Prepare). The
385///   Session lease and Agent attachment are rolled back, so admission having
386///   failed means nothing was committed and no Run exists.
387/// - At every other boundary, by ending the Run: its
388///   [`Terminal`](crate::runtime::run::Terminal) reports
389///   [`Outcome::Failed`] with the
390///   [`FailureKind`](crate::runtime::run::FailureKind) of the boundary that was
391///   running — [`Hook`](crate::runtime::run::FailureKind::Hook) for most,
392///   [`Transcript`](crate::runtime::run::FailureKind::Transcript) or
393///   [`ToolCommit`](crate::runtime::run::FailureKind::ToolCommit) for a failed
394///   reservation, according to which mutation it was reserving. The retained
395///   failure is reachable from the terminal, and the registration name survives
396///   the whole chain.
397///
398/// A cancellation observed at the same boundary ends the Run as
399/// [`Cancelled`](crate::value::lifecycle::Outcome::Cancelled) instead; a real
400/// callback error is never downgraded to a cancellation.
401///
402/// This is why a degradation the Run can survive should not be reported this way.
403/// A mutating scope's `emit_error` method publishes a non-fatal fact and leaves
404/// the Run running, which is the right shape for a hook whose optional work
405/// failed. `HookError` is for the case where continuing would be wrong.
406#[derive(Clone)]
407#[expect(
408    clippy::module_name_repetitions,
409    reason = "HookError distinguishes callback failures from the hook module's other errors"
410)]
411pub struct HookError(Arc<dyn Error + Send + Sync>);
412
413impl HookError {
414    /// Retains a concrete callback error without string flattening.
415    #[must_use]
416    pub fn new(error: impl Error + Send + Sync + 'static) -> Self {
417        Self(Arc::new(error))
418    }
419
420    /// Returns the retained concrete source.
421    #[must_use]
422    pub fn source_ref(&self) -> &(dyn Error + Send + Sync + 'static) {
423        self.0.as_ref()
424    }
425}
426
427impl fmt::Debug for HookError {
428    /// Renders every link of the retained chain, each one through `Display`.
429    ///
430    /// Printing only the outermost link would discard the chain that
431    /// [`source_ref`] retains: a callback error that wraps its own cause reads
432    /// as a single sentence, and the reason underneath it — the one a reader is
433    /// usually after — never appears. Walking `source` states the whole chain.
434    ///
435    /// `Display` rather than the link's own `Debug`, because the cause is
436    /// whatever a hook handed back: arbitrary text this crate neither writes
437    /// nor reviews. `Display` is the rendering those types are contracted to
438    /// produce, and it is what every other boxed failure in reef prints.
439    ///
440    /// [`source_ref`]: Self::source_ref
441    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
442        let mut tuple = formatter.debug_tuple("HookError");
443        let mut link: Option<&(dyn Error + 'static)> = Some(self.0.as_ref());
444        while let Some(error) = link {
445            tuple.field(&error.to_string());
446            link = error.source();
447        }
448        tuple.finish()
449    }
450}
451
452impl fmt::Display for HookError {
453    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
454        self.0.fmt(formatter)
455    }
456}
457
458impl Error for HookError {
459    fn source(&self) -> Option<&(dyn Error + 'static)> {
460        Some(self.0.as_ref())
461    }
462}
463
464/// Result returned by a mutating or reserving callback.
465#[expect(
466    clippy::module_name_repetitions,
467    reason = "HookResult names the shared callback result contract rather than a generic module result"
468)]
469pub type HookResult<T> = Result<T, HookError>;
470
471/// Stable Session identity without transcript, inbox, state-write, or lease authority.
472#[derive(Clone, Copy, Debug)]
473pub struct SessionIdentity<'a>(&'a Coord);
474
475impl SessionIdentity<'_> {
476    /// Returns the Session identifier carried by the callback coordinate.
477    #[must_use]
478    pub fn id(&self) -> &str {
479        self.0.session_id()
480    }
481}
482
483/// A callback-local transcript capability.
484///
485/// The controller creates this from an isolated [`Store`]. It exposes only
486/// append and replacement authority; phase-aligned reads come from the enclosing
487/// scope's `transcript` method. Nothing staged here is visible until the
488/// controller commits.
489#[derive(Debug)]
490pub struct StagedTranscript {
491    reader: SnapshotReader,
492    appender: Appender,
493    replacer: Replacer,
494}
495
496impl StagedTranscript {
497    pub(crate) fn from_store(store: &Store) -> Self {
498        Self {
499            reader: store.snapshot_reader(),
500            appender: store.appender(),
501            replacer: store.replacer(),
502        }
503    }
504
505    /// Appends an ordered owned batch to this callback's staging area.
506    ///
507    /// # Errors
508    ///
509    /// [`store::Error::VersionOverflow`] if the staged version would pass
510    /// [`Version::MAX`], or [`store::Error::Poisoned`] if a writer panicked
511    /// inside this staging area. There is no version conflict to report, because
512    /// this append names no expected version: composing into a
513    /// staging area is not a race against the live transcript, and what the
514    /// boundary later commits is compare-and-set against the live version for the
515    /// registrations as a whole.
516    pub fn append_batch(&self, items: Vec<Item>) -> Result<Version, store::Error> {
517        self.appender.append_batch(items)
518    }
519
520    /// Replaces this callback's complete staged history.
521    ///
522    /// # Errors
523    ///
524    /// [`store::Error::VersionOverflow`] or [`store::Error::Poisoned`], for the
525    /// same reasons as [`append_batch`](Self::append_batch). Replacing the staged
526    /// history does not replace the live one; what reaches the session is the
527    /// resolved staged result, committed by the boundary that created this
528    /// capability.
529    pub fn replace(&self, items: Vec<Item>) -> Result<Version, store::Error> {
530        self.replacer.replace(items)
531    }
532}
533
534/// The internal outward capability behind mutating hook scopes.
535pub(crate) trait Emitter: Send + Sync {
536    /// Emits a validated, non-model-visible audit fact.
537    fn emit_audit(&self, event: audit::Event);
538
539    /// Emits a non-fatal error fact without granting event producer authority.
540    fn emit_error(&self, error: Arc<dyn Error + Send + Sync>);
541}
542
543/// One fact a synchronous callback handed to the loop for publication.
544#[derive(Debug)]
545pub(crate) enum BufferedFact {
546    Audit(audit::Event),
547    Error(Arc<dyn Error + Send + Sync>),
548}
549
550/// The [`Emitter`] every synchronous callback on the loop's own thread writes to.
551///
552/// A callback is synchronous and the outward stream is not, so no callback can
553/// publish anything itself: it records the fact here and the loop hands the queue
554/// to the `Producer` at its next await point. The queue is FIFO and every drain is
555/// total, so the only latitude the loop has is *when* it drains — and it drains
556/// before its own next publication. That is what makes
557/// [`ObserverScope::emit_audit`] mean "now" instead of "some time before this Run
558/// ends": a fact queued while the model stream is still arriving reaches the
559/// consumer ahead of the content event that follows it.
560///
561/// The one exception is a callback running on the managed blocking pool, which
562/// cannot use a buffer at all: it has already returned control to no one, so it
563/// emits through a request/ack rendezvous with the loop instead.
564#[derive(Debug, Default)]
565pub(crate) struct FactBuffer {
566    facts: std::sync::Mutex<Vec<BufferedFact>>,
567}
568
569impl FactBuffer {
570    /// Removes and returns every queued fact, preserving producer order.
571    pub(crate) fn take_facts(&self) -> Vec<BufferedFact> {
572        std::mem::take(&mut *self.facts.lock().expect("hook fact lock poisoned"))
573    }
574
575    #[cfg(test)]
576    pub(crate) fn audit_kinds(&self) -> Vec<String> {
577        self.facts
578            .lock()
579            .expect("hook fact lock poisoned")
580            .iter()
581            .filter_map(|fact| match fact {
582                BufferedFact::Audit(event) => Some(event.kind().to_owned()),
583                BufferedFact::Error(_) => None,
584            })
585            .collect()
586    }
587
588    #[cfg(test)]
589    pub(crate) fn error_messages(&self) -> Vec<String> {
590        self.facts
591            .lock()
592            .expect("hook fact lock poisoned")
593            .iter()
594            .filter_map(|fact| match fact {
595                BufferedFact::Audit(_) => None,
596                BufferedFact::Error(error) => Some(error.to_string()),
597            })
598            .collect()
599    }
600}
601
602impl Emitter for FactBuffer {
603    fn emit_audit(&self, event: audit::Event) {
604        self.facts
605            .lock()
606            .expect("hook fact lock poisoned")
607            .push(BufferedFact::Audit(event));
608    }
609
610    fn emit_error(&self, error: Arc<dyn Error + Send + Sync>) {
611        self.facts
612            .lock()
613            .expect("hook fact lock poisoned")
614            .push(BufferedFact::Error(error));
615    }
616}
617
618#[derive(Clone, Copy, Debug)]
619pub(crate) enum TranscriptSource<'a> {
620    Reader(&'a SnapshotReader),
621    Snapshot(&'a Snapshot),
622}
623
624impl TranscriptSource<'_> {
625    pub(crate) fn snapshot(self) -> Result<Snapshot, store::Error> {
626        match self {
627            Self::Reader(reader) => reader.snapshot(),
628            Self::Snapshot(snapshot) => Ok(snapshot.clone()),
629        }
630    }
631}
632
633#[derive(Clone, Copy, Debug)]
634struct ReadBase<'a> {
635    session: SessionIdentity<'a>,
636    coord: &'a Coord,
637    run_state: &'a run_state::Store,
638    session_state: &'a session_state::Reader,
639    transcript: TranscriptSource<'a>,
640}
641
642#[derive(Clone, Copy, Debug)]
643struct WriteBase<'a> {
644    read: ReadBase<'a>,
645    session_state: Option<&'a session_state::Writer>,
646}
647
648#[derive(Clone, Copy, Debug)]
649struct PrepareBase<'a> {
650    read: ReadBase<'a>,
651    session_state: Option<&'a session_state::StagedWriter>,
652}
653
654#[derive(Clone, Copy)]
655struct ControlBase<'a> {
656    write: WriteBase<'a>,
657    emitter: &'a dyn Emitter,
658}
659
660impl fmt::Debug for ControlBase<'_> {
661    /// Shows the read/write position and elides the emitter behind it.
662    ///
663    /// The crate-private emitter has no `Debug` supertrait, so its implementation
664    /// identity is not useful to print. The trailing `..` records that something
665    /// is there rather than implying nothing is.
666    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
667        formatter
668            .debug_struct("ControlBase")
669            .field("write", &self.write)
670            .finish_non_exhaustive()
671    }
672}
673
674#[derive(Clone, Copy, Debug)]
675struct StagedBase<'a> {
676    control: ControlBase<'a>,
677    staged: &'a StagedTranscript,
678}
679
680macro_rules! read_capabilities {
681    ($this:ident, $base:expr) => {
682        /// Returns stable Session identity without broader Session authority.
683        #[must_use]
684        pub const fn session(&$this) -> SessionIdentity<'_> {
685            $base.read.session
686        }
687
688        /// Returns the immutable callback coordinate.
689        #[must_use]
690        pub const fn coord(&$this) -> &Coord {
691            $base.read.coord
692        }
693
694        /// Returns this hook's private per-Run scratch store.
695        #[must_use]
696        pub const fn run_state(&$this) -> &run_state::Store {
697            $base.read.run_state
698        }
699
700        /// Returns owned-snapshot Session-state read authority.
701        #[must_use]
702        pub const fn session_state(&$this) -> &session_state::Reader {
703            $base.read.session_state
704        }
705
706        /// Captures the complete transcript at this callback's phase position.
707        ///
708        /// # Errors
709        ///
710        /// Returns [`store::Error::Poisoned`] if the underlying transcript lock
711        /// was poisoned.
712        pub fn transcript(&$this) -> Result<Snapshot, store::Error> {
713            $base.read.transcript.snapshot()
714        }
715    };
716}
717
718macro_rules! direct_read_capabilities {
719    ($this:ident, $base:expr) => {
720        /// Returns stable Session identity without broader Session authority.
721        #[must_use]
722        pub const fn session(&$this) -> SessionIdentity<'_> {
723            $base.session
724        }
725
726        /// Returns the immutable callback coordinate.
727        #[must_use]
728        pub const fn coord(&$this) -> &Coord {
729            $base.coord
730        }
731
732        /// Returns this hook's private per-Run scratch store.
733        #[must_use]
734        pub const fn run_state(&$this) -> &run_state::Store {
735            $base.run_state
736        }
737
738        /// Returns owned-snapshot Session-state read authority.
739        #[must_use]
740        pub const fn session_state(&$this) -> &session_state::Reader {
741            $base.session_state
742        }
743
744        /// Captures the complete transcript at this callback's phase position.
745        ///
746        /// # Errors
747        ///
748        /// Returns [`store::Error::Poisoned`] if the underlying transcript lock
749        /// was poisoned.
750        pub fn transcript(&$this) -> Result<Snapshot, store::Error> {
751            $base.transcript.snapshot()
752        }
753    };
754}
755
756macro_rules! write_capabilities {
757    ($this:ident, $base:expr) => {
758        read_capabilities!($this, $base);
759
760        /// Returns lease-bound write authority only for a hook which declared
761        /// `requires_session_state(true)`.
762        #[must_use]
763        pub const fn session_state_writer(&$this) -> Option<&session_state::Writer> {
764            $base.session_state
765        }
766    };
767}
768
769macro_rules! control_capabilities {
770    ($this:ident, $base:expr) => {
771        write_capabilities!($this, $base.write);
772
773        /// Emits an audit fact through the capability-narrowed boundary.
774        pub fn emit_audit(&$this, event: audit::Event) {
775            $base.emitter.emit_audit(event);
776        }
777
778        /// Emits a non-fatal error through the capability-narrowed boundary.
779        pub fn emit_error(&$this, error: Arc<dyn Error + Send + Sync>) {
780            $base.emitter.emit_error(error);
781        }
782    };
783}
784
785macro_rules! staged_capabilities {
786    ($this:ident, $base:expr) => {
787        control_capabilities!($this, $base.control);
788
789        /// Returns this callback's isolated transcript staging area.
790        #[must_use]
791        pub const fn staged(&$this) -> &StagedTranscript {
792            $base.staged
793        }
794    };
795}
796
797/// [`RunHooks::prepare`] scope; no outward stream exists at this boundary.
798///
799/// Both writable capabilities are callback-local overlays. The controller owns
800/// their resolution and this scope cannot mutate the live Session directly.
801#[derive(Debug)]
802pub struct PrepareScope<'a> {
803    base: PrepareBase<'a>,
804    staged: &'a StagedTranscript,
805    base_snapshot: &'a Snapshot,
806    input: &'a [Part],
807}
808
809impl PrepareScope<'_> {
810    direct_read_capabilities!(self, self.base.read);
811
812    /// Returns the callback-local Session-state overlay when this registration
813    /// declared `requires_session_state(true)`.
814    #[must_use]
815    pub const fn staged_session_state_writer(&self) -> Option<&session_state::StagedWriter> {
816        self.base.session_state
817    }
818
819    /// Returns this callback's isolated transcript staging area.
820    #[must_use]
821    pub const fn staged(&self) -> &StagedTranscript {
822        self.staged
823    }
824
825    /// Returns the pre-prepare atomic transcript snapshot.
826    #[must_use]
827    pub const fn base_snapshot(&self) -> &Snapshot {
828        self.base_snapshot
829    }
830
831    /// Returns the current composed input proposal.
832    #[must_use]
833    pub const fn input(&self) -> &[Part] {
834        self.input
835    }
836}
837
838/// [`RunHooks::compose_continuation`] scope on the natural completion path.
839#[derive(Debug)]
840pub struct ContinuationScope<'a> {
841    base: StagedBase<'a>,
842    continuation: &'a [Part],
843    continuations: usize,
844    turns: usize,
845}
846
847impl ContinuationScope<'_> {
848    staged_capabilities!(self, self.base);
849
850    /// Returns the preceding hook's continuation proposal.
851    #[must_use]
852    pub const fn continuation(&self) -> &[Part] {
853        self.continuation
854    }
855
856    /// Returns the number of prior continuation Turns.
857    #[must_use]
858    pub const fn continuations(&self) -> usize {
859        self.continuations
860    }
861
862    /// Returns the number of completed Turns.
863    #[must_use]
864    pub const fn turns(&self) -> usize {
865        self.turns
866    }
867}
868
869/// [`RunHooks::decide_stop`] scope before a prospective Turn exists.
870#[derive(Debug)]
871pub struct StopDecisionScope<'a> {
872    base: ControlBase<'a>,
873}
874
875impl StopDecisionScope<'_> {
876    control_capabilities!(self, self.base);
877}
878
879/// [`InputHooks::before_input_admit`] scope around one claimed owned batch.
880#[derive(Debug)]
881pub struct InputAdmitScope<'a> {
882    base: ControlBase<'a>,
883    target: InputTarget,
884    items: &'a [Item],
885}
886
887impl InputAdmitScope<'_> {
888    control_capabilities!(self, self.base);
889
890    /// Returns the frozen mailbox target.
891    #[must_use]
892    pub const fn target(&self) -> InputTarget {
893        self.target
894    }
895
896    /// Returns the claimed batch as a read-only slice.
897    #[must_use]
898    pub const fn items(&self) -> &[Item] {
899        self.items
900    }
901}
902
903/// Shared scope for true Turn boundary hooks.
904#[derive(Debug)]
905pub struct TurnScope<'a> {
906    base: StagedBase<'a>,
907    trigger: &'a [Item],
908}
909
910impl TurnScope<'_> {
911    staged_capabilities!(self, self.base);
912
913    /// Returns the input batch which opened this Turn.
914    #[must_use]
915    pub const fn trigger(&self) -> &[Item] {
916        self.trigger
917    }
918}
919
920/// One owned, immutable Step fact frozen after the sole writable plan window.
921///
922/// The runtime creates this once per Step and reuses the same [`Arc`] at every
923/// later hook and lifecycle boundary. The owned plan retains all five lanes:
924/// system instruction, client tools, sampling parameters, hosted extensions,
925/// and ephemeral content. The tool snapshot preserves the exact routing handles
926/// from which the model-visible tool lanes were materialized.
927#[derive(Debug)]
928pub struct StepSnapshot {
929    model: Info,
930    plan: RequestPlan,
931    tools: StepToolSnapshot,
932    shared_tools: Arc<StepToolSnapshot>,
933}
934
935impl StepSnapshot {
936    pub(crate) fn freeze(model: Info, plan: RequestPlan, tools: StepToolSnapshot) -> Arc<Self> {
937        // `StepToolSnapshot::shallow_clone` preserves the same executor/mapper
938        // handles and transcript Arc. The public value getter can remain const,
939        // while batch routing receives one shared owner without resolving providers
940        // a second time through `StepToolSnapshot::shallow_clone`.
941        let shared_tools = Arc::new(tools.shallow_clone());
942        Arc::new(Self {
943            model,
944            plan,
945            tools,
946            shared_tools,
947        })
948    }
949
950    /// Returns the complete frozen model identity and capability facts.
951    #[must_use]
952    pub const fn model(&self) -> &Info {
953        &self.model
954    }
955
956    /// Returns the complete frozen plan, including every model-input lane.
957    #[must_use]
958    pub const fn plan(&self) -> &RequestPlan {
959        &self.plan
960    }
961
962    /// Returns the exact immutable exposure/router snapshot for this Step.
963    #[must_use]
964    pub const fn tools(&self) -> &StepToolSnapshot {
965        &self.tools
966    }
967
968    /// Returns the shared shallow twin used by invocation routing.
969    pub(crate) const fn shared_tools(&self) -> &Arc<StepToolSnapshot> {
970        &self.shared_tools
971    }
972}
973
974/// `OnBeforeStep` scope and the sole writable [`RequestPlan`] window.
975#[derive(Debug)]
976pub struct BeforeStepScope<'a> {
977    base: StagedBase<'a>,
978    model: &'a Info,
979    plan: &'a mut RequestPlan,
980}
981
982impl BeforeStepScope<'_> {
983    staged_capabilities!(self, self.base);
984
985    /// Returns immutable model identity and capabilities.
986    #[must_use]
987    pub const fn model(&self) -> &Info {
988        self.model
989    }
990
991    /// Returns the unique plan which runtime re-reads after this fan-out.
992    pub const fn plan(&mut self) -> &mut RequestPlan {
993        self.plan
994    }
995}
996
997/// `OnAfterStep` scope with the shared immutable Step snapshot.
998#[derive(Debug)]
999pub struct AfterStepScope<'a> {
1000    base: StagedBase<'a>,
1001    snapshot: &'a Arc<StepSnapshot>,
1002}
1003
1004impl AfterStepScope<'_> {
1005    staged_capabilities!(self, self.base);
1006
1007    /// Returns the exact frozen Step snapshot reused by later boundaries.
1008    #[must_use]
1009    pub fn snapshot(&self) -> &StepSnapshot {
1010        self.snapshot
1011    }
1012}
1013
1014/// [`ModelHooks::before_model`] scope over one immutable request and Step snapshot.
1015#[derive(Debug)]
1016pub struct BeforeModelScope<'a> {
1017    base: ControlBase<'a>,
1018    snapshot: &'a Arc<StepSnapshot>,
1019    request: &'a Request,
1020}
1021
1022impl BeforeModelScope<'_> {
1023    control_capabilities!(self, self.base);
1024
1025    /// Returns the exact frozen Step snapshot.
1026    #[must_use]
1027    pub fn snapshot(&self) -> &StepSnapshot {
1028        self.snapshot
1029    }
1030
1031    /// Returns the current frozen request; rewrites use the returned decision.
1032    #[must_use]
1033    pub const fn request(&self) -> &Request {
1034        self.request
1035    }
1036}
1037
1038/// [`ModelHooks::after_model`] scope over assembled but uncommitted assistant output.
1039#[derive(Debug)]
1040pub struct AfterModelScope<'a> {
1041    base: ControlBase<'a>,
1042    snapshot: &'a Arc<StepSnapshot>,
1043    output: &'a Assistant,
1044    generated: bool,
1045    finish_reason: &'a str,
1046    completion: CompletionReason,
1047}
1048
1049impl AfterModelScope<'_> {
1050    control_capabilities!(self, self.base);
1051
1052    /// Returns the exact frozen Step snapshot used for this generation.
1053    #[must_use]
1054    pub fn snapshot(&self) -> &StepSnapshot {
1055        self.snapshot
1056    }
1057
1058    /// Returns the current read-only assistant output.
1059    #[must_use]
1060    pub const fn output(&self) -> &Assistant {
1061        self.output
1062    }
1063
1064    /// Reports whether a real model generation produced this output.
1065    #[must_use]
1066    pub const fn generated(&self) -> bool {
1067        self.generated
1068    }
1069
1070    /// Returns the provider's verbatim finish label.
1071    ///
1072    /// This is empty when no provider supplied a label, including when
1073    /// [`BeforeModelDecision::ShortCircuit`] bypassed provider invocation.
1074    #[must_use]
1075    pub const fn finish_reason(&self) -> &str {
1076        self.finish_reason
1077    }
1078
1079    /// Returns the portable completion classification.
1080    #[must_use]
1081    pub const fn completion(&self) -> CompletionReason {
1082        self.completion
1083    }
1084}
1085
1086/// `OnBeforeToolCall` scope over one effective call and frozen Step facts.
1087#[derive(Debug)]
1088pub struct ToolCallScope<'a> {
1089    base: ControlBase<'a>,
1090    snapshot: &'a Arc<StepSnapshot>,
1091    call: &'a ToolCall,
1092}
1093
1094impl ToolCallScope<'_> {
1095    control_capabilities!(self, self.base);
1096
1097    /// Returns the exact frozen Step snapshot used by this tool batch.
1098    #[must_use]
1099    pub fn snapshot(&self) -> &StepSnapshot {
1100        self.snapshot
1101    }
1102
1103    /// Returns the current call; rewrites use the returned decision.
1104    #[must_use]
1105    pub const fn call(&self) -> &ToolCall {
1106        self.call
1107    }
1108}
1109
1110/// `OnBeforeToolResult` scope over an uncommitted closed result.
1111#[derive(Debug)]
1112pub struct ToolResultScope<'a> {
1113    base: ControlBase<'a>,
1114    snapshot: &'a Arc<StepSnapshot>,
1115    call: &'a ToolCall,
1116    disposition: CallDisposition,
1117    result: &'a ToolResult,
1118}
1119
1120impl ToolResultScope<'_> {
1121    control_capabilities!(self, self.base);
1122
1123    /// Returns the exact frozen Step snapshot used by this tool batch.
1124    #[must_use]
1125    pub fn snapshot(&self) -> &StepSnapshot {
1126        self.snapshot
1127    }
1128
1129    /// Returns the final effective call.
1130    #[must_use]
1131    pub const fn call(&self) -> &ToolCall {
1132        self.call
1133    }
1134
1135    /// Returns the call's stable pre-result disposition.
1136    #[must_use]
1137    pub const fn disposition(&self) -> CallDisposition {
1138        self.disposition
1139    }
1140
1141    /// Returns the current closed result; rewrites use the decision.
1142    #[must_use]
1143    pub const fn result(&self) -> &ToolResult {
1144        self.result
1145    }
1146}
1147
1148/// [`ToolHooks::after_tool_commit`] scope after the complete result batch is durable.
1149#[derive(Debug)]
1150pub struct AfterToolCommitScope<'a> {
1151    base: StagedBase<'a>,
1152    snapshot: &'a Arc<StepSnapshot>,
1153    result: &'a ToolResult,
1154}
1155
1156impl AfterToolCommitScope<'_> {
1157    staged_capabilities!(self, self.base);
1158
1159    /// Returns the exact frozen Step snapshot used by this tool batch.
1160    #[must_use]
1161    pub fn snapshot(&self) -> &StepSnapshot {
1162        self.snapshot
1163    }
1164
1165    /// Returns the already-durable closed result.
1166    #[must_use]
1167    pub const fn result(&self) -> &ToolResult {
1168        self.result
1169    }
1170}
1171
1172/// Passive observer scope with audit-only emission.
1173pub struct ObserverScope<'a> {
1174    base: ReadBase<'a>,
1175    snapshot: Option<&'a Arc<StepSnapshot>>,
1176    audit_sink: &'a dyn ObserverAuditSink,
1177}
1178
1179impl fmt::Debug for ObserverScope<'_> {
1180    /// Shows where the observation is anchored and elides the audit sink.
1181    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1182        formatter
1183            .debug_struct("ObserverScope")
1184            .field("base", &self.base)
1185            .field("snapshot", &Presence(self.snapshot.is_some()))
1186            .finish_non_exhaustive()
1187    }
1188}
1189
1190impl ObserverScope<'_> {
1191    direct_read_capabilities!(self, self.base);
1192
1193    /// Returns the exact frozen Step snapshot when the boundary belongs to a Step.
1194    #[must_use]
1195    pub fn snapshot(&self) -> Option<&StepSnapshot> {
1196        self.snapshot.map(Arc::as_ref)
1197    }
1198
1199    /// Emits only an audit fact; no generic Error or event authority is present.
1200    pub fn emit_audit(&self, event: audit::Event) {
1201        self.audit_sink.push(event);
1202    }
1203
1204    fn with_audit_sink<'a>(&'a self, audit_sink: &'a dyn ObserverAuditSink) -> ObserverScope<'a> {
1205        ObserverScope {
1206            base: self.base,
1207            snapshot: self.snapshot,
1208            audit_sink,
1209        }
1210    }
1211}
1212
1213trait ObserverAuditSink {
1214    fn push(&self, event: audit::Event);
1215}
1216
1217struct CallbackAuditBuffer {
1218    pending: RefCell<Vec<audit::Event>>,
1219}
1220
1221impl CallbackAuditBuffer {
1222    const fn new() -> Self {
1223        Self {
1224            pending: RefCell::new(Vec::new()),
1225        }
1226    }
1227
1228    /// Hands FIFO facts to `emitter` after either a normal return or a panic.
1229    ///
1230    /// This is the inner of two stages, and it is not publication: it exists so
1231    /// that emission happens outside the callback catch boundary, and what it
1232    /// flushes into is normally a [`FactBuffer`], which queues again. When the
1233    /// fact reaches the consumer is decided there — see [`FactBuffer`] — not
1234    /// here.
1235    fn flush_to(&self, emitter: &dyn Emitter) {
1236        for event in self.pending.borrow_mut().drain(..) {
1237            emitter.emit_audit(event);
1238        }
1239    }
1240}
1241
1242impl ObserverAuditSink for CallbackAuditBuffer {
1243    fn push(&self, event: audit::Event) {
1244        self.pending.borrow_mut().push(event);
1245    }
1246}
1247
1248struct DirectAuditSink<'a>(&'a dyn Emitter);
1249
1250impl ObserverAuditSink for DirectAuditSink<'_> {
1251    fn push(&self, event: audit::Event) {
1252        self.0.emit_audit(event);
1253    }
1254}
1255
1256/// Fully read-only, non-emitting scope used inside serialized critical sections.
1257#[derive(Debug)]
1258pub struct ReadScope<'a> {
1259    base: ReadBase<'a>,
1260}
1261
1262impl ReadScope<'_> {
1263    direct_read_capabilities!(self, self.base);
1264}
1265
1266/// [`RunHooks::prepare`] decision.
1267///
1268/// Registrations run in registration order and each observes the previous one's
1269/// result, so a bare part list would make "I do not compose input" and "replace
1270/// everything composed so far with nothing" the same value — and the last
1271/// registration would win outright. A registration that has no opinion about the
1272/// input returns [`PrepareDecision::Continue`]; only [`PrepareDecision::Modify`]
1273/// rewrites it, and it may not rewrite it to nothing.
1274#[derive(Debug)]
1275pub enum PrepareDecision {
1276    /// Keep the composed input unchanged.
1277    Continue,
1278    /// Replace the composed input before admission.
1279    Modify(Vec<Part>),
1280}
1281
1282/// An invalid [`RunHooks::prepare`] decision produced by a registration.
1283///
1284/// This mirrors the `Modify` rule of [`InputAdmitDecision`]: a rewrite that
1285/// would discard everything is invalid, not a silent no-op. Refusing it here is
1286/// what makes "model-visible implies recorded" hold for the admitted input — a
1287/// registration that blanked the caller's parts would otherwise leave the Run
1288/// with a first request the transcript has no record of.
1289#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1290#[non_exhaustive]
1291pub enum PrepareError {
1292    /// A registration returned `Modify` with an empty replacement.
1293    EmptyModify,
1294}
1295
1296impl fmt::Display for PrepareError {
1297    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1298        match self {
1299            Self::EmptyModify => {
1300                formatter.write_str("a registration rewrote the initial input to nothing")
1301            }
1302        }
1303    }
1304}
1305
1306impl Error for PrepareError {}
1307
1308/// [`RunHooks::compose_continuation`] decision.
1309///
1310/// This is [`PrepareDecision`]'s sibling and exists for the same reason:
1311/// registrations run in registration order and each observes the previous one's
1312/// result, so a bare part list would make "I have no opinion about continuing"
1313/// and "replace the continuation everyone before me asked for with nothing" the
1314/// same value, and the last registration would win outright. A registration with
1315/// no opinion returns [`ContinuationDecision::Keep`]; only
1316/// [`ContinuationDecision::Replace`] rewrites the request.
1317///
1318/// The one place it differs from `PrepareDecision` is that an **empty `Replace`
1319/// is legitimate here**, so there is no `FinalizeError`. A continuation is a
1320/// request for another Turn, not user content: replacing it with nothing is a
1321/// governance hook vetoing a peer's request and ending the Run, which is a
1322/// meaningful answer rather than data loss. `PrepareDecision` refuses an empty
1323/// `Modify` because there the parts *are* the caller's submission, and blanking
1324/// them would leave the Run with a first request the transcript never recorded.
1325#[derive(Debug)]
1326pub enum ContinuationDecision {
1327    /// Keep the accumulated continuation request unchanged.
1328    Keep,
1329    /// Replace the accumulated continuation request; empty ends the Run.
1330    Replace(Vec<Part>),
1331}
1332
1333/// [`ModelHooks::before_model`] decision.
1334///
1335/// [`Self::Modify`] is where a composition layer normalises history for the
1336/// provider it is about to call. Core applies visibility and the tool-exchange
1337/// grammar and stops there: it never rewrites a
1338/// [`Segment`](crate::value::content::Segment) because a different provider
1339/// produced it, because deciding that one vendor's thinking segment is unusable
1340/// by another requires knowing both vendors' rules — a `compat` matrix core does
1341/// not and must not learn. A registration that changes model mid-session reads
1342/// [`BeforeModelScope::request`], rewrites the segments its next provider cannot
1343/// accept, and re-freezes through
1344/// [`RequestPlan::try_into_request`](crate::runtime::model::RequestPlan::try_into_request), which
1345/// is the only way to construct a [`Request`] and therefore cannot be bypassed.
1346#[derive(Debug)]
1347pub enum BeforeModelDecision {
1348    /// Continue with the current request.
1349    Continue,
1350    /// Replace the request after runtime validation.
1351    Modify(Request),
1352    /// Supply assistant output without invoking the model.
1353    ///
1354    /// [`AfterModelScope::generated`] is false, its
1355    /// [`AfterModelScope::finish_reason`] is empty because no provider supplied a
1356    /// label, and its completion classification is
1357    /// [`CompletionReason::Unknown`].
1358    ///
1359    /// Tool-call identities and names must be nonempty. Model-visible identities
1360    /// may not repeat either within this record or anywhere in the frozen request
1361    /// history. The runtime rejects an invalid value as a typed,
1362    /// registration-attributed hook failure before anything is committed.
1363    ShortCircuit(Assistant),
1364    /// Deliberately abort model invocation.
1365    Abort(String),
1366}
1367
1368/// [`ModelHooks::after_model`] decision.
1369#[derive(Debug)]
1370pub enum AfterModelDecision {
1371    /// Keep assembled output.
1372    Continue,
1373    /// Replace assembled output before commit.
1374    ///
1375    /// Tool-call identities and names must be nonempty. Model-visible identities
1376    /// may not repeat either within this record or anywhere in the frozen request
1377    /// history. The runtime rejects an invalid value as a typed,
1378    /// registration-attributed hook failure before anything is committed.
1379    Modify(Assistant),
1380}
1381
1382/// [`ToolHooks::before_tool_call`] decision.
1383#[derive(Debug)]
1384pub enum ToolCallDecision {
1385    /// Continue with the current call.
1386    Continue,
1387    /// Replace the call before execution.
1388    ///
1389    /// The runtime preserves the model-assigned id, accepts the replacement name
1390    /// and arguments, and attributes an empty replacement name to this hook as a
1391    /// typed [`model::RequestError::EmptyToolCallName`] failure.
1392    Modify(ToolCall),
1393    /// Block execution with a nonempty hook reason.
1394    Block(String),
1395    /// Supply a closed result without execution.
1396    ShortCircuit(ToolResult),
1397}
1398
1399/// [`ToolHooks::before_tool_result`] decision.
1400#[derive(Debug)]
1401pub enum ToolResultDecision {
1402    /// Keep the current closed result.
1403    Continue,
1404    /// Replace the result before commit and publication.
1405    Modify(ToolResult),
1406}
1407
1408/// [`InputHooks::before_input_admit`] decision.
1409#[derive(Debug)]
1410pub enum InputAdmitDecision {
1411    /// Admit the claimed batch unchanged.
1412    Admit,
1413    /// Replace the claimed batch before append.
1414    Modify(Vec<Item>),
1415    /// Permanently discard the claimed batch with a reason.
1416    Reject(String),
1417}
1418
1419/// [`RunHooks::decide_stop`] decision and the sole hook-initiated stop surface.
1420#[derive(Debug)]
1421pub enum StopDecision {
1422    /// Continue toward the prospective Turn.
1423    Continue,
1424    /// Ask runtime to emit its unique validated `EventStop`.
1425    Stop(StopCode),
1426}
1427
1428/// [`TurnStepHooks::after_step`] decision.
1429#[derive(Debug)]
1430pub enum AfterStepDecision {
1431    /// Keep the Turn open and append the ordered items.
1432    Continue(Vec<Item>),
1433    /// Close the current Turn after appending the ordered items.
1434    ///
1435    /// This boundary decision takes precedence over queued work: a queued
1436    /// [`InputTarget::NextStep`] batch is not claimed and remains in the
1437    /// Session-owned mailbox for a later eligible boundary or successor Run.
1438    EndTurn(Vec<Item>),
1439}
1440
1441/// The ten lifecycle observation variants, mechanically paired with callbacks.
1442#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1443#[non_exhaustive]
1444pub enum LifecycleKind {
1445    /// `OnRunStart`.
1446    RunStart,
1447    /// `OnRunEnd`.
1448    RunEnd,
1449    /// `OnTurnStart`.
1450    TurnStart,
1451    /// `OnTurnEnd`.
1452    TurnEnd,
1453    /// `OnStepStart`.
1454    StepStart,
1455    /// `OnStepEnd`.
1456    StepEnd,
1457    /// `OnGenerationStart`.
1458    GenerationStart,
1459    /// `OnGenerationEnd`.
1460    GenerationEnd,
1461    /// `OnToolCallStart`.
1462    ToolCallStart,
1463    /// `OnToolCallEnd`.
1464    ToolCallEnd,
1465}
1466
1467/// A closed, internally consistent lifecycle terminal fact.
1468#[derive(Clone)]
1469#[non_exhaustive]
1470pub enum LifecycleEnd {
1471    /// Normal success.
1472    Completed,
1473    /// Consumer or explicit Run stop.
1474    #[non_exhaustive]
1475    Stopped {
1476        /// Optional opaque hook stop code; ordinary consumer stops have none.
1477        code: Option<StopCode>,
1478    },
1479    /// Parent cancellation or deadline.
1480    #[non_exhaustive]
1481    Cancelled {
1482        /// Authoritative cancellation detail.
1483        error: Arc<dyn Error + Send + Sync>,
1484    },
1485    /// Execution or contract failure.
1486    #[non_exhaustive]
1487    Failed {
1488        /// Authoritative failure detail.
1489        error: Arc<dyn Error + Send + Sync>,
1490    },
1491}
1492
1493impl fmt::Debug for LifecycleEnd {
1494    /// Names the ending and renders its cause through `Display`.
1495    ///
1496    /// The error is an arbitrary boxed failure supplied from outside this
1497    /// crate, so its `Debug` is neither written nor reviewed here; `Display` is
1498    /// the diagnostic the error type is contracted to produce, and it is what
1499    /// `HookError` already prints for the same reason.
1500    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1501        match self {
1502            Self::Completed => formatter.write_str("Completed"),
1503            Self::Stopped { code } => formatter
1504                .debug_struct("Stopped")
1505                .field("code", code)
1506                .finish(),
1507            Self::Cancelled { error } => formatter
1508                .debug_struct("Cancelled")
1509                .field("error", &error.to_string())
1510                .finish(),
1511            Self::Failed { error } => formatter
1512                .debug_struct("Failed")
1513                .field("error", &error.to_string())
1514                .finish(),
1515        }
1516    }
1517}
1518
1519impl LifecycleEnd {
1520    /// Returns the authoritative portable outcome.
1521    #[must_use]
1522    pub const fn outcome(&self) -> Outcome {
1523        match self {
1524            Self::Completed => Outcome::Completed,
1525            Self::Stopped { .. } => Outcome::Stopped,
1526            Self::Cancelled { .. } => Outcome::Cancelled,
1527            Self::Failed { .. } => Outcome::Failed,
1528        }
1529    }
1530
1531    /// Returns the optional explicit stop code.
1532    #[must_use]
1533    pub const fn stop_code(&self) -> Option<&StopCode> {
1534        match self {
1535            Self::Stopped { code } => code.as_ref(),
1536            Self::Completed | Self::Cancelled { .. } | Self::Failed { .. } => None,
1537        }
1538    }
1539
1540    /// Returns cancellation/failure detail when the outcome requires it.
1541    #[must_use]
1542    pub fn error(&self) -> Option<&(dyn Error + Send + Sync)> {
1543        match self {
1544            Self::Cancelled { error } | Self::Failed { error } => Some(error.as_ref()),
1545            Self::Completed | Self::Stopped { .. } => None,
1546        }
1547    }
1548}
1549
1550/// Closed progress reached by a `ToolCall` before its end observation.
1551///
1552/// The private representation makes a committed result without a value and completed
1553/// post-hooks without finalization unrepresentable.
1554///
1555/// ```compile_fail
1556/// use reef_core::runtime::{hook, tool};
1557/// let _ = hook::ToolCallProgress {
1558///     disposition: tool::CallDisposition::Executed,
1559/// };
1560/// ```
1561#[derive(Clone, Debug)]
1562pub struct ToolCallProgress {
1563    disposition: CallDisposition,
1564    state: ToolCallProgressState,
1565}
1566
1567#[derive(Clone, Debug)]
1568enum ToolCallProgressState {
1569    Observed,
1570    ResultAvailable(ToolResult),
1571    ResultCommitted(ToolResult),
1572    PostHooksCompleted(ToolResult),
1573}
1574
1575/// Public classification of the closed `ToolCall` progress.
1576#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1577#[non_exhaustive]
1578pub enum ToolCallProgressKind {
1579    /// The call ended before a closed result became available.
1580    Observed,
1581    /// A closed result exists but its enclosing batch is not yet durable.
1582    ResultAvailable,
1583    /// The enclosing result batch committed.
1584    ResultCommitted,
1585    /// Finalization and the post-execution hook phase both completed.
1586    PostHooksCompleted,
1587}
1588
1589impl ToolCallProgress {
1590    pub(crate) const fn observed(disposition: CallDisposition) -> Self {
1591        Self {
1592            disposition,
1593            state: ToolCallProgressState::Observed,
1594        }
1595    }
1596
1597    pub(crate) const fn result_available(disposition: CallDisposition, result: ToolResult) -> Self {
1598        Self {
1599            disposition,
1600            state: ToolCallProgressState::ResultAvailable(result),
1601        }
1602    }
1603
1604    pub(crate) const fn result_committed(disposition: CallDisposition, result: ToolResult) -> Self {
1605        Self {
1606            disposition,
1607            state: ToolCallProgressState::ResultCommitted(result),
1608        }
1609    }
1610
1611    pub(crate) const fn completed_post_hooks(
1612        disposition: CallDisposition,
1613        result: ToolResult,
1614    ) -> Self {
1615        Self {
1616            disposition,
1617            state: ToolCallProgressState::PostHooksCompleted(result),
1618        }
1619    }
1620
1621    /// Returns the furthest stable call disposition.
1622    #[must_use]
1623    pub const fn disposition(&self) -> CallDisposition {
1624        self.disposition
1625    }
1626
1627    /// Returns the closed progress classification.
1628    #[must_use]
1629    pub const fn kind(&self) -> ToolCallProgressKind {
1630        match self.state {
1631            ToolCallProgressState::Observed => ToolCallProgressKind::Observed,
1632            ToolCallProgressState::ResultAvailable(_) => ToolCallProgressKind::ResultAvailable,
1633            ToolCallProgressState::ResultCommitted(_) => ToolCallProgressKind::ResultCommitted,
1634            ToolCallProgressState::PostHooksCompleted(_) => {
1635                ToolCallProgressKind::PostHooksCompleted
1636            }
1637        }
1638    }
1639
1640    /// Returns the effective result once one became available.
1641    #[must_use]
1642    pub const fn result(&self) -> Option<&ToolResult> {
1643        match &self.state {
1644            ToolCallProgressState::Observed => None,
1645            ToolCallProgressState::ResultAvailable(result)
1646            | ToolCallProgressState::ResultCommitted(result)
1647            | ToolCallProgressState::PostHooksCompleted(result) => Some(result),
1648        }
1649    }
1650
1651    /// Reports whether the enclosing result batch is durable.
1652    #[must_use]
1653    pub const fn is_result_committed(&self) -> bool {
1654        matches!(
1655            self.state,
1656            ToolCallProgressState::ResultCommitted(_)
1657                | ToolCallProgressState::PostHooksCompleted(_)
1658        )
1659    }
1660
1661    /// Reports whether the post-execution hook phase completed after finalization.
1662    #[must_use]
1663    pub const fn post_hooks_completed(&self) -> bool {
1664        matches!(self.state, ToolCallProgressState::PostHooksCompleted(_))
1665    }
1666}
1667
1668/// Why a crate-internal `ToolCall` terminal fact was rejected.
1669#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1670pub(crate) enum ToolCallEndError {
1671    /// This disposition cannot reach the supplied result progress.
1672    InvalidDisposition {
1673        disposition: CallDisposition,
1674        progress: ToolCallProgressKind,
1675    },
1676    /// Normal completion requires the closed result and post-hook phase.
1677    CompletedBeforePostHooks(ToolCallProgressKind),
1678    /// A post-hook-complete call cannot carry a non-completed terminal state.
1679    PostHooksWithoutCompletion(Outcome),
1680}
1681
1682/// A validated, externally non-constructible `ToolCall` terminal observation.
1683///
1684/// ```compile_fail
1685/// use reef_core::runtime::hook;
1686/// let _ = hook::ToolCallEndObservation {};
1687/// ```
1688///
1689/// Crate-internal validation is deliberately not a public escape hatch:
1690///
1691/// ```compile_fail
1692/// use reef_core::runtime::hook;
1693/// let _ = hook::ToolCallEndObservation::try_new;
1694/// ```
1695#[derive(Clone, Debug)]
1696pub struct ToolCallEndObservation {
1697    coord: Coord,
1698    end: LifecycleEnd,
1699    original_call: ToolCall,
1700    effective_call: ToolCall,
1701    progress: ToolCallProgress,
1702}
1703
1704impl ToolCallEndObservation {
1705    pub(crate) fn try_new(
1706        coord: Coord,
1707        end: LifecycleEnd,
1708        original_call: ToolCall,
1709        effective_call: ToolCall,
1710        progress: ToolCallProgress,
1711    ) -> Result<Self, ToolCallEndError> {
1712        let progress_kind = progress.kind();
1713        let disposition = progress.disposition();
1714        let disposition_matches_progress = match progress_kind {
1715            ToolCallProgressKind::Observed => matches!(
1716                disposition,
1717                CallDisposition::Truncated | CallDisposition::NotExecuted
1718            ),
1719            ToolCallProgressKind::ResultAvailable
1720            | ToolCallProgressKind::ResultCommitted
1721            | ToolCallProgressKind::PostHooksCompleted => !matches!(
1722                disposition,
1723                CallDisposition::Truncated | CallDisposition::NotExecuted
1724            ),
1725        };
1726        if !disposition_matches_progress {
1727            return Err(ToolCallEndError::InvalidDisposition {
1728                disposition,
1729                progress: progress_kind,
1730            });
1731        }
1732
1733        match (&end, progress_kind) {
1734            (LifecycleEnd::Completed, ToolCallProgressKind::PostHooksCompleted) => {}
1735            (LifecycleEnd::Completed, incomplete) => {
1736                return Err(ToolCallEndError::CompletedBeforePostHooks(incomplete));
1737            }
1738            (
1739                LifecycleEnd::Stopped { .. }
1740                | LifecycleEnd::Cancelled { .. }
1741                | LifecycleEnd::Failed { .. },
1742                ToolCallProgressKind::PostHooksCompleted,
1743            ) => {
1744                return Err(ToolCallEndError::PostHooksWithoutCompletion(end.outcome()));
1745            }
1746            (
1747                LifecycleEnd::Stopped { .. }
1748                | LifecycleEnd::Cancelled { .. }
1749                | LifecycleEnd::Failed { .. },
1750                ToolCallProgressKind::Observed
1751                | ToolCallProgressKind::ResultAvailable
1752                | ToolCallProgressKind::ResultCommitted,
1753            ) => {}
1754        }
1755
1756        Ok(Self {
1757            coord,
1758            end,
1759            original_call,
1760            effective_call,
1761            progress,
1762        })
1763    }
1764
1765    /// Returns the exact ended `ToolCall` coordinate.
1766    #[must_use]
1767    pub const fn coord(&self) -> &Coord {
1768        &self.coord
1769    }
1770
1771    /// Returns the authoritative terminal state.
1772    #[must_use]
1773    pub const fn end(&self) -> &LifecycleEnd {
1774        &self.end
1775    }
1776
1777    /// Returns the original model-emitted call.
1778    #[must_use]
1779    pub const fn original_call(&self) -> &ToolCall {
1780        &self.original_call
1781    }
1782
1783    /// Returns the final effective call after successful rewrites.
1784    #[must_use]
1785    pub const fn effective_call(&self) -> &ToolCall {
1786        &self.effective_call
1787    }
1788
1789    /// Returns the closed result/finalization progress.
1790    #[must_use]
1791    pub const fn progress(&self) -> &ToolCallProgress {
1792        &self.progress
1793    }
1794}
1795
1796/// Complete immutable facts for exactly one lifecycle callback.
1797///
1798/// Every field is an owned value rather than a view, so an observer cannot see a
1799/// fact mutate under it and the producer needs no defensive copy.
1800#[derive(Clone, Debug)]
1801#[non_exhaustive]
1802pub enum LifecycleObservation {
1803    /// Prepared Run input at execution start.
1804    #[non_exhaustive]
1805    RunStart {
1806        /// Started Run coordinate.
1807        coord: Coord,
1808        /// Prepared input after all rewrites.
1809        input: Vec<Part>,
1810    },
1811    /// Authoritative Run terminal fact and entered Turn count.
1812    #[non_exhaustive]
1813    RunEnd {
1814        /// Ended Run coordinate.
1815        coord: Coord,
1816        /// Authoritative terminal state.
1817        end: LifecycleEnd,
1818        /// Number of Turns entered.
1819        turns: usize,
1820    },
1821    /// Input which opened a Turn.
1822    #[non_exhaustive]
1823    TurnStart {
1824        /// Started Turn coordinate.
1825        coord: Coord,
1826        /// Owned trigger batch.
1827        trigger: Vec<Item>,
1828    },
1829    /// Authoritative Turn terminal fact and entered Step count.
1830    #[non_exhaustive]
1831    TurnEnd {
1832        /// Ended Turn coordinate.
1833        coord: Coord,
1834        /// Authoritative terminal state.
1835        end: LifecycleEnd,
1836        /// Number of Steps entered.
1837        steps: usize,
1838    },
1839    /// Frozen snapshot used by a started Step.
1840    #[non_exhaustive]
1841    StepStart {
1842        /// Started Step coordinate.
1843        coord: Coord,
1844        /// Exact shared Step snapshot.
1845        snapshot: Arc<StepSnapshot>,
1846    },
1847    /// Authoritative Step terminal fact and the same frozen snapshot.
1848    #[non_exhaustive]
1849    StepEnd {
1850        /// Ended Step coordinate.
1851        coord: Coord,
1852        /// Authoritative terminal state.
1853        end: LifecycleEnd,
1854        /// Exact shared Step snapshot.
1855        snapshot: Arc<StepSnapshot>,
1856    },
1857    /// Exact frozen provider request.
1858    ///
1859    /// This observation has no [`event::Kind`] counterpart, and that is a
1860    /// decision rather than an omission: its payload is the whole frozen
1861    /// [`Request`], so publishing it outward would copy the projected history and
1862    /// the system instruction onto a stream a host may log, to tell a consumer
1863    /// something [`event::Kind::StepStart`] already tells it. See ADR-021.
1864    ///
1865    /// [`event::Kind`]: crate::runtime::event::Kind
1866    /// [`event::Kind::StepStart`]: crate::runtime::event::Kind::StepStart
1867    #[non_exhaustive]
1868    GenerationStart {
1869        /// Started Generation coordinate.
1870        coord: Coord,
1871        /// Exact request passed to the provider.
1872        request: Request,
1873    },
1874    /// Authoritative generation outcome plus provider completion facts.
1875    #[non_exhaustive]
1876    GenerationEnd {
1877        /// Ended Generation coordinate.
1878        coord: Coord,
1879        /// Authoritative terminal state.
1880        end: LifecycleEnd,
1881        /// Verbatim provider finish label, empty when no provider supplied one.
1882        finish_reason: String,
1883        /// Normalized provider-neutral completion reason.
1884        completion: CompletionReason,
1885    },
1886    /// Original model-emitted `ToolCall`.
1887    #[non_exhaustive]
1888    ToolCallStart {
1889        /// Started `ToolCall` coordinate.
1890        coord: Coord,
1891        /// Original frozen call.
1892        call: ToolCall,
1893    },
1894    /// Authoritative closed `ToolCall` outcome, rewrites, result, and progress.
1895    ToolCallEnd(ToolCallEndObservation),
1896}
1897
1898impl LifecycleObservation {
1899    /// Returns the callback variant without inspecting its payload.
1900    #[must_use]
1901    pub const fn kind(&self) -> LifecycleKind {
1902        match self {
1903            Self::RunStart { .. } => LifecycleKind::RunStart,
1904            Self::RunEnd { .. } => LifecycleKind::RunEnd,
1905            Self::TurnStart { .. } => LifecycleKind::TurnStart,
1906            Self::TurnEnd { .. } => LifecycleKind::TurnEnd,
1907            Self::StepStart { .. } => LifecycleKind::StepStart,
1908            Self::StepEnd { .. } => LifecycleKind::StepEnd,
1909            Self::GenerationStart { .. } => LifecycleKind::GenerationStart,
1910            Self::GenerationEnd { .. } => LifecycleKind::GenerationEnd,
1911            Self::ToolCallStart { .. } => LifecycleKind::ToolCallStart,
1912            Self::ToolCallEnd(_) => LifecycleKind::ToolCallEnd,
1913        }
1914    }
1915
1916    /// Returns the exact coordinate carried by the producer.
1917    #[must_use]
1918    pub const fn coord(&self) -> &Coord {
1919        match self {
1920            Self::RunStart { coord, .. }
1921            | Self::RunEnd { coord, .. }
1922            | Self::TurnStart { coord, .. }
1923            | Self::TurnEnd { coord, .. }
1924            | Self::StepStart { coord, .. }
1925            | Self::StepEnd { coord, .. }
1926            | Self::GenerationStart { coord, .. }
1927            | Self::GenerationEnd { coord, .. }
1928            | Self::ToolCallStart { coord, .. } => coord,
1929            Self::ToolCallEnd(observation) => observation.coord(),
1930        }
1931    }
1932}
1933
1934/// Immutable transcript mutation fact passed before the live commit.
1935#[derive(Clone, Debug)]
1936#[non_exhaustive]
1937pub enum TranscriptMutation {
1938    /// One ordered append batch and its proposed committed version.
1939    #[non_exhaustive]
1940    Append {
1941        /// Version observed before the mutation.
1942        previous: Version,
1943        /// Version proposed after the mutation.
1944        version: Version,
1945        /// Complete owned append batch.
1946        items: Vec<Item>,
1947    },
1948    /// One complete replacement and its proposed committed snapshot.
1949    #[non_exhaustive]
1950    Replace {
1951        /// Version observed before the mutation.
1952        previous: Version,
1953        /// Complete immutable replacement snapshot.
1954        snapshot: Snapshot,
1955    },
1956}
1957
1958impl TranscriptMutation {
1959    /// Returns the version observed before reservation.
1960    #[must_use]
1961    pub const fn previous_version(&self) -> Version {
1962        match self {
1963            Self::Append { previous, .. } | Self::Replace { previous, .. } => *previous,
1964        }
1965    }
1966
1967    /// Returns the proposed post-commit version.
1968    #[must_use]
1969    pub const fn version(&self) -> Version {
1970        match self {
1971            Self::Append { version, .. } => *version,
1972            Self::Replace { snapshot, .. } => snapshot.version(),
1973        }
1974    }
1975
1976    /// Returns the immutable mutation payload.
1977    #[must_use]
1978    pub fn items(&self) -> &[Item] {
1979        match self {
1980            Self::Append { items, .. } => items,
1981            Self::Replace { snapshot, .. } => snapshot.items(),
1982        }
1983    }
1984
1985    /// Returns the complete proposed snapshot for a replacement.
1986    #[must_use]
1987    pub const fn replacement(&self) -> Option<&Snapshot> {
1988        match self {
1989            Self::Append { .. } => None,
1990            Self::Replace { snapshot, .. } => Some(snapshot),
1991        }
1992    }
1993}
1994
1995/// A successful pre-commit reservation whose publication cannot fail.
1996///
1997/// A reservation is resolved exactly once, and both resolutions consume the box
1998/// so no code path can publish an aborted reservation or abort a published one.
1999/// The controller decides which resolution applies: any pre-commit failure
2000/// aborts every held reservation in reverse acquisition order, and a successful
2001/// commit publishes every held reservation in acquisition order and never
2002/// aborts. Publication is contractually infallible, which is what makes a held
2003/// reservation safe to publish after the commit has already succeeded.
2004pub trait TranscriptReservation: Send {
2005    /// Publishes the already-committed fact; consuming `self` forbids abort after publish.
2006    ///
2007    /// The live transcript mutation has already linearized when this runs, so an
2008    /// implementation must not fail. A panic is isolated by the controller, which
2009    /// still publishes every remaining reservation.
2010    fn publish(self: Box<Self>);
2011
2012    /// Releases a reservation that will never be committed.
2013    ///
2014    /// The controller calls this only before the live commit, so an
2015    /// implementation must not assume the mutation became visible. Releasing
2016    /// nothing is the default, because a reservation that holds no external
2017    /// resource has nothing to undo.
2018    fn abort(self: Box<Self>) {}
2019}
2020
2021/// Run-phase hooks.
2022///
2023/// The three boundaries of a Run itself: what it starts with, whether it takes
2024/// another Turn, and what it does when it would otherwise finish.
2025/// [`compose_continuation`](RunHooks::compose_continuation) is how an agent keeps
2026/// going — returning more input continues the Run, returning nothing ends it —
2027/// so a Run that should do more than one turn needs this family.
2028///
2029/// ```
2030/// use std::sync::Arc;
2031/// use std::sync::atomic::{AtomicUsize, Ordering};
2032///
2033/// use reef_core::runtime::{event, hook};
2034///
2035/// /// Stops the Run after a fixed number of completed Turns.
2036/// struct TurnBudget {
2037///     remaining: AtomicUsize,
2038/// }
2039///
2040/// impl TurnBudget {
2041///     fn completed_turn(&self) -> hook::StopDecision {
2042///         let remaining = self.remaining.fetch_update(
2043///             Ordering::SeqCst,
2044///             Ordering::SeqCst,
2045///             |remaining| remaining.checked_sub(1),
2046///         ).unwrap_or(0);
2047///         if remaining > 1 {
2048///             hook::StopDecision::Continue
2049///         } else {
2050///             // Stop after the configured number of completed Turns. Zero also
2051///             // stops here without wrapping the counter to `usize::MAX`.
2052///             hook::StopDecision::Stop(event::StopCode::new("turn-budget".to_owned()).unwrap())
2053///         }
2054///     }
2055/// }
2056///
2057/// impl hook::RunHooks for TurnBudget {
2058///     fn prepare(&self, _scope: &hook::PrepareScope<'_>) -> hook::HookResult<hook::PrepareDecision> {
2059///         // `Continue` keeps what the caller submitted. `Modify` replaces it,
2060///         // and may not replace it with nothing.
2061///         Ok(hook::PrepareDecision::Continue)
2062///     }
2063///
2064///     fn compose_continuation(&self, _scope: &hook::ContinuationScope<'_>) -> hook::HookResult<hook::ContinuationDecision> {
2065///         Ok(hook::ContinuationDecision::Keep)
2066///     }
2067///
2068///     fn decide_stop(&self, _scope: &hook::StopDecisionScope<'_>) -> hook::HookResult<hook::StopDecision> {
2069///         Ok(self.completed_turn())
2070///     }
2071/// }
2072///
2073/// let budget = TurnBudget { remaining: AtomicUsize::new(4) };
2074/// for _ in 0..3 {
2075///     assert!(matches!(budget.completed_turn(), hook::StopDecision::Continue));
2076/// }
2077/// assert!(matches!(budget.completed_turn(), hook::StopDecision::Stop(_)));
2078/// let exhausted = TurnBudget { remaining: AtomicUsize::new(0) };
2079/// assert!(matches!(exhausted.completed_turn(), hook::StopDecision::Stop(_)));
2080/// assert_eq!(exhausted.remaining.load(Ordering::SeqCst), 0);
2081///
2082/// let mut hooks = hook::RegistryBuilder::new();
2083/// hooks.register(hook::Registration::new("turn-budget".to_owned()).run(Arc::new(TurnBudget {
2084///     remaining: AtomicUsize::new(4),
2085/// })));
2086/// ```
2087pub trait RunHooks: Send + Sync {
2088    /// Composes initial input before admission.
2089    ///
2090    /// # Errors
2091    ///
2092    /// Return one when this registration cannot decide what the Run's initial
2093    /// input should be — a required piece of context it could not load, or an
2094    /// input it judges inadmissible. This is the one hook whose failure is
2095    /// reported to the caller synchronously rather than through a Run:
2096    /// [`Agent::start`](crate::runtime::agent::Agent::start) returns
2097    /// [`StartError::Prepare`](crate::runtime::agent::StartError::Prepare) and no
2098    /// Run comes into existence, so it is also the only place a hook can refuse
2099    /// a Run outright instead of ending one.
2100    ///
2101    /// Reef adds one error of its own here: returning
2102    /// [`PrepareDecision::Modify`] with an empty replacement is refused as
2103    /// [`PrepareError::EmptyModify`], attributed to this registration. Composing
2104    /// nothing is [`PrepareDecision::Continue`]; deleting what the caller
2105    /// submitted is not an option, because the admitted input is also the
2106    /// transcript's record of it.
2107    ///
2108    /// See [`HookError`](HookError#effect-on-the-run) for what a failure costs.
2109    fn prepare(&self, scope: &PrepareScope<'_>) -> HookResult<PrepareDecision>;
2110
2111    /// Composes a natural-completion continuation.
2112    ///
2113    /// # Errors
2114    ///
2115    /// Return one when this registration cannot decide whether the Run should
2116    /// continue. Note that it does not need to fail in order to *stop* the Run:
2117    /// [`ContinuationDecision::Replace`] with an empty continuation ends it normally,
2118    /// which is a governance answer rather than a failure. An error here ends the
2119    /// Run as failed instead, discarding the continuation every earlier
2120    /// registration had composed.
2121    ///
2122    /// See [`HookError`](HookError#effect-on-the-run).
2123    fn compose_continuation(
2124        &self,
2125        scope: &ContinuationScope<'_>,
2126    ) -> HookResult<ContinuationDecision>;
2127
2128    /// Decides whether a prospective Turn may exist.
2129    ///
2130    /// # Errors
2131    ///
2132    /// Return one when this registration cannot decide, rather than when it
2133    /// decides against another Turn: refusing a Turn is
2134    /// [`StopDecision::Stop`], which ends the Run normally carrying a stop
2135    /// code a consumer can read. An error ends it as failed and publishes no stop
2136    /// at all.
2137    ///
2138    /// See [`HookError`](HookError#effect-on-the-run).
2139    fn decide_stop(&self, scope: &StopDecisionScope<'_>) -> HookResult<StopDecision>;
2140}
2141
2142/// Injected-input admission hook.
2143///
2144/// Mid-run input arrives through
2145/// [`Session::input_mailbox`](crate::runtime::session::Session::input_mailbox)
2146/// and is claimed at the boundary it targeted. This is the one chance to rewrite
2147/// or refuse a claimed batch before it becomes a transcript record.
2148///
2149/// ```
2150/// use std::sync::Arc;
2151///
2152/// use reef_core::runtime::hook;
2153///
2154/// /// Refuses injected input once the conversation is long enough.
2155/// struct Doorman;
2156///
2157/// impl hook::InputHooks for Doorman {
2158///     fn before_input_admit(&self, scope: &hook::InputAdmitScope<'_>) -> hook::InputAdmitDecision {
2159///         if scope.items().is_empty() {
2160///             // A rejection must say why; an empty reason is refused.
2161///             hook::InputAdmitDecision::Reject("nothing to admit".to_owned())
2162///         } else {
2163///             hook::InputAdmitDecision::Admit
2164///         }
2165///     }
2166/// }
2167///
2168/// let registration = hook::Registration::new("doorman".to_owned()).input(Arc::new(Doorman));
2169/// # let _ = registration;
2170/// ```
2171pub trait InputHooks: Send + Sync {
2172    /// Rewrites, admits, or permanently rejects one claimed batch.
2173    fn before_input_admit(&self, scope: &InputAdmitScope<'_>) -> InputAdmitDecision;
2174}
2175
2176/// Turn and Step boundary hooks.
2177///
2178/// Four boundaries inside a Run. [`before_step`](TurnStepHooks::before_step) is
2179/// the only place with a writable [`crate::runtime::model::RequestPlan`],
2180/// so it is where per-request material goes — a compaction policy rewrites
2181/// history here, and a status line goes into the plan's ephemeral lane, which
2182/// reaches the model without ever becoming a record.
2183///
2184/// ```
2185/// use std::sync::Arc;
2186///
2187/// use reef_core::runtime::hook;
2188/// use reef_core::transcript::item;
2189/// use reef_core::value::content;
2190///
2191/// /// Adds one volatile line to every request, and nothing to the transcript.
2192/// struct StatusLine;
2193///
2194/// impl hook::TurnStepHooks for StatusLine {
2195///     fn before_turn(&self, _scope: &hook::TurnScope<'_>) -> hook::HookResult<Vec<item::Item>> {
2196///         Ok(Vec::new())
2197///     }
2198///
2199///     fn after_turn(&self, _scope: &hook::TurnScope<'_>) -> hook::HookResult<Vec<item::Item>> {
2200///         Ok(Vec::new())
2201///     }
2202///
2203///     fn before_step(&self, scope: &mut hook::BeforeStepScope<'_>) -> hook::HookResult<Vec<item::Item>> {
2204///         scope
2205///             .plan()
2206///             .push_ephemeral(content::Part::text("[battery: 42%]".to_owned()));
2207///         Ok(Vec::new())
2208///     }
2209///
2210///     fn after_step(&self, _scope: &hook::AfterStepScope<'_>) -> hook::HookResult<hook::AfterStepDecision> {
2211///         Ok(hook::AfterStepDecision::Continue(Vec::new()))
2212///     }
2213/// }
2214///
2215/// let registration = hook::Registration::new("status".to_owned()).turn_step(Arc::new(StatusLine));
2216/// # let _ = registration;
2217/// ```
2218pub trait TurnStepHooks: Send + Sync {
2219    /// Runs before the Turn lifecycle starts.
2220    ///
2221    /// # Errors
2222    ///
2223    /// Return one when this registration cannot produce the items the Turn should
2224    /// open with. The Turn is never opened: the items every earlier registration
2225    /// contributed are discarded together with this one's, so the transcript
2226    /// records no half-composed Turn opening.
2227    ///
2228    /// See [`HookError`](HookError#effect-on-the-run).
2229    fn before_turn(&self, scope: &TurnScope<'_>) -> HookResult<Vec<Item>>;
2230
2231    /// Runs after ordinary Turn work and before its end observer.
2232    ///
2233    /// # Errors
2234    ///
2235    /// Return one when this registration cannot produce the items that should
2236    /// close the Turn. Nothing this boundary composed is appended. The Turn's work
2237    /// is already committed by this point, so the Run fails with a complete Turn
2238    /// behind it and no closing items — not with a partially closed Turn.
2239    ///
2240    /// See [`HookError`](HookError#effect-on-the-run).
2241    fn after_turn(&self, scope: &TurnScope<'_>) -> HookResult<Vec<Item>>;
2242
2243    /// Runs in registration order over the sole writable `RequestPlan`.
2244    ///
2245    /// # Errors
2246    ///
2247    /// Return one when this registration cannot prepare the Step — most often
2248    /// because the request material it needed to add is unavailable. The Step
2249    /// never freezes, so no model call is made, and the plan edits earlier
2250    /// registrations had already applied are dropped along with this one's. That
2251    /// is the reason a partial plan is not worth rescuing: the registrations after
2252    /// this one never saw it.
2253    ///
2254    /// See [`HookError`](HookError#effect-on-the-run).
2255    fn before_step(&self, scope: &mut BeforeStepScope<'_>) -> HookResult<Vec<Item>>;
2256
2257    /// Runs after ordinary Step work and may close its Turn.
2258    ///
2259    /// # Errors
2260    ///
2261    /// Return one when this registration cannot decide how the Step should close.
2262    /// Closing the Turn is not a failure — that is
2263    /// [`AfterStepDecision::EndTurn`] — so an error here means the decision itself
2264    /// could not be made. Neither the items nor the end-of-Turn decisions
2265    /// collected at this boundary are applied.
2266    ///
2267    /// See [`HookError`](HookError#effect-on-the-run).
2268    fn after_step(&self, scope: &AfterStepScope<'_>) -> HookResult<AfterStepDecision>;
2269}
2270
2271/// Model boundary hooks.
2272///
2273/// The two sides of one generation: the request before it is sent, and the
2274/// assistant record before it is committed. This is where a composition layer
2275/// normalises history for the provider it is about to call — core never rewrites
2276/// a segment because a different provider produced it.
2277///
2278/// ```
2279/// use std::sync::Arc;
2280///
2281/// use reef_core::runtime::hook;
2282///
2283/// /// Refuses to call the model at all after a cutoff.
2284/// struct Circuit {
2285///     open: std::sync::atomic::AtomicBool,
2286/// }
2287///
2288/// impl hook::ModelHooks for Circuit {
2289///     fn before_model(&self, _scope: &hook::BeforeModelScope<'_>) -> hook::HookResult<hook::BeforeModelDecision> {
2290///         use std::sync::atomic::Ordering;
2291///         Ok(if self.open.load(Ordering::SeqCst) {
2292///             // Declining to call the model is a decision, not a failure.
2293///             hook::BeforeModelDecision::Abort("circuit open".to_owned())
2294///         } else {
2295///             hook::BeforeModelDecision::Continue
2296///         })
2297///     }
2298///
2299///     fn after_model(&self, _scope: &hook::AfterModelScope<'_>) -> hook::AfterModelDecision {
2300///         hook::AfterModelDecision::Continue
2301///     }
2302/// }
2303///
2304/// let registration = hook::Registration::new("circuit".to_owned()).model(Arc::new(Circuit {
2305///     open: std::sync::atomic::AtomicBool::new(false),
2306/// }));
2307/// # let _ = registration;
2308/// ```
2309pub trait ModelHooks: Send + Sync {
2310    /// Controls one immutable model request.
2311    ///
2312    /// # Errors
2313    ///
2314    /// Return one when this registration cannot produce the request it wanted to
2315    /// send. Declining to call the model is not a failure — that is
2316    /// [`BeforeModelDecision::ShortCircuit`], which supplies the output itself, or
2317    /// [`BeforeModelDecision::Abort`], which states a reason — and neither is
2318    /// rewriting the request, which is [`BeforeModelDecision::Modify`]. An error is
2319    /// for the case where the rewrite itself could not be built, most commonly
2320    /// because
2321    /// re-freezing the modified history through
2322    /// [`RequestPlan::try_into_request`](crate::runtime::model::RequestPlan::try_into_request)
2323    /// returned a [`RequestError`](crate::runtime::model::RequestError) this
2324    /// registration cannot resolve.
2325    ///
2326    /// No model call is made and no generation is recorded; rewrites from earlier
2327    /// registrations are discarded with this one's.
2328    ///
2329    /// See [`HookError`](HookError#effect-on-the-run).
2330    fn before_model(&self, scope: &BeforeModelScope<'_>) -> HookResult<BeforeModelDecision>;
2331
2332    /// Rewrites successfully assembled output before commit.
2333    fn after_model(&self, scope: &AfterModelScope<'_>) -> AfterModelDecision;
2334}
2335
2336/// Tool boundary hooks.
2337///
2338/// This is the synchronous policy plane over tool calls. It sees the call before
2339/// execution and may rewrite, block, or answer it directly.
2340///
2341/// ```
2342/// use std::sync::Arc;
2343///
2344/// use reef_core::runtime::hook;
2345/// use reef_core::transcript::item;
2346///
2347/// /// Blocks one tool by name, without touching the rest.
2348/// struct Policy;
2349///
2350/// impl hook::ToolHooks for Policy {
2351///     fn before_tool_call(&self, scope: &hook::ToolCallScope<'_>) -> hook::HookResult<hook::ToolCallDecision> {
2352///         Ok(if scope.call().name().as_str() == "shell.exec" {
2353///             // A block is an ordinary business result the model reads, not a
2354///             // failure: an `Err` here would fail the whole batch.
2355///             hook::ToolCallDecision::Block("shell is disabled".to_owned())
2356///         } else {
2357///             hook::ToolCallDecision::Continue
2358///         })
2359///     }
2360///
2361///     fn before_tool_result(&self, _scope: &hook::ToolResultScope<'_>) -> hook::HookResult<hook::ToolResultDecision> {
2362///         Ok(hook::ToolResultDecision::Continue)
2363///     }
2364///
2365///     fn after_tool_commit(&self, _scope: &hook::AfterToolCommitScope<'_>) -> Vec<item::Item> {
2366///         Vec::new()
2367///     }
2368/// }
2369///
2370/// let registration = hook::Registration::new("policy".to_owned()).tool(Arc::new(Policy));
2371/// # let _ = registration;
2372/// ```
2373///
2374/// # Cooperative synchronous callback contract
2375///
2376/// These callbacks are trusted, synchronous, and cooperative. An implementation
2377/// must not block forever, wait for work that requires the same runtime thread to
2378/// advance, or catch a runtime-internal abort unwind and then continue external
2379/// side effects. Reef retains and joins every callback owner on normal, error, and
2380/// strong-delivery abort paths, but does not claim to forcibly terminate a
2381/// malicious or permanently blocked synchronous callback.
2382///
2383/// ## How a broken one looks from outside, and who to blame
2384///
2385/// Breaking that contract produces neither an error nor a panic, so it is worth
2386/// knowing the shape it does produce. A [`Self::after_tool_commit`] that never
2387/// returns leaves a thread blocked inside a destructor during teardown: the run
2388/// joins the callback it promised to join, waits for a completion that is not
2389/// coming, and never releases. The Run does not fail — it stops finishing.
2390///
2391/// Nothing in the process reports which registration is responsible, because a
2392/// diagnostic emitted from a destructor would have to be a panic during unwinding
2393/// or a library writing to stderr, and this crate does neither. What is available
2394/// instead is a backtrace: `after_tool_commit` is the only callback that runs on
2395/// Tokio's blocking pool, and the registrations are invoked one after another
2396/// rather than concurrently, so at most one is in flight and the blocking thread's
2397/// own stack names the implementing type. A *panic* at this boundary is attributed
2398/// by registration name and needs no backtrace; a hang is the case that does.
2399pub trait ToolHooks: Send + Sync {
2400    /// Rewrites, blocks, or short-circuits before execution.
2401    ///
2402    /// # Errors
2403    ///
2404    /// Return one when this registration cannot decide about the call. Refusing a
2405    /// call is not a failure: [`ToolCallDecision::Block`] stops it with a reason and
2406    /// [`ToolCallDecision::ShortCircuit`] answers it directly, and both produce an
2407    /// ordinary business result that enters the batch like any other. An error
2408    /// instead fails the **whole batch**, not just this call, because the batch
2409    /// commits atomically and a batch missing one call's decision cannot be
2410    /// committed at all.
2411    ///
2412    /// A registration that cannot fail returns `Ok` unconditionally.
2413    ///
2414    /// See [`HookError`](HookError#effect-on-the-run).
2415    fn before_tool_call(&self, scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision>;
2416
2417    /// Rewrites every closed result before commit.
2418    ///
2419    /// # Errors
2420    ///
2421    /// Return one when this registration cannot produce the result it intended to
2422    /// commit. Rewriting a result, including into a business error, is
2423    /// [`ToolResultDecision::Modify`] rather than a failure. An error fails the batch
2424    /// commit, so the assistant record and every result in the batch stay
2425    /// uncommitted — which is what keeps a rejected rewrite from leaving a call
2426    /// nobody answered in the transcript.
2427    ///
2428    /// See [`HookError`](HookError#effect-on-the-run).
2429    fn before_tool_result(&self, scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision>;
2430
2431    /// Appends after an executed batch is durable; this late hook cannot fail it.
2432    ///
2433    /// Each emitted fact is a synchronous strong-acceptance rendezvous. Rejection,
2434    /// consumer abandonment, invalid facts, or channel closure aborts the callback.
2435    /// The callback must not swallow that internal abort and continue side effects;
2436    /// Reef nevertheless revokes this invocation's Session-state writer before
2437    /// releasing the abort rendezvous, so subsequent state writes fail closed.
2438    fn after_tool_commit(&self, scope: &AfterToolCommitScope<'_>) -> Vec<Item>;
2439}
2440
2441/// Passive hooks isolated at the exact callback invocation boundary.
2442///
2443/// An observer watches and decides nothing, which is what makes it the family a
2444/// budget, a metric or a log belongs in — and
2445/// [`model_event`](ObserverHooks::model_event) is the only route token usage has
2446/// out of the runtime at all.
2447///
2448/// ```
2449/// use std::sync::Arc;
2450/// use std::sync::atomic::{AtomicU64, Ordering};
2451///
2452/// use reef_core::runtime::{model, hook};
2453///
2454/// /// Counts tokens, and observes nothing else.
2455/// #[derive(Default)]
2456/// struct Budget {
2457///     spent: AtomicU64,
2458/// }
2459///
2460/// impl hook::ObserverHooks for Budget {
2461///     fn model_event(&self, _scope: &hook::ObserverScope<'_>, event: &model::Event) {
2462///         // Usage is incremental, so adding it up is exact.
2463///         if let model::Event::Usage(usage) = event {
2464///             self.spent.fetch_add(usage.total, Ordering::SeqCst);
2465///         }
2466///     }
2467/// }
2468///
2469/// let registration = hook::Registration::new("budget".to_owned())
2470///     .observer(Arc::new(Budget::default()));
2471/// # let _ = registration;
2472/// ```
2473///
2474/// # Every method has a default, and this is the only hook family where one does
2475///
2476/// An observation returns nothing and decides nothing: reef does exactly the
2477/// same thing whether a registration watched a boundary or not. Not overriding a
2478/// method here therefore *means* "I do not watch that", which is the honest
2479/// reading of an empty body, and the cost of forgetting one falls entirely on
2480/// the registration that forgot — it sees less than it meant to, in its own
2481/// output, and no other registration and no Run behaves differently.
2482///
2483/// Every other hook family stays fully required, deliberately. Those return a
2484/// decision reef then applies, so a default would have to *pick a policy* —
2485/// allow the call, keep the request, continue the Run — and a registration that
2486/// meant to gate a tool call but misspelled the method would compile into one
2487/// that permits every call. That is the failure this crate designs against
2488/// everywhere else, which is why its enums are exhaustive, why authorisation is
2489/// a compile-time ladder, and why no decision type implements `Default`. A
2490/// silently defaulted decision is that `Default` reached by another route.
2491///
2492/// This is not a deadline that has passed: adding a default body to a required
2493/// method compiles for every existing implementor, so any hook here can gain one
2494/// later on evidence rather than on speculation.
2495pub trait ObserverHooks: Send + Sync {
2496    /// Observes synchronous Run admission without emission.
2497    ///
2498    /// The default observes nothing.
2499    fn run_admitted(&self, scope: &ReadScope<'_>) {
2500        let _ = scope;
2501    }
2502
2503    /// Observes one closed lifecycle fact.
2504    ///
2505    /// The default observes nothing.
2506    fn lifecycle(&self, observation: &LifecycleObservation, scope: &ObserverScope<'_>) {
2507        let _ = (observation, scope);
2508    }
2509
2510    /// Observes provider usage/done facts.
2511    ///
2512    /// This is the only route [`model::Event::Usage`] has to a hook, so a
2513    /// budget or accounting policy overrides this one and leaves the rest.
2514    ///
2515    /// The default observes nothing.
2516    fn model_event(&self, scope: &ObserverScope<'_>, event: &model::Event) {
2517        let _ = (scope, event);
2518    }
2519
2520    /// Observes an audit fact inside the serialized outward boundary.
2521    ///
2522    /// The default observes nothing.
2523    fn audit_event(&self, scope: &ReadScope<'_>, event: &audit::Event) {
2524        let _ = (scope, event);
2525    }
2526}
2527
2528/// Transcript reservation hook.
2529///
2530/// The seam a durable journal is built on. Every transcript mutation is offered
2531/// here *before* it linearizes: a registration that can promise to publish
2532/// returns a [`TranscriptReservation`], and one that cannot returns an error,
2533/// which aborts the mutation with nothing written. Publication afterwards cannot
2534/// fail, so a hook that must not lose a record does its risky work — the
2535/// write-ahead, the lock, the capacity check — inside `reserve`.
2536///
2537/// [`TranscriptMutation::items`] exposes the complete owned transcript values,
2538/// including segment signatures, raw payloads and provider data. This is the
2539/// persistence rail for a byte-faithful resumable Session; the outward event stream
2540/// is an earlier, lossy observation projection and is not a substitute. With the
2541/// `serde` feature, serializing these values also serializes credential-tier
2542/// provider tokens, so the composition layer must protect its destination as the
2543/// [crate-level `Serialization` section](crate#serialization) describes.
2544///
2545/// ```
2546/// use std::sync::Arc;
2547///
2548/// use reef_core::runtime::hook;
2549///
2550/// /// Writes ahead, then publishes what it wrote.
2551/// struct Journal;
2552///
2553/// struct Reserved {
2554///     version: u64,
2555/// }
2556///
2557/// impl hook::TranscriptReservation for Reserved {
2558///     fn publish(self: Box<Self>) {
2559///         // The mutation has linearized. This cannot fail and must not.
2560///         let _durable = self.version;
2561///     }
2562///
2563///     fn abort(self: Box<Self>) {
2564///         // The mutation never happened; release what `reserve` took.
2565///     }
2566/// }
2567///
2568/// impl hook::TranscriptHooks for Journal {
2569///     fn reserve(
2570///         &self,
2571///         _scope: &hook::ReadScope<'_>,
2572///         mutation: &hook::TranscriptMutation,
2573///     ) -> hook::HookResult<Box<dyn hook::TranscriptReservation>> {
2574///         Ok(Box::new(Reserved { version: mutation.version().as_u64() }))
2575///     }
2576/// }
2577///
2578/// let registration = hook::Registration::new("journal".to_owned()).transcript(Arc::new(Journal));
2579/// # let _ = registration;
2580/// ```
2581pub trait TranscriptHooks: Send + Sync {
2582    /// Reserves one immutable mutation before live commit.
2583    ///
2584    /// # Errors
2585    ///
2586    /// Return one when this registration cannot promise to publish the mutation.
2587    /// That is the whole question this hook asks: everything that can go wrong must
2588    /// go wrong *here*, because [`TranscriptReservation::publish`] runs after the
2589    /// commit has linearized and is contractually infallible. A registration that
2590    /// needs to write ahead, take a lock, or reserve capacity does it now and
2591    /// returns an error if it cannot.
2592    ///
2593    /// A failure aborts every reservation this transaction already held, in reverse
2594    /// acquisition order, and the compare-and-set never runs — so the transcript is
2595    /// unchanged and no peer is left holding a reservation for a mutation that never
2596    /// happened. Registrations after this one are not called.
2597    ///
2598    /// Because a reservation failure fails the mutation rather than a callback
2599    /// phase, the Run's [`FailureKind`](crate::runtime::run::FailureKind) is
2600    /// [`Transcript`](crate::runtime::run::FailureKind::Transcript) or
2601    /// [`ToolCommit`](crate::runtime::run::FailureKind::ToolCommit) rather than
2602    /// [`Hook`](crate::runtime::run::FailureKind::Hook), even though this
2603    /// registration's name is still attached to the cause. At Run admission it is
2604    /// [`StartError::Prepare`](crate::runtime::agent::StartError::Prepare) instead.
2605    ///
2606    /// See [`HookError`](HookError#effect-on-the-run).
2607    fn reserve(
2608        &self,
2609        scope: &ReadScope<'_>,
2610        mutation: &TranscriptMutation,
2611    ) -> HookResult<Box<dyn TranscriptReservation>>;
2612}
2613
2614/// Agent teardown is deliberately separate from all 27 runtime callbacks.
2615///
2616/// It is the only hook that runs outside a Run, and the only one whose failure
2617/// costs nothing else: [`Agent::close`](crate::runtime::agent::Agent::close)
2618/// invokes every registration's `close` in registration order regardless of what
2619/// the others did, and reports the failures together.
2620///
2621/// ```
2622/// use std::sync::Arc;
2623/// use std::sync::atomic::{AtomicBool, Ordering};
2624///
2625/// use reef_core::runtime::hook;
2626///
2627/// /// Releases something the hook opened, exactly once.
2628/// #[derive(Default)]
2629/// struct Connection {
2630///     closed: AtomicBool,
2631/// }
2632///
2633/// impl hook::AgentTeardown for Connection {
2634///     fn close(&self) -> hook::HookResult<()> {
2635///         self.closed.store(true, Ordering::SeqCst);
2636///         Ok(())
2637///     }
2638/// }
2639///
2640/// let registration = hook::Registration::new("connection".to_owned())
2641///     .teardown(Arc::new(Connection::default()));
2642/// # let _ = registration;
2643/// ```
2644pub trait AgentTeardown: Send + Sync {
2645    /// Releases hook-owned external resources.
2646    ///
2647    /// # Errors
2648    ///
2649    /// Return one when a resource could not be released cleanly — a connection
2650    /// that would not drain, a flush that failed. This is the one fallible hook
2651    /// whose failure does **not** short-circuit anything: teardown is the last
2652    /// thing that happens, so every registration's `close` runs in registration
2653    /// order regardless, and the failures are collected rather than raced. A peer
2654    /// that would have released a file handle still gets to.
2655    ///
2656    /// [`Agent::close`](crate::runtime::agent::Agent::close) reports them together
2657    /// as [`CloseError::Hooks`](crate::runtime::agent::CloseError::Hooks), whose
2658    /// [`TeardownError::entries`](crate::runtime::agent::TeardownError::entries)
2659    /// lists every failure in registration order with its hook's name. That
2660    /// result is cached, so a repeated close returns the same failures rather than
2661    /// running teardown again — an error here is final, not a retry request. A
2662    /// panicking `close` is caught at this boundary and reported the same way.
2663    ///
2664    /// The Agent is closed either way. There is no Run left for a failure here to
2665    /// affect, which is why [`HookError`](HookError#effect-on-the-run)'s Run
2666    /// consequences do not apply.
2667    fn close(&self) -> HookResult<()>;
2668}
2669
2670/// One named hook's family registrations and state-access metadata.
2671pub struct Registration {
2672    name: String,
2673    requires_session_state: bool,
2674    run: Option<Arc<dyn RunHooks>>,
2675    input: Option<Arc<dyn InputHooks>>,
2676    turn_step: Option<Arc<dyn TurnStepHooks>>,
2677    model: Option<Arc<dyn ModelHooks>>,
2678    tool: Option<Arc<dyn ToolHooks>>,
2679    observer: Option<Arc<dyn ObserverHooks>>,
2680    transcript: Option<Arc<dyn TranscriptHooks>>,
2681    teardown: Option<Arc<dyn AgentTeardown>>,
2682}
2683
2684impl fmt::Debug for Registration {
2685    /// Names the hook and states which hook families it actually claimed.
2686    ///
2687    /// Every hook is a trait object with no `Debug`, and presence is the whole
2688    /// of what a registration decides: which of the eight families this hook
2689    /// will be dispatched into.
2690    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2691        formatter
2692            .debug_struct("Registration")
2693            .field("name", &self.name)
2694            .field("requires_session_state", &self.requires_session_state)
2695            .field("run", &Presence(self.run.is_some()))
2696            .field("input", &Presence(self.input.is_some()))
2697            .field("turn_step", &Presence(self.turn_step.is_some()))
2698            .field("model", &Presence(self.model.is_some()))
2699            .field("tool", &Presence(self.tool.is_some()))
2700            .field("observer", &Presence(self.observer.is_some()))
2701            .field("transcript", &Presence(self.transcript.is_some()))
2702            .field("teardown", &Presence(self.teardown.is_some()))
2703            .finish()
2704    }
2705}
2706
2707impl Registration {
2708    /// Begins one named registration.
2709    #[must_use]
2710    pub fn new(name: String) -> Self {
2711        Self {
2712            name,
2713            requires_session_state: false,
2714            run: None,
2715            input: None,
2716            turn_step: None,
2717            model: None,
2718            tool: None,
2719            observer: None,
2720            transcript: None,
2721            teardown: None,
2722        }
2723    }
2724
2725    /// Declares use of optional successor-Run Session state.
2726    #[must_use]
2727    pub const fn requires_session_state(mut self, required: bool) -> Self {
2728        self.requires_session_state = required;
2729        self
2730    }
2731
2732    /// Mounts the Run family.
2733    #[must_use]
2734    pub fn run(mut self, hooks: Arc<dyn RunHooks>) -> Self {
2735        self.run = Some(hooks);
2736        self
2737    }
2738
2739    /// Mounts the input-admission family.
2740    #[must_use]
2741    pub fn input(mut self, hooks: Arc<dyn InputHooks>) -> Self {
2742        self.input = Some(hooks);
2743        self
2744    }
2745
2746    /// Mounts the Turn/Step family.
2747    #[must_use]
2748    pub fn turn_step(mut self, hooks: Arc<dyn TurnStepHooks>) -> Self {
2749        self.turn_step = Some(hooks);
2750        self
2751    }
2752
2753    /// Mounts the model family.
2754    #[must_use]
2755    pub fn model(mut self, hooks: Arc<dyn ModelHooks>) -> Self {
2756        self.model = Some(hooks);
2757        self
2758    }
2759
2760    /// Mounts the tool family.
2761    #[must_use]
2762    pub fn tool(mut self, hooks: Arc<dyn ToolHooks>) -> Self {
2763        self.tool = Some(hooks);
2764        self
2765    }
2766
2767    /// Mounts passive observers.
2768    #[must_use]
2769    pub fn observer(mut self, hooks: Arc<dyn ObserverHooks>) -> Self {
2770        self.observer = Some(hooks);
2771        self
2772    }
2773
2774    /// Mounts transcript reservation.
2775    #[must_use]
2776    pub fn transcript(mut self, hooks: Arc<dyn TranscriptHooks>) -> Self {
2777        self.transcript = Some(hooks);
2778        self
2779    }
2780
2781    /// Mounts Agent teardown separately from runtime families.
2782    #[must_use]
2783    pub fn teardown(mut self, hooks: Arc<dyn AgentTeardown>) -> Self {
2784        self.teardown = Some(hooks);
2785        self
2786    }
2787}
2788
2789struct RegisteredHook {
2790    registration: Registration,
2791}
2792
2793/// One family hook with its immutable registration metadata.
2794///
2795/// The index is the original registry position, not a dense family-local index,
2796/// so controllers can key independent per-registration Run state and callback
2797/// transactions without losing registrations that omitted this family.
2798pub(crate) struct RegistrationAdapter<'a, H: ?Sized> {
2799    index: usize,
2800    name: &'a str,
2801    requires_session_state: bool,
2802    hook: &'a H,
2803}
2804
2805/// Owned tool adapter used only by managed blocking callback owners.
2806pub(crate) struct OwnedToolRegistrationAdapter {
2807    index: usize,
2808    name: String,
2809    requires_session_state: bool,
2810    hook: Arc<dyn ToolHooks>,
2811}
2812
2813impl<'a, H: ?Sized> RegistrationAdapter<'a, H> {
2814    pub(crate) const fn index(&self) -> usize {
2815        self.index
2816    }
2817
2818    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
2819    pub(crate) const fn name(&self) -> &'a str {
2820        self.name
2821    }
2822
2823    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
2824    pub(crate) const fn requires_session_state(&self) -> bool {
2825        self.requires_session_state
2826    }
2827
2828    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
2829    pub(crate) const fn hook(&self) -> &'a H {
2830        self.hook
2831    }
2832}
2833
2834impl OwnedToolRegistrationAdapter {
2835    pub(crate) const fn index(&self) -> usize {
2836        self.index
2837    }
2838
2839    pub(crate) fn name(&self) -> &str {
2840        &self.name
2841    }
2842
2843    pub(crate) fn invoke_after_tool_commit(
2844        &self,
2845        resources: CallbackResources<'_>,
2846        staged: &StagedTranscript,
2847        snapshot: &Arc<StepSnapshot>,
2848        result: &ToolResult,
2849    ) -> Vec<Item> {
2850        RegistrationAdapter {
2851            index: self.index,
2852            name: &self.name,
2853            requires_session_state: self.requires_session_state,
2854            hook: &*self.hook,
2855        }
2856        .invoke_after_tool_commit(resources, staged, snapshot, result)
2857    }
2858}
2859
2860/// Caller-owned resources for exactly one registration callback invocation.
2861///
2862/// A controller must create a fresh `run_state::Store` per registration and a fresh
2863/// `StagedTranscript` per callback. This bundle deliberately carries neither a
2864/// registry nor commit authority; the controller decides whether successful
2865/// staged work is committed and always discards failed callback stages.
2866#[derive(Clone, Copy)]
2867pub(crate) struct CallbackResources<'a> {
2868    coord: &'a Coord,
2869    run_state: &'a run_state::Store,
2870    session_state: &'a session_state::Reader,
2871    session_state_writer: Option<&'a session_state::Writer>,
2872    emitter: &'a dyn Emitter,
2873}
2874
2875/// Owned aliases of one registration's state capabilities.
2876///
2877/// These handles preserve the same slots and lease authority; they do not copy
2878/// state and never escape the crate-managed callback owner.
2879pub(crate) struct OwnedCallbackResources {
2880    run_state: run_state::Store,
2881    session_state: session_state::Reader,
2882    session_state_writer: Option<session_state::Writer>,
2883    callback_write_permit: Option<CallbackWritePermit>,
2884}
2885
2886impl OwnedCallbackResources {
2887    /// Clones the runtime-owned half of this callback's write permit.
2888    pub(crate) fn callback_write_permit(&self) -> Option<CallbackWritePermit> {
2889        self.callback_write_permit.clone()
2890    }
2891
2892    pub(crate) fn bind<'a>(
2893        &'a self,
2894        coord: &'a Coord,
2895        emitter: &'a dyn Emitter,
2896    ) -> CallbackResources<'a> {
2897        CallbackResources::new(
2898            coord,
2899            &self.run_state,
2900            &self.session_state,
2901            self.session_state_writer.as_ref(),
2902            emitter,
2903        )
2904    }
2905}
2906
2907impl<'a> CallbackResources<'a> {
2908    pub(crate) const fn new(
2909        coord: &'a Coord,
2910        run_state: &'a run_state::Store,
2911        session_state: &'a session_state::Reader,
2912        session_state_writer: Option<&'a session_state::Writer>,
2913        emitter: &'a dyn Emitter,
2914    ) -> Self {
2915        Self {
2916            coord,
2917            run_state,
2918            session_state,
2919            session_state_writer,
2920            emitter,
2921        }
2922    }
2923
2924    /// Clones only crate-private capability handles for a managed callback owner.
2925    ///
2926    /// A writable registration receives a fresh callback-local permit. The async
2927    /// owner retains the matching revocation handle, so aborting one callback does
2928    /// not revoke the registration's ordinary lease writer or any later callback.
2929    pub(crate) fn owned_handles(self) -> OwnedCallbackResources {
2930        let (session_state_writer, callback_write_permit) = match self.session_state_writer {
2931            Some(writer) => {
2932                let (writer, permit) = writer.clone_with_callback_permit();
2933                (Some(writer), Some(permit))
2934            }
2935            None => (None, None),
2936        };
2937        OwnedCallbackResources {
2938            run_state: self.run_state.clone_handle(),
2939            session_state: self.session_state.clone_handle(),
2940            session_state_writer,
2941            callback_write_permit,
2942        }
2943    }
2944
2945    /// Rebinds only the callback coordinate while preserving this registration's
2946    /// private state and capability resources.
2947    pub(crate) const fn with_coord<'b>(self, coord: &'b Coord) -> CallbackResources<'b>
2948    where
2949        'a: 'b,
2950    {
2951        self.rebind(coord, self.emitter)
2952    }
2953
2954    /// Rebinds one callback to its exact coordinate and outward emitter.
2955    ///
2956    /// Synchronous adapters use this crate-private bridge when only coordinate or
2957    /// emitter identity changes. Managed blocking callbacks instead bind the owned
2958    /// aliases above. Registration-private state capabilities remain unchanged.
2959    pub(crate) const fn rebind<'b>(
2960        self,
2961        coord: &'b Coord,
2962        emitter: &'b dyn Emitter,
2963    ) -> CallbackResources<'b>
2964    where
2965        'a: 'b,
2966    {
2967        CallbackResources {
2968            coord,
2969            run_state: self.run_state,
2970            session_state: self.session_state,
2971            session_state_writer: self.session_state_writer,
2972            emitter,
2973        }
2974    }
2975
2976    const fn scope_factory(
2977        self,
2978        requires_session_state: bool,
2979        transcript: TranscriptSource<'a>,
2980    ) -> ScopeFactory<'a> {
2981        ScopeFactory::new(
2982            self.coord,
2983            self.run_state,
2984            self.session_state,
2985            self.session_state_writer,
2986            requires_session_state,
2987            transcript,
2988            self.emitter,
2989        )
2990    }
2991}
2992
2993impl RegistrationAdapter<'_, dyn RunHooks> {
2994    /// Invokes only this registration's [`RunHooks::prepare`] callback.
2995    ///
2996    /// The caller supplies registration-private Run state plus callback-local
2997    /// Session-state and transcript overlays. Neither overlay is committed or
2998    /// discarded here; the caller owns resolution after observing this result.
2999    ///
3000    /// A returned [`PrepareDecision::Modify`] is validated here rather than by
3001    /// the caller, because this is the only frame that still knows *which*
3002    /// registration produced it: an empty replacement becomes a
3003    /// [`PrepareError::EmptyModify`] attributed to that name.
3004    pub(crate) fn invoke_prepare(
3005        &self,
3006        resources: CallbackResources<'_>,
3007        staged: &StagedTranscript,
3008        session_state_stage: Option<&session_state::StagedWriter>,
3009        base_snapshot: &Snapshot,
3010        input: &[Part],
3011        cancellation: &Token,
3012    ) -> Result<PrepareDecision, DispatchError> {
3013        if cancellation.is_cancelled() {
3014            return Err(DispatchError::Cancelled);
3015        }
3016        let factory = resources.scope_factory(
3017            self.requires_session_state,
3018            TranscriptSource::Reader(&staged.reader),
3019        );
3020        let scope = factory.prepare(staged, session_state_stage, base_snapshot, input);
3021        match self.hook.prepare(&scope) {
3022            Err(error) => Err(DispatchError::Callback(AttributedError {
3023                name: self.name.to_owned(),
3024                error,
3025            })),
3026            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3027            Ok(PrepareDecision::Modify(replacement)) if replacement.is_empty() => {
3028                Err(DispatchError::Callback(AttributedError {
3029                    name: self.name.to_owned(),
3030                    error: HookError::new(PrepareError::EmptyModify),
3031                }))
3032            }
3033            Ok(decision) => Ok(decision),
3034        }
3035    }
3036
3037    /// Invokes only this registration's [`RunHooks::compose_continuation`] callback.
3038    ///
3039    /// The decision governs a continuation request: a non-empty request asks the
3040    /// loop for another Turn rather than ending the Run. `continuation` carries
3041    /// what earlier registrations already asked for, so a registration can see,
3042    /// extend, replace or ignore it.
3043    ///
3044    /// Unlike [`RegistrationAdapter::invoke_prepare`] this validates nothing: an
3045    /// empty [`ContinuationDecision::Replace`] is a deliberate veto of a peer's
3046    /// request, not a rewrite that discards user content.
3047    pub(crate) fn invoke_compose_continuation(
3048        &self,
3049        resources: CallbackResources<'_>,
3050        staged: &StagedTranscript,
3051        continuation: &[Part],
3052        continuations: usize,
3053        turns: usize,
3054        cancellation: &Token,
3055    ) -> Result<ContinuationDecision, DispatchError> {
3056        if cancellation.is_cancelled() {
3057            return Err(DispatchError::Cancelled);
3058        }
3059        let factory = resources.scope_factory(
3060            self.requires_session_state,
3061            TranscriptSource::Reader(&staged.reader),
3062        );
3063        let scope = factory.compose_continuation(staged, continuation, continuations, turns);
3064        match self.hook.compose_continuation(&scope) {
3065            Err(error) => Err(DispatchError::Callback(AttributedError {
3066                name: self.name.to_owned(),
3067                error,
3068            })),
3069            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3070            Ok(decision) => Ok(decision),
3071        }
3072    }
3073
3074    /// Invokes only this registration's [`RunHooks::decide_stop`] callback.
3075    ///
3076    /// This is the sole surface through which a hook may stop a Run with a
3077    /// code; the loop converts a stopping decision into the single privately
3078    /// owned `EventStop` (ADR-007).
3079    pub(crate) fn invoke_decide_stop(
3080        &self,
3081        resources: CallbackResources<'_>,
3082        transcript: &SnapshotReader,
3083        cancellation: &Token,
3084    ) -> Result<StopDecision, DispatchError> {
3085        if cancellation.is_cancelled() {
3086            return Err(DispatchError::Cancelled);
3087        }
3088        let factory = resources.scope_factory(
3089            self.requires_session_state,
3090            TranscriptSource::Reader(transcript),
3091        );
3092        let scope = factory.decide_stop();
3093        match self.hook.decide_stop(&scope) {
3094            Err(error) => Err(DispatchError::Callback(AttributedError {
3095                name: self.name.to_owned(),
3096                error,
3097            })),
3098            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3099            Ok(decision) => Ok(decision),
3100        }
3101    }
3102}
3103
3104impl RegistrationAdapter<'_, dyn TurnStepHooks> {
3105    /// Invokes only this registration's `OnBeforeTurn` callback.
3106    ///
3107    /// `trigger` is what opened this Turn — the admitted Run input, a claimed
3108    /// `NextTurn` batch, or a continuation an earlier
3109    /// [`RunHooks::compose_continuation`] asked for.
3110    /// The returned items are appended before the Turn's first Step.
3111    pub(crate) fn invoke_before_turn(
3112        &self,
3113        resources: CallbackResources<'_>,
3114        staged: &StagedTranscript,
3115        trigger: &[Item],
3116        cancellation: &Token,
3117    ) -> Result<Vec<Item>, DispatchError> {
3118        self.invoke_turn(resources, staged, trigger, cancellation, TurnHook::Before)
3119    }
3120
3121    /// Invokes only this registration's `OnAfterTurn` callback.
3122    pub(crate) fn invoke_after_turn(
3123        &self,
3124        resources: CallbackResources<'_>,
3125        staged: &StagedTranscript,
3126        trigger: &[Item],
3127        cancellation: &Token,
3128    ) -> Result<Vec<Item>, DispatchError> {
3129        self.invoke_turn(resources, staged, trigger, cancellation, TurnHook::After)
3130    }
3131
3132    /// Runs one Turn-boundary callback.
3133    ///
3134    /// Both boundaries take the same scope and return the same shape, so the
3135    /// cancellation and attribution rules exist once and cannot drift apart.
3136    fn invoke_turn(
3137        &self,
3138        resources: CallbackResources<'_>,
3139        staged: &StagedTranscript,
3140        trigger: &[Item],
3141        cancellation: &Token,
3142        boundary: TurnHook,
3143    ) -> Result<Vec<Item>, DispatchError> {
3144        if cancellation.is_cancelled() {
3145            return Err(DispatchError::Cancelled);
3146        }
3147        let factory = resources.scope_factory(
3148            self.requires_session_state,
3149            TranscriptSource::Reader(&staged.reader),
3150        );
3151        let scope = factory.turn(staged, trigger);
3152        let result = match boundary {
3153            TurnHook::Before => self.hook.before_turn(&scope),
3154            TurnHook::After => self.hook.after_turn(&scope),
3155        };
3156        match result {
3157            Err(error) => Err(DispatchError::Callback(AttributedError {
3158                name: self.name.to_owned(),
3159                error,
3160            })),
3161            Ok(_items) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3162            Ok(items) => Ok(items),
3163        }
3164    }
3165
3166    /// Invokes only this registration's `OnAfterStep` callback.
3167    ///
3168    /// The decision decides whether the Turn continues past this Step; the items
3169    /// it carries are appended either way.
3170    pub(crate) fn invoke_after_step(
3171        &self,
3172        resources: CallbackResources<'_>,
3173        staged: &StagedTranscript,
3174        snapshot: &Arc<StepSnapshot>,
3175        cancellation: &Token,
3176    ) -> Result<AfterStepDecision, DispatchError> {
3177        if cancellation.is_cancelled() {
3178            return Err(DispatchError::Cancelled);
3179        }
3180        let factory = resources.scope_factory(
3181            self.requires_session_state,
3182            TranscriptSource::Reader(&staged.reader),
3183        );
3184        let scope = factory.after_step(staged, snapshot);
3185        match self.hook.after_step(&scope) {
3186            Err(error) => Err(DispatchError::Callback(AttributedError {
3187                name: self.name.to_owned(),
3188                error,
3189            })),
3190            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3191            Ok(decision) => Ok(decision),
3192        }
3193    }
3194
3195    /// Invokes only this registration's `OnBeforeStep` callback.
3196    ///
3197    /// The caller supplies registration-private Run state, a lease-bound writer,
3198    /// and a callback-local staged transcript. This method has no authority to
3199    /// commit that staged transcript into the live Session.
3200    pub(crate) fn invoke_before_step(
3201        &self,
3202        resources: CallbackResources<'_>,
3203        staged: &StagedTranscript,
3204        model: &Info,
3205        plan: &mut RequestPlan,
3206        cancellation: &Token,
3207    ) -> Result<Vec<Item>, DispatchError> {
3208        if cancellation.is_cancelled() {
3209            return Err(DispatchError::Cancelled);
3210        }
3211        let factory = resources.scope_factory(
3212            self.requires_session_state,
3213            TranscriptSource::Reader(&staged.reader),
3214        );
3215        let mut scope = factory.before_step(staged, model, plan);
3216        match self.hook.before_step(&mut scope) {
3217            Err(error) => Err(DispatchError::Callback(AttributedError {
3218                name: self.name.to_owned(),
3219                error,
3220            })),
3221            Ok(_items) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3222            Ok(items) => Ok(items),
3223        }
3224    }
3225}
3226
3227impl RegistrationAdapter<'_, dyn ObserverHooks> {
3228    /// Invokes only this registration's lifecycle observer.
3229    ///
3230    /// Callback audits are buffered locally. Buffer flushes and core panic
3231    /// audits remain outside the catch boundary, so core panics propagate.
3232    pub(crate) fn invoke_lifecycle(
3233        &self,
3234        resources: CallbackResources<'_>,
3235        transcript: TranscriptSource<'_>,
3236        snapshot: Option<&Arc<StepSnapshot>>,
3237        observation: &LifecycleObservation,
3238    ) {
3239        let factory = resources.scope_factory(self.requires_session_state, transcript);
3240        let pending = CallbackAuditBuffer::new();
3241        let scope = factory.observer(snapshot);
3242        let buffered_scope = scope.with_audit_sink(&pending);
3243        let panicked = match catch_unwind(AssertUnwindSafe(|| {
3244            self.hook.lifecycle(observation, &buffered_scope);
3245        })) {
3246            Ok(()) => false,
3247            Err(payload) => {
3248                std::mem::forget(payload);
3249                true
3250            }
3251        };
3252        pending.flush_to(resources.emitter);
3253        if panicked {
3254            emit_observer_panic(
3255                resources.emitter,
3256                self.name,
3257                lifecycle_hook_name(observation.kind()),
3258            );
3259        }
3260    }
3261
3262    /// Invokes only this registration's synchronous admission observer.
3263    pub(crate) fn invoke_run_admitted(
3264        &self,
3265        resources: CallbackResources<'_>,
3266        transcript: &SnapshotReader,
3267    ) {
3268        let factory = resources.scope_factory(
3269            self.requires_session_state,
3270            TranscriptSource::Reader(transcript),
3271        );
3272        let scope = factory.read();
3273        let panicked = match catch_unwind(AssertUnwindSafe(|| self.hook.run_admitted(&scope))) {
3274            Ok(()) => false,
3275            Err(payload) => {
3276                std::mem::forget(payload);
3277                true
3278            }
3279        };
3280        if panicked {
3281            emit_observer_panic(resources.emitter, self.name, "OnRunAdmitted");
3282        }
3283    }
3284
3285    /// Invokes only this registration's model-event observer.
3286    pub(crate) fn invoke_model_event(
3287        &self,
3288        resources: CallbackResources<'_>,
3289        transcript: &Snapshot,
3290        snapshot: Option<&Arc<StepSnapshot>>,
3291        event: &model::Event,
3292    ) {
3293        let factory = resources.scope_factory(
3294            self.requires_session_state,
3295            TranscriptSource::Snapshot(transcript),
3296        );
3297        let pending = CallbackAuditBuffer::new();
3298        let scope = factory.observer(snapshot);
3299        let buffered_scope = scope.with_audit_sink(&pending);
3300        let panicked = match catch_unwind(AssertUnwindSafe(|| {
3301            self.hook.model_event(&buffered_scope, event);
3302        })) {
3303            Ok(()) => false,
3304            Err(payload) => {
3305                std::mem::forget(payload);
3306                true
3307            }
3308        };
3309        pending.flush_to(resources.emitter);
3310        if panicked {
3311            emit_observer_panic(resources.emitter, self.name, "OnModelEvent");
3312        }
3313    }
3314
3315    /// Invokes only this registration's serialized audit observer.
3316    pub(crate) fn invoke_audit_event(
3317        &self,
3318        resources: CallbackResources<'_>,
3319        transcript: &SnapshotReader,
3320        event: &audit::Event,
3321    ) {
3322        let factory = resources.scope_factory(
3323            self.requires_session_state,
3324            TranscriptSource::Reader(transcript),
3325        );
3326        let scope = factory.read();
3327        let panicked = match catch_unwind(AssertUnwindSafe(|| self.hook.audit_event(&scope, event)))
3328        {
3329            Ok(()) => false,
3330            Err(payload) => {
3331                std::mem::forget(payload);
3332                true
3333            }
3334        };
3335        if panicked {
3336            emit_observer_panic(resources.emitter, self.name, "OnAuditEvent");
3337        }
3338    }
3339}
3340
3341impl RegistrationAdapter<'_, dyn InputHooks> {
3342    /// Invokes only this registration's `OnBeforeInputAdmit` callback.
3343    ///
3344    /// `OnBeforeInputAdmit` is infallible by trait shape, so cancellation is the
3345    /// only dispatch failure. The pre-callback check fails the claimed batch
3346    /// rather than admitting new work after cancellation.
3347    pub(crate) fn invoke_before_input_admit(
3348        &self,
3349        resources: CallbackResources<'_>,
3350        transcript: &SnapshotReader,
3351        target: InputTarget,
3352        items: &[Item],
3353        cancellation: &Token,
3354    ) -> Result<InputAdmitDecision, DispatchError> {
3355        if cancellation.is_cancelled() {
3356            return Err(DispatchError::Cancelled);
3357        }
3358        let factory = resources.scope_factory(
3359            self.requires_session_state,
3360            TranscriptSource::Reader(transcript),
3361        );
3362        let scope = factory.input_admit(target, items);
3363        let decision = self.hook.before_input_admit(&scope);
3364        if cancellation.is_cancelled() {
3365            return Err(DispatchError::Cancelled);
3366        }
3367        Ok(decision)
3368    }
3369}
3370
3371fn validate_hook_assistant(
3372    registration: &str,
3373    assistant: &Assistant,
3374    snapshot: &StepSnapshot,
3375) -> Result<(), DispatchError> {
3376    // `Step::advance` in runtime/driver.rs freezes this transcript immediately
3377    // before formal RequestPlan validation. Reusing model.rs's projection and
3378    // global identity walk here keeps hook output on that same request grammar
3379    // while retaining the producing registration's attribution frame.
3380    model::validate_assistant(assistant, snapshot.tools().transcript().items()).map_err(|error| {
3381        DispatchError::Callback(AttributedError {
3382            name: registration.to_owned(),
3383            error: HookError::new(error),
3384        })
3385    })
3386}
3387
3388impl RegistrationAdapter<'_, dyn ModelHooks> {
3389    /// Invokes only this registration's `OnBeforeModel` callback.
3390    ///
3391    /// A real callback error outranks a concurrently observed cancellation, so
3392    /// the cancellation re-check runs only on the `Ok` path.
3393    pub(crate) fn invoke_before_model(
3394        &self,
3395        resources: CallbackResources<'_>,
3396        snapshot: &Arc<StepSnapshot>,
3397        request: &Request,
3398        cancellation: &Token,
3399    ) -> Result<BeforeModelDecision, DispatchError> {
3400        if cancellation.is_cancelled() {
3401            return Err(DispatchError::Cancelled);
3402        }
3403        let factory = resources.scope_factory(
3404            self.requires_session_state,
3405            TranscriptSource::Snapshot(snapshot.tools().transcript()),
3406        );
3407        let scope = factory.before_model(snapshot, request);
3408        match self.hook.before_model(&scope) {
3409            Err(error) => Err(DispatchError::Callback(AttributedError {
3410                name: self.name.to_owned(),
3411                error,
3412            })),
3413            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3414            Ok(decision) => {
3415                if let BeforeModelDecision::ShortCircuit(assistant) = &decision {
3416                    validate_hook_assistant(self.name, assistant, snapshot)?;
3417                }
3418                Ok(decision)
3419            }
3420        }
3421    }
3422
3423    /// Invokes only this registration's `OnAfterModel` callback.
3424    #[expect(
3425        clippy::too_many_arguments,
3426        reason = "OnAfterModel observes five independent frozen model facts plus its resources"
3427    )]
3428    pub(crate) fn invoke_after_model(
3429        &self,
3430        resources: CallbackResources<'_>,
3431        snapshot: &Arc<StepSnapshot>,
3432        output: &Assistant,
3433        generated: bool,
3434        finish_reason: &str,
3435        completion: CompletionReason,
3436        cancellation: &Token,
3437    ) -> Result<AfterModelDecision, DispatchError> {
3438        if cancellation.is_cancelled() {
3439            return Err(DispatchError::Cancelled);
3440        }
3441        let factory = resources.scope_factory(
3442            self.requires_session_state,
3443            TranscriptSource::Snapshot(snapshot.tools().transcript()),
3444        );
3445        let scope = factory.after_model(snapshot, output, generated, finish_reason, completion);
3446        let decision = self.hook.after_model(&scope);
3447        if cancellation.is_cancelled() {
3448            return Err(DispatchError::Cancelled);
3449        }
3450        if let AfterModelDecision::Modify(assistant) = &decision {
3451            validate_hook_assistant(self.name, assistant, snapshot)?;
3452        }
3453        Ok(decision)
3454    }
3455}
3456
3457impl RegistrationAdapter<'_, dyn ToolHooks> {
3458    /// Invokes only this registration's `OnBeforeToolCall` callback.
3459    ///
3460    /// This rewrite plane runs strictly before execution, which therefore sees
3461    /// the final effective call. Validation remains
3462    /// in this registration frame so an empty effective name is a typed,
3463    /// registration-attributed failure rather than a later coordinate panic.
3464    pub(crate) fn invoke_before_tool_call(
3465        &self,
3466        resources: CallbackResources<'_>,
3467        snapshot: &Arc<StepSnapshot>,
3468        call: &ToolCall,
3469        cancellation: &Token,
3470    ) -> Result<ToolCallDecision, DispatchError> {
3471        if cancellation.is_cancelled() {
3472            return Err(DispatchError::Cancelled);
3473        }
3474        let factory = resources.scope_factory(
3475            self.requires_session_state,
3476            TranscriptSource::Snapshot(snapshot.tools().transcript()),
3477        );
3478        let scope = factory.tool_call(snapshot, call);
3479        match self.hook.before_tool_call(&scope) {
3480            Err(error) => Err(DispatchError::Callback(AttributedError {
3481                name: self.name.to_owned(),
3482                error,
3483            })),
3484            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3485            Ok(ToolCallDecision::Modify(modified)) if modified.name().as_str().is_empty() => {
3486                Err(DispatchError::Callback(AttributedError {
3487                    name: self.name.to_owned(),
3488                    error: HookError::new(model::RequestError::EmptyToolCallName {
3489                        call_id: call.id().as_str().to_owned(),
3490                    }),
3491                }))
3492            }
3493            Ok(decision) => Ok(decision),
3494        }
3495    }
3496
3497    /// Invokes only this registration's `OnBeforeToolResult` callback.
3498    ///
3499    /// Each rewrite is observed by the next registration, so the committed
3500    /// append, the outward result event, and the `ToolCall` end observation all
3501    /// report the same output.
3502    pub(crate) fn invoke_before_tool_result(
3503        &self,
3504        resources: CallbackResources<'_>,
3505        snapshot: &Arc<StepSnapshot>,
3506        call: &ToolCall,
3507        disposition: CallDisposition,
3508        result: &ToolResult,
3509        cancellation: &Token,
3510    ) -> Result<ToolResultDecision, DispatchError> {
3511        if cancellation.is_cancelled() {
3512            return Err(DispatchError::Cancelled);
3513        }
3514        let factory = resources.scope_factory(
3515            self.requires_session_state,
3516            TranscriptSource::Snapshot(snapshot.tools().transcript()),
3517        );
3518        let scope = factory.tool_result(snapshot, call, disposition, result);
3519        match self.hook.before_tool_result(&scope) {
3520            Err(error) => Err(DispatchError::Callback(AttributedError {
3521                name: self.name.to_owned(),
3522                error,
3523            })),
3524            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3525            Ok(decision) => Ok(decision),
3526        }
3527    }
3528
3529    /// Invokes only this registration's [`ToolHooks::after_tool_commit`] callback.
3530    ///
3531    /// The result batch is already durable at this boundary, so this late hook
3532    /// cannot fail the batch and takes no cancellation token: cancelling here
3533    /// would drop items that belong to an already-committed batch.
3534    pub(crate) fn invoke_after_tool_commit(
3535        &self,
3536        resources: CallbackResources<'_>,
3537        staged: &StagedTranscript,
3538        snapshot: &Arc<StepSnapshot>,
3539        result: &ToolResult,
3540    ) -> Vec<Item> {
3541        let factory = resources.scope_factory(
3542            self.requires_session_state,
3543            TranscriptSource::Reader(&staged.reader),
3544        );
3545        let scope = factory.after_tool_commit(staged, snapshot, result);
3546        self.hook.after_tool_commit(&scope)
3547    }
3548}
3549
3550impl RegistrationAdapter<'_, dyn TranscriptHooks> {
3551    /// Invokes only this registration's `OnTranscriptMutation` callback.
3552    ///
3553    /// The callback runs inside the controller's single pre-commit critical
3554    /// section and therefore receives a [`ReadScope`], which cannot re-enter the
3555    /// commit path or the outward boundary. Returning the reservation to
3556    /// the caller keeps abort/publish authority with the controller.
3557    pub(crate) fn invoke_reserve(
3558        &self,
3559        resources: CallbackResources<'_>,
3560        transcript: &Snapshot,
3561        mutation: &TranscriptMutation,
3562    ) -> Result<Box<dyn TranscriptReservation>, DispatchError> {
3563        let factory = resources.scope_factory(
3564            self.requires_session_state,
3565            TranscriptSource::Snapshot(transcript),
3566        );
3567        let scope = factory.read();
3568        self.hook.reserve(&scope, mutation).map_err(|error| {
3569            DispatchError::Callback(AttributedError {
3570                name: self.name.to_owned(),
3571                error,
3572            })
3573        })
3574    }
3575}
3576
3577/// Fail-closed hook-roster error reported by [`crate::runtime::agent::Agent::new`].
3578#[derive(Clone, Debug, Eq, PartialEq)]
3579#[non_exhaustive]
3580pub enum RegistryError {
3581    /// A hook name was empty.
3582    EmptyName,
3583    /// A hook name appeared more than once.
3584    DuplicateName(String),
3585}
3586
3587impl fmt::Display for RegistryError {
3588    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3589        match self {
3590            Self::EmptyName => formatter.write_str("hook name must be non-empty"),
3591            Self::DuplicateName(name) => write!(formatter, "duplicate hook name: {name}"),
3592        }
3593    }
3594}
3595
3596impl Error for RegistryError {}
3597
3598/// One callback failure attributed to its stable registration name.
3599#[derive(Clone, Debug)]
3600pub struct AttributedError {
3601    name: String,
3602    error: HookError,
3603}
3604
3605impl AttributedError {
3606    /// Returns the hook registration name.
3607    #[must_use]
3608    pub fn name(&self) -> &str {
3609        &self.name
3610    }
3611
3612    /// Returns the unflattened callback error.
3613    #[must_use]
3614    pub const fn error(&self) -> &HookError {
3615        &self.error
3616    }
3617}
3618
3619impl fmt::Display for AttributedError {
3620    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3621        write!(formatter, "hook {} failed: {}", self.name, self.error)
3622    }
3623}
3624
3625impl Error for AttributedError {
3626    fn source(&self) -> Option<&(dyn Error + 'static)> {
3627        Some(&self.error)
3628    }
3629}
3630
3631/// Which of the two Turn-boundary callbacks one dispatch runs.
3632#[derive(Clone, Copy)]
3633enum TurnHook {
3634    Before,
3635    After,
3636}
3637
3638/// Mutating dispatch failure with callback errors distinct from cancellation.
3639#[derive(Clone, Debug)]
3640#[non_exhaustive]
3641pub(crate) enum DispatchError {
3642    /// A real callback failed and outranks a concurrently observed cancellation.
3643    Callback(AttributedError),
3644    /// Cancellation was observed after the preceding callback returned normally.
3645    Cancelled,
3646}
3647
3648impl fmt::Display for DispatchError {
3649    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3650        match self {
3651            Self::Callback(failure) => write!(
3652                formatter,
3653                "hook {} failed: {}",
3654                failure.name(),
3655                failure.error()
3656            ),
3657            Self::Cancelled => formatter.write_str("cancelled around a callback"),
3658        }
3659    }
3660}
3661
3662impl Error for DispatchError {
3663    /// Returns the attributed callback failure, chain intact.
3664    ///
3665    /// The immediate cause is the [`AttributedError`], not the [`HookError`]
3666    /// inside it. Returning the inner error directly would drop the one link
3667    /// that carries the registration name, so a caller walking the chain could
3668    /// read the failure but never learn which hook produced it. The name is
3669    /// not recoverable from anything below, and `AttributedError` yields the
3670    /// callback error from its own `source`, so nothing deeper is lost.
3671    ///
3672    /// Cancellation is the runtime's own observation rather than a report of
3673    /// something else, so it has no cause underneath it.
3674    fn source(&self) -> Option<&(dyn Error + 'static)> {
3675        match self {
3676            Self::Callback(failure) => Some(failure),
3677            Self::Cancelled => None,
3678        }
3679    }
3680}
3681
3682/// Mutable hook roster consumed by [`crate::runtime::agent::Agent::new`].
3683///
3684/// Pass this builder directly to
3685/// [`agent::Config::new`](crate::runtime::agent::Config::new).
3686#[derive(Default)]
3687pub struct RegistryBuilder {
3688    hooks: Vec<Registration>,
3689}
3690
3691impl fmt::Debug for RegistryBuilder {
3692    /// Lists the hook names registered so far, in registration order.
3693    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3694        debug_hook_names("RegistryBuilder", self.hooks.iter(), formatter)
3695    }
3696}
3697
3698// A registry and the builder it is frozen from are both identified by the
3699// ordered hook roster they carry, and registration order is dispatch order.
3700fn debug_hook_names<'a>(
3701    name: &str,
3702    hooks: impl Iterator<Item = &'a Registration>,
3703    formatter: &mut fmt::Formatter<'_>,
3704) -> fmt::Result {
3705    formatter
3706        .debug_struct(name)
3707        .field(
3708            "hooks",
3709            &hooks
3710                .map(|registration| registration.name.as_str())
3711                .collect::<Vec<_>>(),
3712        )
3713        .finish()
3714}
3715
3716impl RegistryBuilder {
3717    /// Creates an empty builder.
3718    #[must_use]
3719    pub fn new() -> Self {
3720        Self::default()
3721    }
3722
3723    /// Appends one complete hook registration in observable fan-out order.
3724    pub fn register(&mut self, hook: Registration) -> &mut Self {
3725        self.hooks.push(hook);
3726        self
3727    }
3728
3729    /// Validates and freezes the one runtime registry owned by an Agent.
3730    pub(crate) fn build_runtime(self) -> Result<RuntimeRegistry, RegistryError> {
3731        self.freeze().map(RuntimeRegistry::new)
3732    }
3733
3734    fn freeze(self) -> Result<FrozenRegistry, RegistryError> {
3735        let mut names = std::collections::HashSet::new();
3736        let mut hooks = Vec::with_capacity(self.hooks.len());
3737        for registration in self.hooks {
3738            if registration.name.is_empty() {
3739                return Err(RegistryError::EmptyName);
3740            }
3741            if !names.insert(registration.name.clone()) {
3742                return Err(RegistryError::DuplicateName(registration.name));
3743            }
3744            hooks.push(RegisteredHook { registration });
3745        }
3746        Ok(FrozenRegistry {
3747            hooks: hooks.into(),
3748        })
3749    }
3750}
3751
3752/// Frozen registration storage owned by the Agent runtime registry.
3753#[derive(Clone)]
3754pub(crate) struct FrozenRegistry {
3755    hooks: Arc<[RegisteredHook]>,
3756}
3757
3758/// Agent-private runtime hook registry with stable registration-order fan-out.
3759#[derive(Clone)]
3760pub(crate) struct RuntimeRegistry {
3761    frozen: FrozenRegistry,
3762}
3763
3764impl RuntimeRegistry {
3765    const fn new(frozen: FrozenRegistry) -> Self {
3766        Self { frozen }
3767    }
3768}
3769
3770impl std::ops::Deref for RuntimeRegistry {
3771    type Target = FrozenRegistry;
3772
3773    fn deref(&self) -> &Self::Target {
3774        &self.frozen
3775    }
3776}
3777
3778impl fmt::Debug for RuntimeRegistry {
3779    /// Lists the frozen hook roster, in registration order.
3780    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3781        debug_hook_names(
3782            "RuntimeRegistry",
3783            self.frozen.hooks.iter().map(|hook| &hook.registration),
3784            formatter,
3785        )
3786    }
3787}
3788
3789impl FrozenRegistry {
3790    /// Returns the number of named registrations.
3791    #[must_use]
3792    pub(crate) fn len(&self) -> usize {
3793        self.hooks.len()
3794    }
3795
3796    /// Reports whether no hook is registered.
3797    #[cfg(test)]
3798    #[must_use]
3799    pub(crate) fn is_empty(&self) -> bool {
3800        self.hooks.is_empty()
3801    }
3802
3803    /// Iterates stable registration names.
3804    #[must_use]
3805    pub(crate) fn names(&self) -> impl ExactSizeIterator<Item = &str> {
3806        self.hooks
3807            .iter()
3808            .map(|hook| hook.registration.name.as_str())
3809    }
3810
3811    /// Reports whether any hook requires optional Session state support.
3812    #[must_use]
3813    pub(crate) fn requires_session_state(&self) -> bool {
3814        self.hooks
3815            .iter()
3816            .any(|hook| hook.registration.requires_session_state)
3817    }
3818
3819    pub(crate) fn run_hooks(&self) -> impl Iterator<Item = RegistrationAdapter<'_, dyn RunHooks>> {
3820        self.hooks
3821            .iter()
3822            .enumerate()
3823            .filter_map(|(index, registered)| {
3824                registered
3825                    .registration
3826                    .run
3827                    .as_deref()
3828                    .map(|hook| RegistrationAdapter {
3829                        index,
3830                        name: registered.registration.name.as_str(),
3831                        requires_session_state: registered.registration.requires_session_state,
3832                        hook,
3833                    })
3834            })
3835    }
3836
3837    pub(crate) fn input_hooks(
3838        &self,
3839    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn InputHooks>> {
3840        self.hooks
3841            .iter()
3842            .enumerate()
3843            .filter_map(|(index, registered)| {
3844                registered
3845                    .registration
3846                    .input
3847                    .as_deref()
3848                    .map(|hook| RegistrationAdapter {
3849                        index,
3850                        name: registered.registration.name.as_str(),
3851                        requires_session_state: registered.registration.requires_session_state,
3852                        hook,
3853                    })
3854            })
3855    }
3856
3857    pub(crate) fn turn_step_hooks(
3858        &self,
3859    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn TurnStepHooks>> {
3860        self.hooks
3861            .iter()
3862            .enumerate()
3863            .filter_map(|(index, registered)| {
3864                registered
3865                    .registration
3866                    .turn_step
3867                    .as_deref()
3868                    .map(|hook| RegistrationAdapter {
3869                        index,
3870                        name: registered.registration.name.as_str(),
3871                        requires_session_state: registered.registration.requires_session_state,
3872                        hook,
3873                    })
3874            })
3875    }
3876
3877    pub(crate) fn model_hooks(
3878        &self,
3879    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ModelHooks>> {
3880        self.hooks
3881            .iter()
3882            .enumerate()
3883            .filter_map(|(index, registered)| {
3884                registered
3885                    .registration
3886                    .model
3887                    .as_deref()
3888                    .map(|hook| RegistrationAdapter {
3889                        index,
3890                        name: registered.registration.name.as_str(),
3891                        requires_session_state: registered.registration.requires_session_state,
3892                        hook,
3893                    })
3894            })
3895    }
3896
3897    pub(crate) fn tool_hooks(
3898        &self,
3899    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ToolHooks>> {
3900        self.hooks
3901            .iter()
3902            .enumerate()
3903            .filter_map(|(index, registered)| {
3904                registered
3905                    .registration
3906                    .tool
3907                    .as_deref()
3908                    .map(|hook| RegistrationAdapter {
3909                        index,
3910                        name: registered.registration.name.as_str(),
3911                        requires_session_state: registered.registration.requires_session_state,
3912                        hook,
3913                    })
3914            })
3915    }
3916
3917    pub(crate) fn owned_tool_hooks(
3918        &self,
3919    ) -> impl Iterator<Item = OwnedToolRegistrationAdapter> + '_ {
3920        self.hooks
3921            .iter()
3922            .enumerate()
3923            .filter_map(|(index, registered)| {
3924                registered
3925                    .registration
3926                    .tool
3927                    .as_ref()
3928                    .map(|hook| OwnedToolRegistrationAdapter {
3929                        index,
3930                        name: registered.registration.name.clone(),
3931                        requires_session_state: registered.registration.requires_session_state,
3932                        hook: Arc::clone(hook),
3933                    })
3934            })
3935    }
3936
3937    pub(crate) fn observer_hooks(
3938        &self,
3939    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ObserverHooks>> {
3940        self.hooks
3941            .iter()
3942            .enumerate()
3943            .filter_map(|(index, registered)| {
3944                registered
3945                    .registration
3946                    .observer
3947                    .as_deref()
3948                    .map(|hook| RegistrationAdapter {
3949                        index,
3950                        name: registered.registration.name.as_str(),
3951                        requires_session_state: registered.registration.requires_session_state,
3952                        hook,
3953                    })
3954            })
3955    }
3956
3957    pub(crate) fn transcript_hooks(
3958        &self,
3959    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn TranscriptHooks>> {
3960        self.hooks
3961            .iter()
3962            .enumerate()
3963            .filter_map(|(index, registered)| {
3964                registered
3965                    .registration
3966                    .transcript
3967                    .as_deref()
3968                    .map(|hook| RegistrationAdapter {
3969                        index,
3970                        name: registered.registration.name.as_str(),
3971                        requires_session_state: registered.registration.requires_session_state,
3972                        hook,
3973                    })
3974            })
3975    }
3976
3977    /// Fans out Agent teardown and collects every error without short-circuiting.
3978    ///
3979    /// This operation is crate-private and reached in production only by
3980    /// [`crate::runtime::agent::Agent::close`]. A callback panic is isolated as a
3981    /// registration-attributed [`crate::runtime::agent::ClosePanickedError`]. Later
3982    /// callbacks still run, so one broken teardown cannot suppress its peers.
3983    ///
3984    /// The captured panic payload is deliberately forgotten rather than dropped:
3985    /// [`std::panic::panic_any`] permits payloads whose destructor also panics, and
3986    /// dropping such a payload would escape this isolation boundary. This leaks one
3987    /// captured payload value per panicking callback invocation, confined to this
3988    /// already-pathological path, in exchange for preserving the teardown guarantee
3989    /// for every legal payload.
3990    #[must_use]
3991    pub(crate) fn close(&self) -> Vec<AttributedError> {
3992        let panic_error = HookError::new(crate::runtime::agent::ClosePanickedError);
3993        let mut failures = Vec::new();
3994        for hook in self.hooks.iter() {
3995            let Some(teardown) = &hook.registration.teardown else {
3996                continue;
3997            };
3998            let error = match catch_unwind(AssertUnwindSafe(|| teardown.close())) {
3999                Ok(Ok(())) => continue,
4000                Ok(Err(error)) => error,
4001                Err(payload) => {
4002                    // A legal `panic_any` payload may itself panic in `Drop`. There
4003                    // is no generally safe way to destroy an arbitrary captured
4004                    // payload: catching that second panic only produces another
4005                    // arbitrary payload to dispose of. Leak exactly this payload
4006                    // instead, so teardown isolation remains total and later
4007                    // registrations still run.
4008                    std::mem::forget(payload);
4009                    panic_error.clone()
4010                }
4011            };
4012            failures.push(AttributedError {
4013                name: hook.registration.name.clone(),
4014                error,
4015            });
4016        }
4017        failures
4018    }
4019}
4020
4021pub(crate) const fn lifecycle_hook_name(kind: LifecycleKind) -> &'static str {
4022    match kind {
4023        LifecycleKind::RunStart => "OnRunStart",
4024        LifecycleKind::RunEnd => "OnRunEnd",
4025        LifecycleKind::TurnStart => "OnTurnStart",
4026        LifecycleKind::TurnEnd => "OnTurnEnd",
4027        LifecycleKind::StepStart => "OnStepStart",
4028        LifecycleKind::StepEnd => "OnStepEnd",
4029        LifecycleKind::GenerationStart => "OnGenerationStart",
4030        LifecycleKind::GenerationEnd => "OnGenerationEnd",
4031        LifecycleKind::ToolCallStart => "OnToolCallStart",
4032        LifecycleKind::ToolCallEnd => "OnToolCallEnd",
4033    }
4034}
4035
4036fn emit_observer_panic(emitter: &dyn Emitter, registration: &str, callback: &str) {
4037    let payload = format!("{registration}:{callback}")
4038        .into_bytes()
4039        .into_boxed_slice();
4040    emitter.emit_audit(audit::Event::new(
4041        "hook.observer_panic".to_owned(),
4042        Some(payload),
4043    ));
4044}
4045
4046pub(crate) struct ScopeFactory<'a> {
4047    coord: &'a Coord,
4048    run_state: &'a run_state::Store,
4049    session_state: &'a session_state::Reader,
4050    session_state_writer: Option<&'a session_state::Writer>,
4051    requires_session_state: bool,
4052    transcript: TranscriptSource<'a>,
4053    emitter: &'a dyn Emitter,
4054    direct_audit: DirectAuditSink<'a>,
4055}
4056
4057impl<'a> ScopeFactory<'a> {
4058    /// Builds scopes for one hook adapter. `requires_session_state` is taken
4059    /// from that adapter's frozen registration metadata; a writer is never
4060    /// exposed when the declaration is false.
4061    pub(crate) const fn new(
4062        coord: &'a Coord,
4063        run_state: &'a run_state::Store,
4064        session_state: &'a session_state::Reader,
4065        session_state_writer: Option<&'a session_state::Writer>,
4066        requires_session_state: bool,
4067        transcript: TranscriptSource<'a>,
4068        emitter: &'a dyn Emitter,
4069    ) -> Self {
4070        Self {
4071            coord,
4072            run_state,
4073            session_state,
4074            session_state_writer,
4075            requires_session_state,
4076            transcript,
4077            emitter,
4078            direct_audit: DirectAuditSink(emitter),
4079        }
4080    }
4081
4082    const fn read_base(&self) -> ReadBase<'a> {
4083        ReadBase {
4084            session: SessionIdentity(self.coord),
4085            coord: self.coord,
4086            run_state: self.run_state,
4087            session_state: self.session_state,
4088            transcript: self.transcript,
4089        }
4090    }
4091
4092    const fn write_base(&self) -> WriteBase<'a> {
4093        WriteBase {
4094            read: self.read_base(),
4095            session_state: if self.requires_session_state {
4096                self.session_state_writer
4097            } else {
4098                None
4099            },
4100        }
4101    }
4102
4103    const fn control_base(&self) -> ControlBase<'a> {
4104        ControlBase {
4105            write: self.write_base(),
4106            emitter: self.emitter,
4107        }
4108    }
4109
4110    const fn staged_base(&self, staged: &'a StagedTranscript) -> StagedBase<'a> {
4111        StagedBase {
4112            control: self.control_base(),
4113            staged,
4114        }
4115    }
4116
4117    pub(crate) const fn prepare(
4118        &self,
4119        staged: &'a StagedTranscript,
4120        session_state_stage: Option<&'a session_state::StagedWriter>,
4121        base_snapshot: &'a Snapshot,
4122        input: &'a [Part],
4123    ) -> PrepareScope<'a> {
4124        PrepareScope {
4125            base: PrepareBase {
4126                read: self.read_base(),
4127                session_state: if self.requires_session_state {
4128                    session_state_stage
4129                } else {
4130                    None
4131                },
4132            },
4133            staged,
4134            base_snapshot,
4135            input,
4136        }
4137    }
4138
4139    pub(crate) const fn compose_continuation(
4140        &self,
4141        staged: &'a StagedTranscript,
4142        continuation: &'a [Part],
4143        continuations: usize,
4144        turns: usize,
4145    ) -> ContinuationScope<'a> {
4146        ContinuationScope {
4147            base: self.staged_base(staged),
4148            continuation,
4149            continuations,
4150            turns,
4151        }
4152    }
4153
4154    pub(crate) const fn decide_stop(&self) -> StopDecisionScope<'a> {
4155        StopDecisionScope {
4156            base: self.control_base(),
4157        }
4158    }
4159
4160    pub(crate) const fn input_admit(
4161        &self,
4162        target: InputTarget,
4163        items: &'a [Item],
4164    ) -> InputAdmitScope<'a> {
4165        InputAdmitScope {
4166            base: self.control_base(),
4167            target,
4168            items,
4169        }
4170    }
4171
4172    pub(crate) const fn turn(
4173        &self,
4174        staged: &'a StagedTranscript,
4175        trigger: &'a [Item],
4176    ) -> TurnScope<'a> {
4177        TurnScope {
4178            base: self.staged_base(staged),
4179            trigger,
4180        }
4181    }
4182
4183    pub(crate) const fn before_step<'scope>(
4184        &'scope self,
4185        staged: &'scope StagedTranscript,
4186        model: &'scope Info,
4187        plan: &'scope mut RequestPlan,
4188    ) -> BeforeStepScope<'scope> {
4189        BeforeStepScope {
4190            base: self.staged_base(staged),
4191            model,
4192            plan,
4193        }
4194    }
4195
4196    pub(crate) const fn after_step(
4197        &self,
4198        staged: &'a StagedTranscript,
4199        snapshot: &'a Arc<StepSnapshot>,
4200    ) -> AfterStepScope<'a> {
4201        AfterStepScope {
4202            base: self.staged_base(staged),
4203            snapshot,
4204        }
4205    }
4206
4207    pub(crate) const fn before_model(
4208        &self,
4209        snapshot: &'a Arc<StepSnapshot>,
4210        request: &'a Request,
4211    ) -> BeforeModelScope<'a> {
4212        BeforeModelScope {
4213            base: self.control_base(),
4214            snapshot,
4215            request,
4216        }
4217    }
4218
4219    pub(crate) const fn after_model(
4220        &self,
4221        snapshot: &'a Arc<StepSnapshot>,
4222        output: &'a Assistant,
4223        generated: bool,
4224        finish_reason: &'a str,
4225        completion: CompletionReason,
4226    ) -> AfterModelScope<'a> {
4227        AfterModelScope {
4228            base: self.control_base(),
4229            snapshot,
4230            output,
4231            generated,
4232            finish_reason,
4233            completion,
4234        }
4235    }
4236
4237    pub(crate) const fn tool_call(
4238        &self,
4239        snapshot: &'a Arc<StepSnapshot>,
4240        call: &'a ToolCall,
4241    ) -> ToolCallScope<'a> {
4242        ToolCallScope {
4243            base: self.control_base(),
4244            snapshot,
4245            call,
4246        }
4247    }
4248
4249    pub(crate) const fn tool_result(
4250        &self,
4251        snapshot: &'a Arc<StepSnapshot>,
4252        call: &'a ToolCall,
4253        disposition: CallDisposition,
4254        result: &'a ToolResult,
4255    ) -> ToolResultScope<'a> {
4256        ToolResultScope {
4257            base: self.control_base(),
4258            snapshot,
4259            call,
4260            disposition,
4261            result,
4262        }
4263    }
4264
4265    pub(crate) const fn after_tool_commit(
4266        &self,
4267        staged: &'a StagedTranscript,
4268        snapshot: &'a Arc<StepSnapshot>,
4269        result: &'a ToolResult,
4270    ) -> AfterToolCommitScope<'a> {
4271        AfterToolCommitScope {
4272            base: self.staged_base(staged),
4273            snapshot,
4274            result,
4275        }
4276    }
4277
4278    pub(crate) fn observer(&self, snapshot: Option<&'a Arc<StepSnapshot>>) -> ObserverScope<'_> {
4279        ObserverScope {
4280            base: self.read_base(),
4281            snapshot,
4282            audit_sink: &self.direct_audit,
4283        }
4284    }
4285
4286    pub(crate) const fn read(&self) -> ReadScope<'a> {
4287        ReadScope {
4288            base: self.read_base(),
4289        }
4290    }
4291}