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/// **Expect to see one batch more than once.** A claimed batch whose admission
2150/// neither commits nor is refused — a cancellation, a later registration's
2151/// contract error, a transcript failure, a panic — is restored to the mailbox
2152/// unrewritten (see [`InputMailbox`'s conservation
2153/// guarantee](crate::runtime::session::InputMailbox#conservation)), and the
2154/// boundary that claims it next calls this hook again. Anything a registration
2155/// does here besides returning its decision, such as a Session-state write or
2156/// an audit fact, is not rolled back, so it must be idempotent under re-entry.
2157///
2158/// ```
2159/// use std::sync::Arc;
2160///
2161/// use reef_core::runtime::hook;
2162///
2163/// /// Refuses injected input once the conversation is long enough.
2164/// struct Doorman;
2165///
2166/// impl hook::InputHooks for Doorman {
2167///     fn before_input_admit(&self, scope: &hook::InputAdmitScope<'_>) -> hook::InputAdmitDecision {
2168///         if scope.items().is_empty() {
2169///             // A rejection must say why; an empty reason is refused.
2170///             hook::InputAdmitDecision::Reject("nothing to admit".to_owned())
2171///         } else {
2172///             hook::InputAdmitDecision::Admit
2173///         }
2174///     }
2175/// }
2176///
2177/// let registration = hook::Registration::new("doorman".to_owned()).input(Arc::new(Doorman));
2178/// # let _ = registration;
2179/// ```
2180pub trait InputHooks: Send + Sync {
2181    /// Rewrites, admits, or permanently rejects one claimed batch.
2182    fn before_input_admit(&self, scope: &InputAdmitScope<'_>) -> InputAdmitDecision;
2183}
2184
2185/// Turn and Step boundary hooks.
2186///
2187/// Four boundaries inside a Run. [`before_step`](TurnStepHooks::before_step) is
2188/// the only place with a writable [`crate::runtime::model::RequestPlan`],
2189/// so it is where per-request material goes — a compaction policy rewrites
2190/// history here, and a status line goes into the plan's ephemeral lane, which
2191/// reaches the model without ever becoming a record.
2192///
2193/// ```
2194/// use std::sync::Arc;
2195///
2196/// use reef_core::runtime::hook;
2197/// use reef_core::transcript::item;
2198/// use reef_core::value::content;
2199///
2200/// /// Adds one volatile line to every request, and nothing to the transcript.
2201/// struct StatusLine;
2202///
2203/// impl hook::TurnStepHooks for StatusLine {
2204///     fn before_turn(&self, _scope: &hook::TurnScope<'_>) -> hook::HookResult<Vec<item::Item>> {
2205///         Ok(Vec::new())
2206///     }
2207///
2208///     fn after_turn(&self, _scope: &hook::TurnScope<'_>) -> hook::HookResult<Vec<item::Item>> {
2209///         Ok(Vec::new())
2210///     }
2211///
2212///     fn before_step(&self, scope: &mut hook::BeforeStepScope<'_>) -> hook::HookResult<Vec<item::Item>> {
2213///         scope
2214///             .plan()
2215///             .push_ephemeral(content::Part::text("[battery: 42%]".to_owned()));
2216///         Ok(Vec::new())
2217///     }
2218///
2219///     fn after_step(&self, _scope: &hook::AfterStepScope<'_>) -> hook::HookResult<hook::AfterStepDecision> {
2220///         Ok(hook::AfterStepDecision::Continue(Vec::new()))
2221///     }
2222/// }
2223///
2224/// let registration = hook::Registration::new("status".to_owned()).turn_step(Arc::new(StatusLine));
2225/// # let _ = registration;
2226/// ```
2227pub trait TurnStepHooks: Send + Sync {
2228    /// Runs before the Turn lifecycle starts.
2229    ///
2230    /// # Errors
2231    ///
2232    /// Return one when this registration cannot produce the items the Turn should
2233    /// open with. The Turn is never opened: the items every earlier registration
2234    /// contributed are discarded together with this one's, so the transcript
2235    /// records no half-composed Turn opening.
2236    ///
2237    /// See [`HookError`](HookError#effect-on-the-run).
2238    fn before_turn(&self, scope: &TurnScope<'_>) -> HookResult<Vec<Item>>;
2239
2240    /// Runs after ordinary Turn work and before its end observer.
2241    ///
2242    /// # Errors
2243    ///
2244    /// Return one when this registration cannot produce the items that should
2245    /// close the Turn. Nothing this boundary composed is appended. The Turn's work
2246    /// is already committed by this point, so the Run fails with a complete Turn
2247    /// behind it and no closing items — not with a partially closed Turn.
2248    ///
2249    /// See [`HookError`](HookError#effect-on-the-run).
2250    fn after_turn(&self, scope: &TurnScope<'_>) -> HookResult<Vec<Item>>;
2251
2252    /// Runs in registration order over the sole writable `RequestPlan`.
2253    ///
2254    /// # Errors
2255    ///
2256    /// Return one when this registration cannot prepare the Step — most often
2257    /// because the request material it needed to add is unavailable. The Step
2258    /// never freezes, so no model call is made, and the plan edits earlier
2259    /// registrations had already applied are dropped along with this one's. That
2260    /// is the reason a partial plan is not worth rescuing: the registrations after
2261    /// this one never saw it.
2262    ///
2263    /// See [`HookError`](HookError#effect-on-the-run).
2264    fn before_step(&self, scope: &mut BeforeStepScope<'_>) -> HookResult<Vec<Item>>;
2265
2266    /// Runs after ordinary Step work and may close its Turn.
2267    ///
2268    /// # Errors
2269    ///
2270    /// Return one when this registration cannot decide how the Step should close.
2271    /// Closing the Turn is not a failure — that is
2272    /// [`AfterStepDecision::EndTurn`] — so an error here means the decision itself
2273    /// could not be made. Neither the items nor the end-of-Turn decisions
2274    /// collected at this boundary are applied.
2275    ///
2276    /// See [`HookError`](HookError#effect-on-the-run).
2277    fn after_step(&self, scope: &AfterStepScope<'_>) -> HookResult<AfterStepDecision>;
2278}
2279
2280/// Model boundary hooks.
2281///
2282/// The two sides of one generation: the request before it is sent, and the
2283/// assistant record before it is committed. This is where a composition layer
2284/// normalises history for the provider it is about to call — core never rewrites
2285/// a segment because a different provider produced it.
2286///
2287/// ```
2288/// use std::sync::Arc;
2289///
2290/// use reef_core::runtime::hook;
2291///
2292/// /// Refuses to call the model at all after a cutoff.
2293/// struct Circuit {
2294///     open: std::sync::atomic::AtomicBool,
2295/// }
2296///
2297/// impl hook::ModelHooks for Circuit {
2298///     fn before_model(&self, _scope: &hook::BeforeModelScope<'_>) -> hook::HookResult<hook::BeforeModelDecision> {
2299///         use std::sync::atomic::Ordering;
2300///         Ok(if self.open.load(Ordering::SeqCst) {
2301///             // Declining to call the model is a decision, not a failure.
2302///             hook::BeforeModelDecision::Abort("circuit open".to_owned())
2303///         } else {
2304///             hook::BeforeModelDecision::Continue
2305///         })
2306///     }
2307///
2308///     fn after_model(&self, _scope: &hook::AfterModelScope<'_>) -> hook::AfterModelDecision {
2309///         hook::AfterModelDecision::Continue
2310///     }
2311/// }
2312///
2313/// let registration = hook::Registration::new("circuit".to_owned()).model(Arc::new(Circuit {
2314///     open: std::sync::atomic::AtomicBool::new(false),
2315/// }));
2316/// # let _ = registration;
2317/// ```
2318pub trait ModelHooks: Send + Sync {
2319    /// Controls one immutable model request.
2320    ///
2321    /// # Errors
2322    ///
2323    /// Return one when this registration cannot produce the request it wanted to
2324    /// send. Declining to call the model is not a failure — that is
2325    /// [`BeforeModelDecision::ShortCircuit`], which supplies the output itself, or
2326    /// [`BeforeModelDecision::Abort`], which states a reason — and neither is
2327    /// rewriting the request, which is [`BeforeModelDecision::Modify`]. An error is
2328    /// for the case where the rewrite itself could not be built, most commonly
2329    /// because
2330    /// re-freezing the modified history through
2331    /// [`RequestPlan::try_into_request`](crate::runtime::model::RequestPlan::try_into_request)
2332    /// returned a [`RequestError`](crate::runtime::model::RequestError) this
2333    /// registration cannot resolve.
2334    ///
2335    /// No model call is made and no generation is recorded; rewrites from earlier
2336    /// registrations are discarded with this one's.
2337    ///
2338    /// See [`HookError`](HookError#effect-on-the-run).
2339    fn before_model(&self, scope: &BeforeModelScope<'_>) -> HookResult<BeforeModelDecision>;
2340
2341    /// Rewrites successfully assembled output before commit.
2342    fn after_model(&self, scope: &AfterModelScope<'_>) -> AfterModelDecision;
2343}
2344
2345/// Tool boundary hooks.
2346///
2347/// This is the synchronous policy plane over tool calls. It sees the call before
2348/// execution and may rewrite, block, or answer it directly.
2349///
2350/// ```
2351/// use std::sync::Arc;
2352///
2353/// use reef_core::runtime::hook;
2354/// use reef_core::transcript::item;
2355///
2356/// /// Blocks one tool by name, without touching the rest.
2357/// struct Policy;
2358///
2359/// impl hook::ToolHooks for Policy {
2360///     fn before_tool_call(&self, scope: &hook::ToolCallScope<'_>) -> hook::HookResult<hook::ToolCallDecision> {
2361///         Ok(if scope.call().name().as_str() == "shell.exec" {
2362///             // A block is an ordinary business result the model reads, not a
2363///             // failure: an `Err` here would fail the whole batch.
2364///             hook::ToolCallDecision::Block("shell is disabled".to_owned())
2365///         } else {
2366///             hook::ToolCallDecision::Continue
2367///         })
2368///     }
2369///
2370///     fn before_tool_result(&self, _scope: &hook::ToolResultScope<'_>) -> hook::HookResult<hook::ToolResultDecision> {
2371///         Ok(hook::ToolResultDecision::Continue)
2372///     }
2373///
2374///     fn after_tool_commit(&self, _scope: &hook::AfterToolCommitScope<'_>) -> Vec<item::Item> {
2375///         Vec::new()
2376///     }
2377/// }
2378///
2379/// let registration = hook::Registration::new("policy".to_owned()).tool(Arc::new(Policy));
2380/// # let _ = registration;
2381/// ```
2382///
2383/// # Cooperative synchronous callback contract
2384///
2385/// These callbacks are trusted, synchronous, and cooperative. An implementation
2386/// must not block forever, wait for work that requires the same runtime thread to
2387/// advance, or catch a runtime-internal abort unwind and then continue external
2388/// side effects. Reef retains and joins every callback owner on normal, error, and
2389/// strong-delivery abort paths, but does not claim to forcibly terminate a
2390/// malicious or permanently blocked synchronous callback.
2391///
2392/// ## How a broken one looks from outside, and who to blame
2393///
2394/// Breaking that contract produces neither an error nor a panic, so it is worth
2395/// knowing the shape it does produce. A [`Self::after_tool_commit`] that never
2396/// returns leaves a thread blocked inside a destructor during teardown: the run
2397/// joins the callback it promised to join, waits for a completion that is not
2398/// coming, and never releases. The Run does not fail — it stops finishing.
2399///
2400/// Nothing in the process reports which registration is responsible, because a
2401/// diagnostic emitted from a destructor would have to be a panic during unwinding
2402/// or a library writing to stderr, and this crate does neither. What is available
2403/// instead is a backtrace: `after_tool_commit` is the only callback that runs on
2404/// Tokio's blocking pool, and the registrations are invoked one after another
2405/// rather than concurrently, so at most one is in flight and the blocking thread's
2406/// own stack names the implementing type. A *panic* at this boundary is attributed
2407/// by registration name and needs no backtrace; a hang is the case that does.
2408pub trait ToolHooks: Send + Sync {
2409    /// Rewrites, blocks, or short-circuits before execution.
2410    ///
2411    /// # Errors
2412    ///
2413    /// Return one when this registration cannot decide about the call. Refusing a
2414    /// call is not a failure: [`ToolCallDecision::Block`] stops it with a reason and
2415    /// [`ToolCallDecision::ShortCircuit`] answers it directly, and both produce an
2416    /// ordinary business result that enters the batch like any other. An error
2417    /// instead fails the **whole batch**, not just this call, because the batch
2418    /// commits atomically and a batch missing one call's decision cannot be
2419    /// committed at all.
2420    ///
2421    /// A registration that cannot fail returns `Ok` unconditionally.
2422    ///
2423    /// See [`HookError`](HookError#effect-on-the-run).
2424    fn before_tool_call(&self, scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision>;
2425
2426    /// Rewrites every closed result before commit.
2427    ///
2428    /// # Errors
2429    ///
2430    /// Return one when this registration cannot produce the result it intended to
2431    /// commit. Rewriting a result, including into a business error, is
2432    /// [`ToolResultDecision::Modify`] rather than a failure. An error fails the batch
2433    /// commit, so the assistant record and every result in the batch stay
2434    /// uncommitted — which is what keeps a rejected rewrite from leaving a call
2435    /// nobody answered in the transcript.
2436    ///
2437    /// See [`HookError`](HookError#effect-on-the-run).
2438    fn before_tool_result(&self, scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision>;
2439
2440    /// Appends after an executed batch is durable; this late hook cannot fail it.
2441    ///
2442    /// Each emitted fact is a synchronous strong-acceptance rendezvous. Rejection,
2443    /// consumer abandonment, invalid facts, or channel closure aborts the callback.
2444    /// The callback must not swallow that internal abort and continue side effects;
2445    /// Reef nevertheless revokes this invocation's Session-state writer before
2446    /// releasing the abort rendezvous, so subsequent state writes fail closed.
2447    fn after_tool_commit(&self, scope: &AfterToolCommitScope<'_>) -> Vec<Item>;
2448}
2449
2450/// Passive hooks isolated at the exact callback invocation boundary.
2451///
2452/// An observer watches and decides nothing, which is what makes it the family a
2453/// budget, a metric or a log belongs in — and
2454/// [`model_event`](ObserverHooks::model_event) is the only route token usage has
2455/// out of the runtime at all.
2456///
2457/// ```
2458/// use std::sync::Arc;
2459/// use std::sync::atomic::{AtomicU64, Ordering};
2460///
2461/// use reef_core::runtime::{model, hook};
2462///
2463/// /// Counts tokens, and observes nothing else.
2464/// #[derive(Default)]
2465/// struct Budget {
2466///     spent: AtomicU64,
2467/// }
2468///
2469/// impl hook::ObserverHooks for Budget {
2470///     fn model_event(&self, _scope: &hook::ObserverScope<'_>, event: &model::Event) {
2471///         // Usage is incremental, so adding it up is exact.
2472///         if let model::Event::Usage(usage) = event {
2473///             self.spent.fetch_add(usage.total, Ordering::SeqCst);
2474///         }
2475///     }
2476/// }
2477///
2478/// let registration = hook::Registration::new("budget".to_owned())
2479///     .observer(Arc::new(Budget::default()));
2480/// # let _ = registration;
2481/// ```
2482///
2483/// # Every method has a default, and this is the only hook family where one does
2484///
2485/// An observation returns nothing and decides nothing: reef does exactly the
2486/// same thing whether a registration watched a boundary or not. Not overriding a
2487/// method here therefore *means* "I do not watch that", which is the honest
2488/// reading of an empty body, and the cost of forgetting one falls entirely on
2489/// the registration that forgot — it sees less than it meant to, in its own
2490/// output, and no other registration and no Run behaves differently.
2491///
2492/// Every other hook family stays fully required, deliberately. Those return a
2493/// decision reef then applies, so a default would have to *pick a policy* —
2494/// allow the call, keep the request, continue the Run — and a registration that
2495/// meant to gate a tool call but misspelled the method would compile into one
2496/// that permits every call. That is the failure this crate designs against
2497/// everywhere else, which is why its enums are exhaustive, why authorisation is
2498/// a compile-time ladder, and why no decision type implements `Default`. A
2499/// silently defaulted decision is that `Default` reached by another route.
2500///
2501/// This is not a deadline that has passed: adding a default body to a required
2502/// method compiles for every existing implementor, so any hook here can gain one
2503/// later on evidence rather than on speculation.
2504pub trait ObserverHooks: Send + Sync {
2505    /// Observes synchronous Run admission without emission.
2506    ///
2507    /// The default observes nothing.
2508    fn run_admitted(&self, scope: &ReadScope<'_>) {
2509        let _ = scope;
2510    }
2511
2512    /// Observes one closed lifecycle fact.
2513    ///
2514    /// The default observes nothing.
2515    fn lifecycle(&self, observation: &LifecycleObservation, scope: &ObserverScope<'_>) {
2516        let _ = (observation, scope);
2517    }
2518
2519    /// Observes provider usage/done facts.
2520    ///
2521    /// This is the only route [`model::Event::Usage`] has to a hook, so a
2522    /// budget or accounting policy overrides this one and leaves the rest.
2523    ///
2524    /// The default observes nothing.
2525    fn model_event(&self, scope: &ObserverScope<'_>, event: &model::Event) {
2526        let _ = (scope, event);
2527    }
2528
2529    /// Observes an audit fact inside the serialized outward boundary.
2530    ///
2531    /// The default observes nothing.
2532    fn audit_event(&self, scope: &ReadScope<'_>, event: &audit::Event) {
2533        let _ = (scope, event);
2534    }
2535}
2536
2537/// Transcript reservation hook.
2538///
2539/// The seam a durable journal is built on. Every live transcript mutation the
2540/// Agent runtime performs is offered here *before* it linearizes: a registration
2541/// that can promise to publish returns a [`TranscriptReservation`], and one that
2542/// cannot returns an error, which aborts the mutation with nothing written.
2543/// Publication afterwards cannot fail, so a hook that must not lose a record does
2544/// its risky work — the write-ahead, the lock, the capacity check — inside
2545/// `reserve`.
2546///
2547/// This is an Agent-owned Run rail, not a Session-global observer. Restoring the
2548/// initial seed through [`Session::new`](crate::runtime::session::Session::new)
2549/// does not create a live mutation, and direct composition-layer calls to
2550/// [`Lease::append_batch_if_version`](crate::runtime::session::Lease::append_batch_if_version)
2551/// or [`Lease::replace_if_version`](crate::runtime::session::Lease::replace_if_version)
2552/// have no Agent registry to dispatch. Those calls share the Session transaction
2553/// lock with this rail, so they cannot cross an unresolved reservation, but a
2554/// caller that uses them must include them in its own persistence protocol.
2555///
2556/// [`TranscriptMutation::items`] exposes the complete owned transcript values,
2557/// including segment signatures, raw payloads and provider data. This is the
2558/// persistence rail for a byte-faithful resumable Session; the outward event stream
2559/// is an earlier, lossy observation projection and is not a substitute. With the
2560/// `serde` feature, serializing these values also serializes credential-tier
2561/// provider tokens, so the composition layer must protect its destination as the
2562/// [crate-level `Serialization` section](crate#serialization) describes.
2563///
2564/// ```
2565/// use std::sync::Arc;
2566///
2567/// use reef_core::runtime::hook;
2568///
2569/// /// Writes ahead, then publishes what it wrote.
2570/// struct Journal;
2571///
2572/// struct Reserved {
2573///     version: u64,
2574/// }
2575///
2576/// impl hook::TranscriptReservation for Reserved {
2577///     fn publish(self: Box<Self>) {
2578///         // The mutation has linearized. This cannot fail and must not.
2579///         let _durable = self.version;
2580///     }
2581///
2582///     fn abort(self: Box<Self>) {
2583///         // The mutation never happened; release what `reserve` took.
2584///     }
2585/// }
2586///
2587/// impl hook::TranscriptHooks for Journal {
2588///     fn reserve(
2589///         &self,
2590///         _scope: &hook::ReadScope<'_>,
2591///         mutation: &hook::TranscriptMutation,
2592///     ) -> hook::HookResult<Box<dyn hook::TranscriptReservation>> {
2593///         Ok(Box::new(Reserved { version: mutation.version().as_u64() }))
2594///     }
2595/// }
2596///
2597/// let registration = hook::Registration::new("journal".to_owned()).transcript(Arc::new(Journal));
2598/// # let _ = registration;
2599/// ```
2600pub trait TranscriptHooks: Send + Sync {
2601    /// Reserves one immutable mutation before live commit.
2602    ///
2603    /// # Errors
2604    ///
2605    /// Return one when this registration cannot promise to publish the mutation.
2606    /// That is the whole question this hook asks: everything that can go wrong must
2607    /// go wrong *here*, because [`TranscriptReservation::publish`] runs after the
2608    /// commit has linearized and is contractually infallible. A registration that
2609    /// needs to write ahead, take a lock, or reserve capacity does it now and
2610    /// returns an error if it cannot.
2611    ///
2612    /// A failure aborts every reservation this transaction already held, in reverse
2613    /// acquisition order, and the compare-and-set never runs — so the transcript is
2614    /// unchanged and no peer is left holding a reservation for a mutation that never
2615    /// happened. Registrations after this one are not called.
2616    ///
2617    /// Because a reservation failure fails the mutation rather than a callback
2618    /// phase, the Run's [`FailureKind`](crate::runtime::run::FailureKind) is
2619    /// [`Transcript`](crate::runtime::run::FailureKind::Transcript) or
2620    /// [`ToolCommit`](crate::runtime::run::FailureKind::ToolCommit) rather than
2621    /// [`Hook`](crate::runtime::run::FailureKind::Hook), even though this
2622    /// registration's name is still attached to the cause. At Run admission it is
2623    /// [`StartError::Prepare`](crate::runtime::agent::StartError::Prepare) instead.
2624    ///
2625    /// See [`HookError`](HookError#effect-on-the-run).
2626    fn reserve(
2627        &self,
2628        scope: &ReadScope<'_>,
2629        mutation: &TranscriptMutation,
2630    ) -> HookResult<Box<dyn TranscriptReservation>>;
2631}
2632
2633/// Agent teardown is deliberately separate from all 27 runtime callbacks.
2634///
2635/// It is the only hook that runs outside a Run, and the only one whose failure
2636/// costs nothing else: [`Agent::close`](crate::runtime::agent::Agent::close)
2637/// invokes every registration's `close` in registration order regardless of what
2638/// the others did, and reports the failures together.
2639///
2640/// ```
2641/// use std::sync::Arc;
2642/// use std::sync::atomic::{AtomicBool, Ordering};
2643///
2644/// use reef_core::runtime::hook;
2645///
2646/// /// Releases something the hook opened, exactly once.
2647/// #[derive(Default)]
2648/// struct Connection {
2649///     closed: AtomicBool,
2650/// }
2651///
2652/// impl hook::AgentTeardown for Connection {
2653///     fn close(&self) -> hook::HookResult<()> {
2654///         self.closed.store(true, Ordering::SeqCst);
2655///         Ok(())
2656///     }
2657/// }
2658///
2659/// let registration = hook::Registration::new("connection".to_owned())
2660///     .teardown(Arc::new(Connection::default()));
2661/// # let _ = registration;
2662/// ```
2663pub trait AgentTeardown: Send + Sync {
2664    /// Releases hook-owned external resources.
2665    ///
2666    /// # Errors
2667    ///
2668    /// Return one when a resource could not be released cleanly — a connection
2669    /// that would not drain, a flush that failed. This is the one fallible hook
2670    /// whose failure does **not** short-circuit anything: teardown is the last
2671    /// thing that happens, so every registration's `close` runs in registration
2672    /// order regardless, and the failures are collected rather than raced. A peer
2673    /// that would have released a file handle still gets to.
2674    ///
2675    /// [`Agent::close`](crate::runtime::agent::Agent::close) reports them together
2676    /// as [`CloseError::Hooks`](crate::runtime::agent::CloseError::Hooks), whose
2677    /// [`TeardownError::entries`](crate::runtime::agent::TeardownError::entries)
2678    /// lists every failure in registration order with its hook's name. That
2679    /// result is cached, so a repeated close returns the same failures rather than
2680    /// running teardown again — an error here is final, not a retry request. A
2681    /// panicking `close` is caught at this boundary and reported the same way.
2682    ///
2683    /// The Agent is closed either way. There is no Run left for a failure here to
2684    /// affect, which is why [`HookError`](HookError#effect-on-the-run)'s Run
2685    /// consequences do not apply.
2686    fn close(&self) -> HookResult<()>;
2687}
2688
2689/// One named hook's family registrations and state-access metadata.
2690pub struct Registration {
2691    name: String,
2692    requires_session_state: bool,
2693    run: Option<Arc<dyn RunHooks>>,
2694    input: Option<Arc<dyn InputHooks>>,
2695    turn_step: Option<Arc<dyn TurnStepHooks>>,
2696    model: Option<Arc<dyn ModelHooks>>,
2697    tool: Option<Arc<dyn ToolHooks>>,
2698    observer: Option<Arc<dyn ObserverHooks>>,
2699    transcript: Option<Arc<dyn TranscriptHooks>>,
2700    teardown: Option<Arc<dyn AgentTeardown>>,
2701}
2702
2703impl fmt::Debug for Registration {
2704    /// Names the hook and states which hook families it actually claimed.
2705    ///
2706    /// Every hook is a trait object with no `Debug`, and presence is the whole
2707    /// of what a registration decides: which of the eight families this hook
2708    /// will be dispatched into.
2709    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2710        formatter
2711            .debug_struct("Registration")
2712            .field("name", &self.name)
2713            .field("requires_session_state", &self.requires_session_state)
2714            .field("run", &Presence(self.run.is_some()))
2715            .field("input", &Presence(self.input.is_some()))
2716            .field("turn_step", &Presence(self.turn_step.is_some()))
2717            .field("model", &Presence(self.model.is_some()))
2718            .field("tool", &Presence(self.tool.is_some()))
2719            .field("observer", &Presence(self.observer.is_some()))
2720            .field("transcript", &Presence(self.transcript.is_some()))
2721            .field("teardown", &Presence(self.teardown.is_some()))
2722            .finish()
2723    }
2724}
2725
2726impl Registration {
2727    /// Begins one named registration.
2728    #[must_use]
2729    pub fn new(name: String) -> Self {
2730        Self {
2731            name,
2732            requires_session_state: false,
2733            run: None,
2734            input: None,
2735            turn_step: None,
2736            model: None,
2737            tool: None,
2738            observer: None,
2739            transcript: None,
2740            teardown: None,
2741        }
2742    }
2743
2744    /// Declares use of optional successor-Run Session state.
2745    #[must_use]
2746    pub const fn requires_session_state(mut self, required: bool) -> Self {
2747        self.requires_session_state = required;
2748        self
2749    }
2750
2751    /// Mounts the Run family.
2752    #[must_use]
2753    pub fn run(mut self, hooks: Arc<dyn RunHooks>) -> Self {
2754        self.run = Some(hooks);
2755        self
2756    }
2757
2758    /// Mounts the input-admission family.
2759    #[must_use]
2760    pub fn input(mut self, hooks: Arc<dyn InputHooks>) -> Self {
2761        self.input = Some(hooks);
2762        self
2763    }
2764
2765    /// Mounts the Turn/Step family.
2766    #[must_use]
2767    pub fn turn_step(mut self, hooks: Arc<dyn TurnStepHooks>) -> Self {
2768        self.turn_step = Some(hooks);
2769        self
2770    }
2771
2772    /// Mounts the model family.
2773    #[must_use]
2774    pub fn model(mut self, hooks: Arc<dyn ModelHooks>) -> Self {
2775        self.model = Some(hooks);
2776        self
2777    }
2778
2779    /// Mounts the tool family.
2780    #[must_use]
2781    pub fn tool(mut self, hooks: Arc<dyn ToolHooks>) -> Self {
2782        self.tool = Some(hooks);
2783        self
2784    }
2785
2786    /// Mounts passive observers.
2787    #[must_use]
2788    pub fn observer(mut self, hooks: Arc<dyn ObserverHooks>) -> Self {
2789        self.observer = Some(hooks);
2790        self
2791    }
2792
2793    /// Mounts transcript reservation.
2794    #[must_use]
2795    pub fn transcript(mut self, hooks: Arc<dyn TranscriptHooks>) -> Self {
2796        self.transcript = Some(hooks);
2797        self
2798    }
2799
2800    /// Mounts Agent teardown separately from runtime families.
2801    #[must_use]
2802    pub fn teardown(mut self, hooks: Arc<dyn AgentTeardown>) -> Self {
2803        self.teardown = Some(hooks);
2804        self
2805    }
2806}
2807
2808struct RegisteredHook {
2809    registration: Registration,
2810}
2811
2812/// One family hook with its immutable registration metadata.
2813///
2814/// The index is the original registry position, not a dense family-local index,
2815/// so controllers can key independent per-registration Run state and callback
2816/// transactions without losing registrations that omitted this family.
2817pub(crate) struct RegistrationAdapter<'a, H: ?Sized> {
2818    index: usize,
2819    name: &'a str,
2820    requires_session_state: bool,
2821    hook: &'a H,
2822}
2823
2824/// Owned tool adapter used only by managed blocking callback owners.
2825pub(crate) struct OwnedToolRegistrationAdapter {
2826    index: usize,
2827    name: String,
2828    requires_session_state: bool,
2829    hook: Arc<dyn ToolHooks>,
2830}
2831
2832impl<'a, H: ?Sized> RegistrationAdapter<'a, H> {
2833    pub(crate) const fn index(&self) -> usize {
2834        self.index
2835    }
2836
2837    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
2838    pub(crate) const fn name(&self) -> &'a str {
2839        self.name
2840    }
2841
2842    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
2843    pub(crate) const fn requires_session_state(&self) -> bool {
2844        self.requires_session_state
2845    }
2846
2847    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
2848    pub(crate) const fn hook(&self) -> &'a H {
2849        self.hook
2850    }
2851}
2852
2853impl OwnedToolRegistrationAdapter {
2854    pub(crate) const fn index(&self) -> usize {
2855        self.index
2856    }
2857
2858    pub(crate) fn name(&self) -> &str {
2859        &self.name
2860    }
2861
2862    pub(crate) fn invoke_after_tool_commit(
2863        &self,
2864        resources: CallbackResources<'_>,
2865        staged: &StagedTranscript,
2866        snapshot: &Arc<StepSnapshot>,
2867        result: &ToolResult,
2868    ) -> Vec<Item> {
2869        RegistrationAdapter {
2870            index: self.index,
2871            name: &self.name,
2872            requires_session_state: self.requires_session_state,
2873            hook: &*self.hook,
2874        }
2875        .invoke_after_tool_commit(resources, staged, snapshot, result)
2876    }
2877}
2878
2879/// Caller-owned resources for exactly one registration callback invocation.
2880///
2881/// A controller must create a fresh `run_state::Store` per registration and a fresh
2882/// `StagedTranscript` per callback. This bundle deliberately carries neither a
2883/// registry nor commit authority; the controller decides whether successful
2884/// staged work is committed and always discards failed callback stages.
2885#[derive(Clone, Copy)]
2886pub(crate) struct CallbackResources<'a> {
2887    coord: &'a Coord,
2888    run_state: &'a run_state::Store,
2889    session_state: &'a session_state::Reader,
2890    session_state_writer: Option<&'a session_state::Writer>,
2891    emitter: &'a dyn Emitter,
2892}
2893
2894/// Owned aliases of one registration's state capabilities.
2895///
2896/// These handles preserve the same slots and lease authority; they do not copy
2897/// state and never escape the crate-managed callback owner.
2898pub(crate) struct OwnedCallbackResources {
2899    run_state: run_state::Store,
2900    session_state: session_state::Reader,
2901    session_state_writer: Option<session_state::Writer>,
2902    callback_write_permit: Option<CallbackWritePermit>,
2903}
2904
2905impl OwnedCallbackResources {
2906    /// Clones the runtime-owned half of this callback's write permit.
2907    pub(crate) fn callback_write_permit(&self) -> Option<CallbackWritePermit> {
2908        self.callback_write_permit.clone()
2909    }
2910
2911    pub(crate) fn bind<'a>(
2912        &'a self,
2913        coord: &'a Coord,
2914        emitter: &'a dyn Emitter,
2915    ) -> CallbackResources<'a> {
2916        CallbackResources::new(
2917            coord,
2918            &self.run_state,
2919            &self.session_state,
2920            self.session_state_writer.as_ref(),
2921            emitter,
2922        )
2923    }
2924}
2925
2926impl<'a> CallbackResources<'a> {
2927    pub(crate) const fn new(
2928        coord: &'a Coord,
2929        run_state: &'a run_state::Store,
2930        session_state: &'a session_state::Reader,
2931        session_state_writer: Option<&'a session_state::Writer>,
2932        emitter: &'a dyn Emitter,
2933    ) -> Self {
2934        Self {
2935            coord,
2936            run_state,
2937            session_state,
2938            session_state_writer,
2939            emitter,
2940        }
2941    }
2942
2943    /// Clones only crate-private capability handles for a managed callback owner.
2944    ///
2945    /// A writable registration receives a fresh callback-local permit. The async
2946    /// owner retains the matching revocation handle, so aborting one callback does
2947    /// not revoke the registration's ordinary lease writer or any later callback.
2948    pub(crate) fn owned_handles(self) -> OwnedCallbackResources {
2949        let (session_state_writer, callback_write_permit) = match self.session_state_writer {
2950            Some(writer) => {
2951                let (writer, permit) = writer.clone_with_callback_permit();
2952                (Some(writer), Some(permit))
2953            }
2954            None => (None, None),
2955        };
2956        OwnedCallbackResources {
2957            run_state: self.run_state.clone_handle(),
2958            session_state: self.session_state.clone_handle(),
2959            session_state_writer,
2960            callback_write_permit,
2961        }
2962    }
2963
2964    /// Rebinds only the callback coordinate while preserving this registration's
2965    /// private state and capability resources.
2966    pub(crate) const fn with_coord<'b>(self, coord: &'b Coord) -> CallbackResources<'b>
2967    where
2968        'a: 'b,
2969    {
2970        self.rebind(coord, self.emitter)
2971    }
2972
2973    /// Rebinds one callback to its exact coordinate and outward emitter.
2974    ///
2975    /// Synchronous adapters use this crate-private bridge when only coordinate or
2976    /// emitter identity changes. Managed blocking callbacks instead bind the owned
2977    /// aliases above. Registration-private state capabilities remain unchanged.
2978    pub(crate) const fn rebind<'b>(
2979        self,
2980        coord: &'b Coord,
2981        emitter: &'b dyn Emitter,
2982    ) -> CallbackResources<'b>
2983    where
2984        'a: 'b,
2985    {
2986        CallbackResources {
2987            coord,
2988            run_state: self.run_state,
2989            session_state: self.session_state,
2990            session_state_writer: self.session_state_writer,
2991            emitter,
2992        }
2993    }
2994
2995    const fn scope_factory(
2996        self,
2997        requires_session_state: bool,
2998        transcript: TranscriptSource<'a>,
2999    ) -> ScopeFactory<'a> {
3000        ScopeFactory::new(
3001            self.coord,
3002            self.run_state,
3003            self.session_state,
3004            self.session_state_writer,
3005            requires_session_state,
3006            transcript,
3007            self.emitter,
3008        )
3009    }
3010}
3011
3012impl RegistrationAdapter<'_, dyn RunHooks> {
3013    /// Invokes only this registration's [`RunHooks::prepare`] callback.
3014    ///
3015    /// The caller supplies registration-private Run state plus callback-local
3016    /// Session-state and transcript overlays. Neither overlay is committed or
3017    /// discarded here; the caller owns resolution after observing this result.
3018    ///
3019    /// A returned [`PrepareDecision::Modify`] is validated here rather than by
3020    /// the caller, because this is the only frame that still knows *which*
3021    /// registration produced it: an empty replacement becomes a
3022    /// [`PrepareError::EmptyModify`] attributed to that name.
3023    pub(crate) fn invoke_prepare(
3024        &self,
3025        resources: CallbackResources<'_>,
3026        staged: &StagedTranscript,
3027        session_state_stage: Option<&session_state::StagedWriter>,
3028        base_snapshot: &Snapshot,
3029        input: &[Part],
3030        cancellation: &Token,
3031    ) -> Result<PrepareDecision, DispatchError> {
3032        if cancellation.is_cancelled() {
3033            return Err(DispatchError::Cancelled);
3034        }
3035        let factory = resources.scope_factory(
3036            self.requires_session_state,
3037            TranscriptSource::Reader(&staged.reader),
3038        );
3039        let scope = factory.prepare(staged, session_state_stage, base_snapshot, input);
3040        match self.hook.prepare(&scope) {
3041            Err(error) => Err(DispatchError::Callback(AttributedError {
3042                name: self.name.to_owned(),
3043                error,
3044            })),
3045            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3046            Ok(PrepareDecision::Modify(replacement)) if replacement.is_empty() => {
3047                Err(DispatchError::Callback(AttributedError {
3048                    name: self.name.to_owned(),
3049                    error: HookError::new(PrepareError::EmptyModify),
3050                }))
3051            }
3052            Ok(decision) => Ok(decision),
3053        }
3054    }
3055
3056    /// Invokes only this registration's [`RunHooks::compose_continuation`] callback.
3057    ///
3058    /// The decision governs a continuation request: a non-empty request asks the
3059    /// loop for another Turn rather than ending the Run. `continuation` carries
3060    /// what earlier registrations already asked for, so a registration can see,
3061    /// extend, replace or ignore it.
3062    ///
3063    /// Unlike [`RegistrationAdapter::invoke_prepare`] this validates nothing: an
3064    /// empty [`ContinuationDecision::Replace`] is a deliberate veto of a peer's
3065    /// request, not a rewrite that discards user content.
3066    pub(crate) fn invoke_compose_continuation(
3067        &self,
3068        resources: CallbackResources<'_>,
3069        staged: &StagedTranscript,
3070        continuation: &[Part],
3071        continuations: usize,
3072        turns: usize,
3073        cancellation: &Token,
3074    ) -> Result<ContinuationDecision, DispatchError> {
3075        if cancellation.is_cancelled() {
3076            return Err(DispatchError::Cancelled);
3077        }
3078        let factory = resources.scope_factory(
3079            self.requires_session_state,
3080            TranscriptSource::Reader(&staged.reader),
3081        );
3082        let scope = factory.compose_continuation(staged, continuation, continuations, turns);
3083        match self.hook.compose_continuation(&scope) {
3084            Err(error) => Err(DispatchError::Callback(AttributedError {
3085                name: self.name.to_owned(),
3086                error,
3087            })),
3088            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3089            Ok(decision) => Ok(decision),
3090        }
3091    }
3092
3093    /// Invokes only this registration's [`RunHooks::decide_stop`] callback.
3094    ///
3095    /// This is the sole surface through which a hook may stop a Run with a
3096    /// code; the loop converts a stopping decision into the single privately
3097    /// owned `EventStop` (ADR-007).
3098    pub(crate) fn invoke_decide_stop(
3099        &self,
3100        resources: CallbackResources<'_>,
3101        transcript: &SnapshotReader,
3102        cancellation: &Token,
3103    ) -> Result<StopDecision, DispatchError> {
3104        if cancellation.is_cancelled() {
3105            return Err(DispatchError::Cancelled);
3106        }
3107        let factory = resources.scope_factory(
3108            self.requires_session_state,
3109            TranscriptSource::Reader(transcript),
3110        );
3111        let scope = factory.decide_stop();
3112        match self.hook.decide_stop(&scope) {
3113            Err(error) => Err(DispatchError::Callback(AttributedError {
3114                name: self.name.to_owned(),
3115                error,
3116            })),
3117            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3118            Ok(decision) => Ok(decision),
3119        }
3120    }
3121}
3122
3123impl RegistrationAdapter<'_, dyn TurnStepHooks> {
3124    /// Invokes only this registration's `OnBeforeTurn` callback.
3125    ///
3126    /// `trigger` is what opened this Turn — the admitted Run input, a claimed
3127    /// `NextTurn` batch, or a continuation an earlier
3128    /// [`RunHooks::compose_continuation`] asked for.
3129    /// The returned items are appended before the Turn's first Step.
3130    pub(crate) fn invoke_before_turn(
3131        &self,
3132        resources: CallbackResources<'_>,
3133        staged: &StagedTranscript,
3134        trigger: &[Item],
3135        cancellation: &Token,
3136    ) -> Result<Vec<Item>, DispatchError> {
3137        self.invoke_turn(resources, staged, trigger, cancellation, TurnHook::Before)
3138    }
3139
3140    /// Invokes only this registration's `OnAfterTurn` callback.
3141    pub(crate) fn invoke_after_turn(
3142        &self,
3143        resources: CallbackResources<'_>,
3144        staged: &StagedTranscript,
3145        trigger: &[Item],
3146        cancellation: &Token,
3147    ) -> Result<Vec<Item>, DispatchError> {
3148        self.invoke_turn(resources, staged, trigger, cancellation, TurnHook::After)
3149    }
3150
3151    /// Runs one Turn-boundary callback.
3152    ///
3153    /// Both boundaries take the same scope and return the same shape, so the
3154    /// cancellation and attribution rules exist once and cannot drift apart.
3155    fn invoke_turn(
3156        &self,
3157        resources: CallbackResources<'_>,
3158        staged: &StagedTranscript,
3159        trigger: &[Item],
3160        cancellation: &Token,
3161        boundary: TurnHook,
3162    ) -> Result<Vec<Item>, DispatchError> {
3163        if cancellation.is_cancelled() {
3164            return Err(DispatchError::Cancelled);
3165        }
3166        let factory = resources.scope_factory(
3167            self.requires_session_state,
3168            TranscriptSource::Reader(&staged.reader),
3169        );
3170        let scope = factory.turn(staged, trigger);
3171        let result = match boundary {
3172            TurnHook::Before => self.hook.before_turn(&scope),
3173            TurnHook::After => self.hook.after_turn(&scope),
3174        };
3175        match result {
3176            Err(error) => Err(DispatchError::Callback(AttributedError {
3177                name: self.name.to_owned(),
3178                error,
3179            })),
3180            Ok(_items) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3181            Ok(items) => Ok(items),
3182        }
3183    }
3184
3185    /// Invokes only this registration's `OnAfterStep` callback.
3186    ///
3187    /// The decision decides whether the Turn continues past this Step; the items
3188    /// it carries are appended either way.
3189    pub(crate) fn invoke_after_step(
3190        &self,
3191        resources: CallbackResources<'_>,
3192        staged: &StagedTranscript,
3193        snapshot: &Arc<StepSnapshot>,
3194        cancellation: &Token,
3195    ) -> Result<AfterStepDecision, DispatchError> {
3196        if cancellation.is_cancelled() {
3197            return Err(DispatchError::Cancelled);
3198        }
3199        let factory = resources.scope_factory(
3200            self.requires_session_state,
3201            TranscriptSource::Reader(&staged.reader),
3202        );
3203        let scope = factory.after_step(staged, snapshot);
3204        match self.hook.after_step(&scope) {
3205            Err(error) => Err(DispatchError::Callback(AttributedError {
3206                name: self.name.to_owned(),
3207                error,
3208            })),
3209            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3210            Ok(decision) => Ok(decision),
3211        }
3212    }
3213
3214    /// Invokes only this registration's `OnBeforeStep` callback.
3215    ///
3216    /// The caller supplies registration-private Run state, a lease-bound writer,
3217    /// and a callback-local staged transcript. This method has no authority to
3218    /// commit that staged transcript into the live Session.
3219    pub(crate) fn invoke_before_step(
3220        &self,
3221        resources: CallbackResources<'_>,
3222        staged: &StagedTranscript,
3223        model: &Info,
3224        plan: &mut RequestPlan,
3225        cancellation: &Token,
3226    ) -> Result<Vec<Item>, DispatchError> {
3227        if cancellation.is_cancelled() {
3228            return Err(DispatchError::Cancelled);
3229        }
3230        let factory = resources.scope_factory(
3231            self.requires_session_state,
3232            TranscriptSource::Reader(&staged.reader),
3233        );
3234        let mut scope = factory.before_step(staged, model, plan);
3235        match self.hook.before_step(&mut scope) {
3236            Err(error) => Err(DispatchError::Callback(AttributedError {
3237                name: self.name.to_owned(),
3238                error,
3239            })),
3240            Ok(_items) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3241            Ok(items) => Ok(items),
3242        }
3243    }
3244}
3245
3246impl RegistrationAdapter<'_, dyn ObserverHooks> {
3247    /// Invokes only this registration's lifecycle observer.
3248    ///
3249    /// Callback audits are buffered locally. Buffer flushes and core panic
3250    /// audits remain outside the catch boundary, so core panics propagate.
3251    pub(crate) fn invoke_lifecycle(
3252        &self,
3253        resources: CallbackResources<'_>,
3254        transcript: TranscriptSource<'_>,
3255        snapshot: Option<&Arc<StepSnapshot>>,
3256        observation: &LifecycleObservation,
3257    ) {
3258        let factory = resources.scope_factory(self.requires_session_state, transcript);
3259        let pending = CallbackAuditBuffer::new();
3260        let scope = factory.observer(snapshot);
3261        let buffered_scope = scope.with_audit_sink(&pending);
3262        let panicked = match catch_unwind(AssertUnwindSafe(|| {
3263            self.hook.lifecycle(observation, &buffered_scope);
3264        })) {
3265            Ok(()) => false,
3266            Err(payload) => {
3267                std::mem::forget(payload);
3268                true
3269            }
3270        };
3271        pending.flush_to(resources.emitter);
3272        if panicked {
3273            emit_observer_panic(
3274                resources.emitter,
3275                self.name,
3276                lifecycle_hook_name(observation.kind()),
3277            );
3278        }
3279    }
3280
3281    /// Invokes only this registration's synchronous admission observer.
3282    pub(crate) fn invoke_run_admitted(
3283        &self,
3284        resources: CallbackResources<'_>,
3285        transcript: &SnapshotReader,
3286    ) {
3287        let factory = resources.scope_factory(
3288            self.requires_session_state,
3289            TranscriptSource::Reader(transcript),
3290        );
3291        let scope = factory.read();
3292        let panicked = match catch_unwind(AssertUnwindSafe(|| self.hook.run_admitted(&scope))) {
3293            Ok(()) => false,
3294            Err(payload) => {
3295                std::mem::forget(payload);
3296                true
3297            }
3298        };
3299        if panicked {
3300            emit_observer_panic(resources.emitter, self.name, "OnRunAdmitted");
3301        }
3302    }
3303
3304    /// Invokes only this registration's model-event observer.
3305    pub(crate) fn invoke_model_event(
3306        &self,
3307        resources: CallbackResources<'_>,
3308        transcript: &Snapshot,
3309        snapshot: Option<&Arc<StepSnapshot>>,
3310        event: &model::Event,
3311    ) {
3312        let factory = resources.scope_factory(
3313            self.requires_session_state,
3314            TranscriptSource::Snapshot(transcript),
3315        );
3316        let pending = CallbackAuditBuffer::new();
3317        let scope = factory.observer(snapshot);
3318        let buffered_scope = scope.with_audit_sink(&pending);
3319        let panicked = match catch_unwind(AssertUnwindSafe(|| {
3320            self.hook.model_event(&buffered_scope, event);
3321        })) {
3322            Ok(()) => false,
3323            Err(payload) => {
3324                std::mem::forget(payload);
3325                true
3326            }
3327        };
3328        pending.flush_to(resources.emitter);
3329        if panicked {
3330            emit_observer_panic(resources.emitter, self.name, "OnModelEvent");
3331        }
3332    }
3333
3334    /// Invokes only this registration's serialized audit observer.
3335    pub(crate) fn invoke_audit_event(
3336        &self,
3337        resources: CallbackResources<'_>,
3338        transcript: &SnapshotReader,
3339        event: &audit::Event,
3340    ) {
3341        let factory = resources.scope_factory(
3342            self.requires_session_state,
3343            TranscriptSource::Reader(transcript),
3344        );
3345        let scope = factory.read();
3346        let panicked = match catch_unwind(AssertUnwindSafe(|| self.hook.audit_event(&scope, event)))
3347        {
3348            Ok(()) => false,
3349            Err(payload) => {
3350                std::mem::forget(payload);
3351                true
3352            }
3353        };
3354        if panicked {
3355            emit_observer_panic(resources.emitter, self.name, "OnAuditEvent");
3356        }
3357    }
3358}
3359
3360impl RegistrationAdapter<'_, dyn InputHooks> {
3361    /// Invokes only this registration's `OnBeforeInputAdmit` callback.
3362    ///
3363    /// `OnBeforeInputAdmit` is infallible by trait shape, so cancellation is the
3364    /// only dispatch failure. The pre-callback check fails the claimed batch
3365    /// rather than admitting new work after cancellation.
3366    pub(crate) fn invoke_before_input_admit(
3367        &self,
3368        resources: CallbackResources<'_>,
3369        transcript: &SnapshotReader,
3370        target: InputTarget,
3371        items: &[Item],
3372        cancellation: &Token,
3373    ) -> Result<InputAdmitDecision, DispatchError> {
3374        if cancellation.is_cancelled() {
3375            return Err(DispatchError::Cancelled);
3376        }
3377        let factory = resources.scope_factory(
3378            self.requires_session_state,
3379            TranscriptSource::Reader(transcript),
3380        );
3381        let scope = factory.input_admit(target, items);
3382        let decision = self.hook.before_input_admit(&scope);
3383        if cancellation.is_cancelled() {
3384            return Err(DispatchError::Cancelled);
3385        }
3386        Ok(decision)
3387    }
3388}
3389
3390fn validate_hook_assistant(
3391    registration: &str,
3392    assistant: &Assistant,
3393    snapshot: &StepSnapshot,
3394) -> Result<(), DispatchError> {
3395    // `Step::advance` in runtime/driver.rs freezes this transcript immediately
3396    // before formal RequestPlan validation. Reusing model.rs's projection and
3397    // global identity walk here keeps hook output on that same request grammar
3398    // while retaining the producing registration's attribution frame.
3399    model::validate_assistant(assistant, snapshot.tools().transcript().items()).map_err(|error| {
3400        DispatchError::Callback(AttributedError {
3401            name: registration.to_owned(),
3402            error: HookError::new(error),
3403        })
3404    })
3405}
3406
3407impl RegistrationAdapter<'_, dyn ModelHooks> {
3408    /// Invokes only this registration's `OnBeforeModel` callback.
3409    ///
3410    /// A real callback error outranks a concurrently observed cancellation, so
3411    /// the cancellation re-check runs only on the `Ok` path.
3412    pub(crate) fn invoke_before_model(
3413        &self,
3414        resources: CallbackResources<'_>,
3415        snapshot: &Arc<StepSnapshot>,
3416        request: &Request,
3417        cancellation: &Token,
3418    ) -> Result<BeforeModelDecision, DispatchError> {
3419        if cancellation.is_cancelled() {
3420            return Err(DispatchError::Cancelled);
3421        }
3422        let factory = resources.scope_factory(
3423            self.requires_session_state,
3424            TranscriptSource::Snapshot(snapshot.tools().transcript()),
3425        );
3426        let scope = factory.before_model(snapshot, request);
3427        match self.hook.before_model(&scope) {
3428            Err(error) => Err(DispatchError::Callback(AttributedError {
3429                name: self.name.to_owned(),
3430                error,
3431            })),
3432            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3433            Ok(decision) => {
3434                if let BeforeModelDecision::ShortCircuit(assistant) = &decision {
3435                    validate_hook_assistant(self.name, assistant, snapshot)?;
3436                }
3437                Ok(decision)
3438            }
3439        }
3440    }
3441
3442    /// Invokes only this registration's `OnAfterModel` callback.
3443    #[expect(
3444        clippy::too_many_arguments,
3445        reason = "OnAfterModel observes five independent frozen model facts plus its resources"
3446    )]
3447    pub(crate) fn invoke_after_model(
3448        &self,
3449        resources: CallbackResources<'_>,
3450        snapshot: &Arc<StepSnapshot>,
3451        output: &Assistant,
3452        generated: bool,
3453        finish_reason: &str,
3454        completion: CompletionReason,
3455        cancellation: &Token,
3456    ) -> Result<AfterModelDecision, DispatchError> {
3457        if cancellation.is_cancelled() {
3458            return Err(DispatchError::Cancelled);
3459        }
3460        let factory = resources.scope_factory(
3461            self.requires_session_state,
3462            TranscriptSource::Snapshot(snapshot.tools().transcript()),
3463        );
3464        let scope = factory.after_model(snapshot, output, generated, finish_reason, completion);
3465        let decision = self.hook.after_model(&scope);
3466        if cancellation.is_cancelled() {
3467            return Err(DispatchError::Cancelled);
3468        }
3469        if let AfterModelDecision::Modify(assistant) = &decision {
3470            validate_hook_assistant(self.name, assistant, snapshot)?;
3471        }
3472        Ok(decision)
3473    }
3474}
3475
3476impl RegistrationAdapter<'_, dyn ToolHooks> {
3477    /// Invokes only this registration's `OnBeforeToolCall` callback.
3478    ///
3479    /// This rewrite plane runs strictly before execution, which therefore sees
3480    /// the final effective call. Validation remains
3481    /// in this registration frame so an empty effective name is a typed,
3482    /// registration-attributed failure rather than a later coordinate panic.
3483    pub(crate) fn invoke_before_tool_call(
3484        &self,
3485        resources: CallbackResources<'_>,
3486        snapshot: &Arc<StepSnapshot>,
3487        call: &ToolCall,
3488        cancellation: &Token,
3489    ) -> Result<ToolCallDecision, DispatchError> {
3490        if cancellation.is_cancelled() {
3491            return Err(DispatchError::Cancelled);
3492        }
3493        let factory = resources.scope_factory(
3494            self.requires_session_state,
3495            TranscriptSource::Snapshot(snapshot.tools().transcript()),
3496        );
3497        let scope = factory.tool_call(snapshot, call);
3498        match self.hook.before_tool_call(&scope) {
3499            Err(error) => Err(DispatchError::Callback(AttributedError {
3500                name: self.name.to_owned(),
3501                error,
3502            })),
3503            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3504            Ok(ToolCallDecision::Modify(modified)) if modified.name().as_str().is_empty() => {
3505                Err(DispatchError::Callback(AttributedError {
3506                    name: self.name.to_owned(),
3507                    error: HookError::new(model::RequestError::EmptyToolCallName {
3508                        call_id: call.id().as_str().to_owned(),
3509                    }),
3510                }))
3511            }
3512            Ok(decision) => Ok(decision),
3513        }
3514    }
3515
3516    /// Invokes only this registration's `OnBeforeToolResult` callback.
3517    ///
3518    /// Each rewrite is observed by the next registration, so the committed
3519    /// append, the outward result event, and the `ToolCall` end observation all
3520    /// report the same output.
3521    pub(crate) fn invoke_before_tool_result(
3522        &self,
3523        resources: CallbackResources<'_>,
3524        snapshot: &Arc<StepSnapshot>,
3525        call: &ToolCall,
3526        disposition: CallDisposition,
3527        result: &ToolResult,
3528        cancellation: &Token,
3529    ) -> Result<ToolResultDecision, DispatchError> {
3530        if cancellation.is_cancelled() {
3531            return Err(DispatchError::Cancelled);
3532        }
3533        let factory = resources.scope_factory(
3534            self.requires_session_state,
3535            TranscriptSource::Snapshot(snapshot.tools().transcript()),
3536        );
3537        let scope = factory.tool_result(snapshot, call, disposition, result);
3538        match self.hook.before_tool_result(&scope) {
3539            Err(error) => Err(DispatchError::Callback(AttributedError {
3540                name: self.name.to_owned(),
3541                error,
3542            })),
3543            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3544            Ok(decision) => Ok(decision),
3545        }
3546    }
3547
3548    /// Invokes only this registration's [`ToolHooks::after_tool_commit`] callback.
3549    ///
3550    /// The result batch is already durable at this boundary, so this late hook
3551    /// cannot fail the batch and takes no cancellation token: cancelling here
3552    /// would drop items that belong to an already-committed batch.
3553    pub(crate) fn invoke_after_tool_commit(
3554        &self,
3555        resources: CallbackResources<'_>,
3556        staged: &StagedTranscript,
3557        snapshot: &Arc<StepSnapshot>,
3558        result: &ToolResult,
3559    ) -> Vec<Item> {
3560        let factory = resources.scope_factory(
3561            self.requires_session_state,
3562            TranscriptSource::Reader(&staged.reader),
3563        );
3564        let scope = factory.after_tool_commit(staged, snapshot, result);
3565        self.hook.after_tool_commit(&scope)
3566    }
3567}
3568
3569impl RegistrationAdapter<'_, dyn TranscriptHooks> {
3570    /// Invokes only this registration's `OnTranscriptMutation` callback.
3571    ///
3572    /// The callback runs inside the controller's single pre-commit critical
3573    /// section and therefore receives a [`ReadScope`], which cannot re-enter the
3574    /// commit path or the outward boundary. Returning the reservation to
3575    /// the caller keeps abort/publish authority with the controller.
3576    pub(crate) fn invoke_reserve(
3577        &self,
3578        resources: CallbackResources<'_>,
3579        transcript: &Snapshot,
3580        mutation: &TranscriptMutation,
3581    ) -> Result<Box<dyn TranscriptReservation>, DispatchError> {
3582        let factory = resources.scope_factory(
3583            self.requires_session_state,
3584            TranscriptSource::Snapshot(transcript),
3585        );
3586        let scope = factory.read();
3587        self.hook.reserve(&scope, mutation).map_err(|error| {
3588            DispatchError::Callback(AttributedError {
3589                name: self.name.to_owned(),
3590                error,
3591            })
3592        })
3593    }
3594}
3595
3596/// Fail-closed hook-roster error reported by [`crate::runtime::agent::Agent::new`].
3597#[derive(Clone, Debug, Eq, PartialEq)]
3598#[non_exhaustive]
3599pub enum RegistryError {
3600    /// A hook name was empty.
3601    EmptyName,
3602    /// A hook name appeared more than once.
3603    DuplicateName(String),
3604}
3605
3606impl fmt::Display for RegistryError {
3607    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3608        match self {
3609            Self::EmptyName => formatter.write_str("hook name must be non-empty"),
3610            Self::DuplicateName(name) => write!(formatter, "duplicate hook name: {name}"),
3611        }
3612    }
3613}
3614
3615impl Error for RegistryError {}
3616
3617/// One callback failure attributed to its stable registration name.
3618#[derive(Clone, Debug)]
3619pub struct AttributedError {
3620    name: String,
3621    error: HookError,
3622}
3623
3624impl AttributedError {
3625    /// Returns the hook registration name.
3626    #[must_use]
3627    pub fn name(&self) -> &str {
3628        &self.name
3629    }
3630
3631    /// Returns the unflattened callback error.
3632    #[must_use]
3633    pub const fn error(&self) -> &HookError {
3634        &self.error
3635    }
3636}
3637
3638impl fmt::Display for AttributedError {
3639    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3640        write!(formatter, "hook {} failed: {}", self.name, self.error)
3641    }
3642}
3643
3644impl Error for AttributedError {
3645    fn source(&self) -> Option<&(dyn Error + 'static)> {
3646        Some(&self.error)
3647    }
3648}
3649
3650/// Which of the two Turn-boundary callbacks one dispatch runs.
3651#[derive(Clone, Copy)]
3652enum TurnHook {
3653    Before,
3654    After,
3655}
3656
3657/// Mutating dispatch failure with callback errors distinct from cancellation.
3658#[derive(Clone, Debug)]
3659#[non_exhaustive]
3660pub(crate) enum DispatchError {
3661    /// A real callback failed and outranks a concurrently observed cancellation.
3662    Callback(AttributedError),
3663    /// Cancellation was observed after the preceding callback returned normally.
3664    Cancelled,
3665}
3666
3667impl fmt::Display for DispatchError {
3668    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3669        match self {
3670            Self::Callback(failure) => write!(
3671                formatter,
3672                "hook {} failed: {}",
3673                failure.name(),
3674                failure.error()
3675            ),
3676            Self::Cancelled => formatter.write_str("cancelled around a callback"),
3677        }
3678    }
3679}
3680
3681impl Error for DispatchError {
3682    /// Returns the attributed callback failure, chain intact.
3683    ///
3684    /// The immediate cause is the [`AttributedError`], not the [`HookError`]
3685    /// inside it. Returning the inner error directly would drop the one link
3686    /// that carries the registration name, so a caller walking the chain could
3687    /// read the failure but never learn which hook produced it. The name is
3688    /// not recoverable from anything below, and `AttributedError` yields the
3689    /// callback error from its own `source`, so nothing deeper is lost.
3690    ///
3691    /// Cancellation is the runtime's own observation rather than a report of
3692    /// something else, so it has no cause underneath it.
3693    fn source(&self) -> Option<&(dyn Error + 'static)> {
3694        match self {
3695            Self::Callback(failure) => Some(failure),
3696            Self::Cancelled => None,
3697        }
3698    }
3699}
3700
3701/// Mutable hook roster consumed by [`crate::runtime::agent::Agent::new`].
3702///
3703/// Pass this builder directly to
3704/// [`agent::Config::new`](crate::runtime::agent::Config::new).
3705#[derive(Default)]
3706pub struct RegistryBuilder {
3707    hooks: Vec<Registration>,
3708}
3709
3710impl fmt::Debug for RegistryBuilder {
3711    /// Lists the hook names registered so far, in registration order.
3712    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3713        debug_hook_names("RegistryBuilder", self.hooks.iter(), formatter)
3714    }
3715}
3716
3717// A registry and the builder it is frozen from are both identified by the
3718// ordered hook roster they carry, and registration order is dispatch order.
3719fn debug_hook_names<'a>(
3720    name: &str,
3721    hooks: impl Iterator<Item = &'a Registration>,
3722    formatter: &mut fmt::Formatter<'_>,
3723) -> fmt::Result {
3724    formatter
3725        .debug_struct(name)
3726        .field(
3727            "hooks",
3728            &hooks
3729                .map(|registration| registration.name.as_str())
3730                .collect::<Vec<_>>(),
3731        )
3732        .finish()
3733}
3734
3735impl RegistryBuilder {
3736    /// Creates an empty builder.
3737    #[must_use]
3738    pub fn new() -> Self {
3739        Self::default()
3740    }
3741
3742    /// Appends one complete hook registration in observable fan-out order.
3743    pub fn register(&mut self, hook: Registration) -> &mut Self {
3744        self.hooks.push(hook);
3745        self
3746    }
3747
3748    /// Validates and freezes the one runtime registry owned by an Agent.
3749    pub(crate) fn build_runtime(self) -> Result<RuntimeRegistry, RegistryError> {
3750        self.freeze().map(RuntimeRegistry::new)
3751    }
3752
3753    fn freeze(self) -> Result<FrozenRegistry, RegistryError> {
3754        let mut names = std::collections::HashSet::new();
3755        let mut hooks = Vec::with_capacity(self.hooks.len());
3756        for registration in self.hooks {
3757            if registration.name.is_empty() {
3758                return Err(RegistryError::EmptyName);
3759            }
3760            if !names.insert(registration.name.clone()) {
3761                return Err(RegistryError::DuplicateName(registration.name));
3762            }
3763            hooks.push(RegisteredHook { registration });
3764        }
3765        Ok(FrozenRegistry {
3766            hooks: hooks.into(),
3767        })
3768    }
3769}
3770
3771/// Frozen registration storage owned by the Agent runtime registry.
3772#[derive(Clone)]
3773pub(crate) struct FrozenRegistry {
3774    hooks: Arc<[RegisteredHook]>,
3775}
3776
3777/// Agent-private runtime hook registry with stable registration-order fan-out.
3778#[derive(Clone)]
3779pub(crate) struct RuntimeRegistry {
3780    frozen: FrozenRegistry,
3781}
3782
3783impl RuntimeRegistry {
3784    const fn new(frozen: FrozenRegistry) -> Self {
3785        Self { frozen }
3786    }
3787}
3788
3789impl std::ops::Deref for RuntimeRegistry {
3790    type Target = FrozenRegistry;
3791
3792    fn deref(&self) -> &Self::Target {
3793        &self.frozen
3794    }
3795}
3796
3797impl fmt::Debug for RuntimeRegistry {
3798    /// Lists the frozen hook roster, in registration order.
3799    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3800        debug_hook_names(
3801            "RuntimeRegistry",
3802            self.frozen.hooks.iter().map(|hook| &hook.registration),
3803            formatter,
3804        )
3805    }
3806}
3807
3808impl FrozenRegistry {
3809    /// Returns the number of named registrations.
3810    #[must_use]
3811    pub(crate) fn len(&self) -> usize {
3812        self.hooks.len()
3813    }
3814
3815    /// Reports whether no hook is registered.
3816    #[cfg(test)]
3817    #[must_use]
3818    pub(crate) fn is_empty(&self) -> bool {
3819        self.hooks.is_empty()
3820    }
3821
3822    /// Iterates stable registration names.
3823    #[must_use]
3824    pub(crate) fn names(&self) -> impl ExactSizeIterator<Item = &str> {
3825        self.hooks
3826            .iter()
3827            .map(|hook| hook.registration.name.as_str())
3828    }
3829
3830    /// Reports whether any hook requires optional Session state support.
3831    #[must_use]
3832    pub(crate) fn requires_session_state(&self) -> bool {
3833        self.hooks
3834            .iter()
3835            .any(|hook| hook.registration.requires_session_state)
3836    }
3837
3838    pub(crate) fn run_hooks(&self) -> impl Iterator<Item = RegistrationAdapter<'_, dyn RunHooks>> {
3839        self.hooks
3840            .iter()
3841            .enumerate()
3842            .filter_map(|(index, registered)| {
3843                registered
3844                    .registration
3845                    .run
3846                    .as_deref()
3847                    .map(|hook| RegistrationAdapter {
3848                        index,
3849                        name: registered.registration.name.as_str(),
3850                        requires_session_state: registered.registration.requires_session_state,
3851                        hook,
3852                    })
3853            })
3854    }
3855
3856    pub(crate) fn input_hooks(
3857        &self,
3858    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn InputHooks>> {
3859        self.hooks
3860            .iter()
3861            .enumerate()
3862            .filter_map(|(index, registered)| {
3863                registered
3864                    .registration
3865                    .input
3866                    .as_deref()
3867                    .map(|hook| RegistrationAdapter {
3868                        index,
3869                        name: registered.registration.name.as_str(),
3870                        requires_session_state: registered.registration.requires_session_state,
3871                        hook,
3872                    })
3873            })
3874    }
3875
3876    pub(crate) fn turn_step_hooks(
3877        &self,
3878    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn TurnStepHooks>> {
3879        self.hooks
3880            .iter()
3881            .enumerate()
3882            .filter_map(|(index, registered)| {
3883                registered
3884                    .registration
3885                    .turn_step
3886                    .as_deref()
3887                    .map(|hook| RegistrationAdapter {
3888                        index,
3889                        name: registered.registration.name.as_str(),
3890                        requires_session_state: registered.registration.requires_session_state,
3891                        hook,
3892                    })
3893            })
3894    }
3895
3896    pub(crate) fn model_hooks(
3897        &self,
3898    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ModelHooks>> {
3899        self.hooks
3900            .iter()
3901            .enumerate()
3902            .filter_map(|(index, registered)| {
3903                registered
3904                    .registration
3905                    .model
3906                    .as_deref()
3907                    .map(|hook| RegistrationAdapter {
3908                        index,
3909                        name: registered.registration.name.as_str(),
3910                        requires_session_state: registered.registration.requires_session_state,
3911                        hook,
3912                    })
3913            })
3914    }
3915
3916    pub(crate) fn tool_hooks(
3917        &self,
3918    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ToolHooks>> {
3919        self.hooks
3920            .iter()
3921            .enumerate()
3922            .filter_map(|(index, registered)| {
3923                registered
3924                    .registration
3925                    .tool
3926                    .as_deref()
3927                    .map(|hook| RegistrationAdapter {
3928                        index,
3929                        name: registered.registration.name.as_str(),
3930                        requires_session_state: registered.registration.requires_session_state,
3931                        hook,
3932                    })
3933            })
3934    }
3935
3936    pub(crate) fn owned_tool_hooks(
3937        &self,
3938    ) -> impl Iterator<Item = OwnedToolRegistrationAdapter> + '_ {
3939        self.hooks
3940            .iter()
3941            .enumerate()
3942            .filter_map(|(index, registered)| {
3943                registered
3944                    .registration
3945                    .tool
3946                    .as_ref()
3947                    .map(|hook| OwnedToolRegistrationAdapter {
3948                        index,
3949                        name: registered.registration.name.clone(),
3950                        requires_session_state: registered.registration.requires_session_state,
3951                        hook: Arc::clone(hook),
3952                    })
3953            })
3954    }
3955
3956    pub(crate) fn observer_hooks(
3957        &self,
3958    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ObserverHooks>> {
3959        self.hooks
3960            .iter()
3961            .enumerate()
3962            .filter_map(|(index, registered)| {
3963                registered
3964                    .registration
3965                    .observer
3966                    .as_deref()
3967                    .map(|hook| RegistrationAdapter {
3968                        index,
3969                        name: registered.registration.name.as_str(),
3970                        requires_session_state: registered.registration.requires_session_state,
3971                        hook,
3972                    })
3973            })
3974    }
3975
3976    pub(crate) fn transcript_hooks(
3977        &self,
3978    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn TranscriptHooks>> {
3979        self.hooks
3980            .iter()
3981            .enumerate()
3982            .filter_map(|(index, registered)| {
3983                registered
3984                    .registration
3985                    .transcript
3986                    .as_deref()
3987                    .map(|hook| RegistrationAdapter {
3988                        index,
3989                        name: registered.registration.name.as_str(),
3990                        requires_session_state: registered.registration.requires_session_state,
3991                        hook,
3992                    })
3993            })
3994    }
3995
3996    /// Fans out Agent teardown and collects every error without short-circuiting.
3997    ///
3998    /// This operation is crate-private and reached in production only by
3999    /// [`crate::runtime::agent::Agent::close`]. A callback panic is isolated as a
4000    /// registration-attributed [`crate::runtime::agent::ClosePanickedError`]. Later
4001    /// callbacks still run, so one broken teardown cannot suppress its peers.
4002    ///
4003    /// The captured panic payload is deliberately forgotten rather than dropped:
4004    /// [`std::panic::panic_any`] permits payloads whose destructor also panics, and
4005    /// dropping such a payload would escape this isolation boundary. This leaks one
4006    /// captured payload value per panicking callback invocation, confined to this
4007    /// already-pathological path, in exchange for preserving the teardown guarantee
4008    /// for every legal payload.
4009    #[must_use]
4010    pub(crate) fn close(&self) -> Vec<AttributedError> {
4011        let panic_error = HookError::new(crate::runtime::agent::ClosePanickedError);
4012        let mut failures = Vec::new();
4013        for hook in self.hooks.iter() {
4014            let Some(teardown) = &hook.registration.teardown else {
4015                continue;
4016            };
4017            let error = match catch_unwind(AssertUnwindSafe(|| teardown.close())) {
4018                Ok(Ok(())) => continue,
4019                Ok(Err(error)) => error,
4020                Err(payload) => {
4021                    // A legal `panic_any` payload may itself panic in `Drop`. There
4022                    // is no generally safe way to destroy an arbitrary captured
4023                    // payload: catching that second panic only produces another
4024                    // arbitrary payload to dispose of. Leak exactly this payload
4025                    // instead, so teardown isolation remains total and later
4026                    // registrations still run.
4027                    std::mem::forget(payload);
4028                    panic_error.clone()
4029                }
4030            };
4031            failures.push(AttributedError {
4032                name: hook.registration.name.clone(),
4033                error,
4034            });
4035        }
4036        failures
4037    }
4038}
4039
4040pub(crate) const fn lifecycle_hook_name(kind: LifecycleKind) -> &'static str {
4041    match kind {
4042        LifecycleKind::RunStart => "OnRunStart",
4043        LifecycleKind::RunEnd => "OnRunEnd",
4044        LifecycleKind::TurnStart => "OnTurnStart",
4045        LifecycleKind::TurnEnd => "OnTurnEnd",
4046        LifecycleKind::StepStart => "OnStepStart",
4047        LifecycleKind::StepEnd => "OnStepEnd",
4048        LifecycleKind::GenerationStart => "OnGenerationStart",
4049        LifecycleKind::GenerationEnd => "OnGenerationEnd",
4050        LifecycleKind::ToolCallStart => "OnToolCallStart",
4051        LifecycleKind::ToolCallEnd => "OnToolCallEnd",
4052    }
4053}
4054
4055fn emit_observer_panic(emitter: &dyn Emitter, registration: &str, callback: &str) {
4056    let payload = format!("{registration}:{callback}")
4057        .into_bytes()
4058        .into_boxed_slice();
4059    emitter.emit_audit(audit::Event::new(
4060        "hook.observer_panic".to_owned(),
4061        Some(payload),
4062    ));
4063}
4064
4065pub(crate) struct ScopeFactory<'a> {
4066    coord: &'a Coord,
4067    run_state: &'a run_state::Store,
4068    session_state: &'a session_state::Reader,
4069    session_state_writer: Option<&'a session_state::Writer>,
4070    requires_session_state: bool,
4071    transcript: TranscriptSource<'a>,
4072    emitter: &'a dyn Emitter,
4073    direct_audit: DirectAuditSink<'a>,
4074}
4075
4076impl<'a> ScopeFactory<'a> {
4077    /// Builds scopes for one hook adapter. `requires_session_state` is taken
4078    /// from that adapter's frozen registration metadata; a writer is never
4079    /// exposed when the declaration is false.
4080    pub(crate) const fn new(
4081        coord: &'a Coord,
4082        run_state: &'a run_state::Store,
4083        session_state: &'a session_state::Reader,
4084        session_state_writer: Option<&'a session_state::Writer>,
4085        requires_session_state: bool,
4086        transcript: TranscriptSource<'a>,
4087        emitter: &'a dyn Emitter,
4088    ) -> Self {
4089        Self {
4090            coord,
4091            run_state,
4092            session_state,
4093            session_state_writer,
4094            requires_session_state,
4095            transcript,
4096            emitter,
4097            direct_audit: DirectAuditSink(emitter),
4098        }
4099    }
4100
4101    const fn read_base(&self) -> ReadBase<'a> {
4102        ReadBase {
4103            session: SessionIdentity(self.coord),
4104            coord: self.coord,
4105            run_state: self.run_state,
4106            session_state: self.session_state,
4107            transcript: self.transcript,
4108        }
4109    }
4110
4111    const fn write_base(&self) -> WriteBase<'a> {
4112        WriteBase {
4113            read: self.read_base(),
4114            session_state: if self.requires_session_state {
4115                self.session_state_writer
4116            } else {
4117                None
4118            },
4119        }
4120    }
4121
4122    const fn control_base(&self) -> ControlBase<'a> {
4123        ControlBase {
4124            write: self.write_base(),
4125            emitter: self.emitter,
4126        }
4127    }
4128
4129    const fn staged_base(&self, staged: &'a StagedTranscript) -> StagedBase<'a> {
4130        StagedBase {
4131            control: self.control_base(),
4132            staged,
4133        }
4134    }
4135
4136    pub(crate) const fn prepare(
4137        &self,
4138        staged: &'a StagedTranscript,
4139        session_state_stage: Option<&'a session_state::StagedWriter>,
4140        base_snapshot: &'a Snapshot,
4141        input: &'a [Part],
4142    ) -> PrepareScope<'a> {
4143        PrepareScope {
4144            base: PrepareBase {
4145                read: self.read_base(),
4146                session_state: if self.requires_session_state {
4147                    session_state_stage
4148                } else {
4149                    None
4150                },
4151            },
4152            staged,
4153            base_snapshot,
4154            input,
4155        }
4156    }
4157
4158    pub(crate) const fn compose_continuation(
4159        &self,
4160        staged: &'a StagedTranscript,
4161        continuation: &'a [Part],
4162        continuations: usize,
4163        turns: usize,
4164    ) -> ContinuationScope<'a> {
4165        ContinuationScope {
4166            base: self.staged_base(staged),
4167            continuation,
4168            continuations,
4169            turns,
4170        }
4171    }
4172
4173    pub(crate) const fn decide_stop(&self) -> StopDecisionScope<'a> {
4174        StopDecisionScope {
4175            base: self.control_base(),
4176        }
4177    }
4178
4179    pub(crate) const fn input_admit(
4180        &self,
4181        target: InputTarget,
4182        items: &'a [Item],
4183    ) -> InputAdmitScope<'a> {
4184        InputAdmitScope {
4185            base: self.control_base(),
4186            target,
4187            items,
4188        }
4189    }
4190
4191    pub(crate) const fn turn(
4192        &self,
4193        staged: &'a StagedTranscript,
4194        trigger: &'a [Item],
4195    ) -> TurnScope<'a> {
4196        TurnScope {
4197            base: self.staged_base(staged),
4198            trigger,
4199        }
4200    }
4201
4202    pub(crate) const fn before_step<'scope>(
4203        &'scope self,
4204        staged: &'scope StagedTranscript,
4205        model: &'scope Info,
4206        plan: &'scope mut RequestPlan,
4207    ) -> BeforeStepScope<'scope> {
4208        BeforeStepScope {
4209            base: self.staged_base(staged),
4210            model,
4211            plan,
4212        }
4213    }
4214
4215    pub(crate) const fn after_step(
4216        &self,
4217        staged: &'a StagedTranscript,
4218        snapshot: &'a Arc<StepSnapshot>,
4219    ) -> AfterStepScope<'a> {
4220        AfterStepScope {
4221            base: self.staged_base(staged),
4222            snapshot,
4223        }
4224    }
4225
4226    pub(crate) const fn before_model(
4227        &self,
4228        snapshot: &'a Arc<StepSnapshot>,
4229        request: &'a Request,
4230    ) -> BeforeModelScope<'a> {
4231        BeforeModelScope {
4232            base: self.control_base(),
4233            snapshot,
4234            request,
4235        }
4236    }
4237
4238    pub(crate) const fn after_model(
4239        &self,
4240        snapshot: &'a Arc<StepSnapshot>,
4241        output: &'a Assistant,
4242        generated: bool,
4243        finish_reason: &'a str,
4244        completion: CompletionReason,
4245    ) -> AfterModelScope<'a> {
4246        AfterModelScope {
4247            base: self.control_base(),
4248            snapshot,
4249            output,
4250            generated,
4251            finish_reason,
4252            completion,
4253        }
4254    }
4255
4256    pub(crate) const fn tool_call(
4257        &self,
4258        snapshot: &'a Arc<StepSnapshot>,
4259        call: &'a ToolCall,
4260    ) -> ToolCallScope<'a> {
4261        ToolCallScope {
4262            base: self.control_base(),
4263            snapshot,
4264            call,
4265        }
4266    }
4267
4268    pub(crate) const fn tool_result(
4269        &self,
4270        snapshot: &'a Arc<StepSnapshot>,
4271        call: &'a ToolCall,
4272        disposition: CallDisposition,
4273        result: &'a ToolResult,
4274    ) -> ToolResultScope<'a> {
4275        ToolResultScope {
4276            base: self.control_base(),
4277            snapshot,
4278            call,
4279            disposition,
4280            result,
4281        }
4282    }
4283
4284    pub(crate) const fn after_tool_commit(
4285        &self,
4286        staged: &'a StagedTranscript,
4287        snapshot: &'a Arc<StepSnapshot>,
4288        result: &'a ToolResult,
4289    ) -> AfterToolCommitScope<'a> {
4290        AfterToolCommitScope {
4291            base: self.staged_base(staged),
4292            snapshot,
4293            result,
4294        }
4295    }
4296
4297    pub(crate) fn observer(&self, snapshot: Option<&'a Arc<StepSnapshot>>) -> ObserverScope<'_> {
4298        ObserverScope {
4299            base: self.read_base(),
4300            snapshot,
4301            audit_sink: &self.direct_audit,
4302        }
4303    }
4304
4305    pub(crate) const fn read(&self) -> ReadScope<'a> {
4306        ReadScope {
4307            base: self.read_base(),
4308        }
4309    }
4310}