reef_core/runtime/tool.rs
1//! Immutable tool registration, per-Step exposure, mapping, and admission.
2//!
3//! The registration and snapshot split follows ADR-009. Runtime names are
4//! validated here while [`crate::value::tool_call::Name`] remains the open
5//! wire value validated at model boundaries.
6
7use std::collections::HashSet;
8use std::error::Error;
9use std::fmt::{self, Debug, Display, Formatter};
10use std::future::Future;
11use std::pin::Pin;
12use std::sync::Arc;
13use std::task::Poll;
14#[cfg(test)]
15use std::task::{Context, Waker};
16
17use crate::cancel::Token;
18
19use crate::opaque::{Envelope, EnvelopeError, Payload};
20use crate::redact;
21use crate::runtime::event::ToolEmitter;
22use crate::runtime::model::{ClientTool, RequestPlan};
23use crate::transcript::store::Snapshot;
24use crate::value::tool_call::{self, Id, ToolCall, ToolPartError, ToolResult};
25
26/// A stable validation failure for a runtime tool name.
27#[derive(Clone, Copy, Debug, Eq, PartialEq)]
28#[non_exhaustive]
29pub enum NameError {
30 /// The local name component is empty.
31 EmptyLocal,
32 /// A supplied namespace is empty.
33 EmptyNamespace,
34 /// A component contains the reserved namespace separator `/`.
35 ReservedSeparator,
36}
37
38impl Display for NameError {
39 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
40 match self {
41 Self::EmptyLocal => formatter.write_str("tool local name is empty"),
42 Self::EmptyNamespace => formatter.write_str("tool namespace is empty"),
43 Self::ReservedSeparator => formatter.write_str("tool name component contains '/'"),
44 }
45 }
46}
47
48impl Error for NameError {}
49
50/// A nonempty, namespace-aware canonical runtime tool name.
51///
52/// The namespace is **syntax only**. Core owns the grammar — an optional
53/// namespace component, one reserved `/` separator, both components non-empty —
54/// and the canonical spelling used as the collision and routing key. It assigns
55/// no meaning to any namespace value, reserves none, and derives no behaviour
56/// from one; deciding what a namespace stands for is composition-layer policy.
57///
58/// Namespacing creates no resolution order: `a/x` and `x` are different
59/// canonical names and never collide, while two registrations of `a/x` collide
60/// regardless of which source produced each.
61///
62/// [`Name::to_wire`] and [`Name::parse_canonical`] are inverses, so a
63/// composition layer that aggregates several tool sources can recover core's
64/// exact collision key from an advertised spelling instead of re-implementing
65/// the split.
66///
67/// ```
68/// use reef_core::runtime::tool;
69///
70/// let scoped = tool::Name::namespaced("server".to_owned(), "search".to_owned()).unwrap();
71/// let wire = scoped.to_wire();
72/// assert_eq!(wire.as_str(), "server/search");
73/// assert_eq!(tool::Name::parse_canonical(wire.as_str()).unwrap(), scoped);
74///
75/// // A namespaced name never collides with the bare local spelling.
76/// let plain = tool::Name::parse_canonical("search").unwrap();
77/// assert_eq!(plain.namespace(), None);
78/// assert_ne!(plain, scoped);
79/// ```
80#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
81pub struct Name {
82 namespace: Option<String>,
83 local: String,
84 canonical: String,
85}
86
87impl Name {
88 /// Creates an unnamespaced tool name.
89 ///
90 /// # Errors
91 ///
92 /// [`NameError::EmptyLocal`] if `local` has no characters, or
93 /// [`NameError::ReservedSeparator`] if it contains `/`. The separator is
94 /// refused rather than escaped because it is the collision key's only
95 /// structure: a local name carrying one would be indistinguishable from a
96 /// namespaced name built by [`Name::namespaced`].
97 pub fn local(local: String) -> Result<Self, NameError> {
98 Self::from_parts(None, local)
99 }
100
101 /// Creates a namespaced tool name.
102 ///
103 /// # Errors
104 ///
105 /// [`NameError::EmptyLocal`] for an empty `local`,
106 /// [`NameError::EmptyNamespace`] for an empty `namespace` — which would spell
107 /// the same canonical name as an unnamespaced one while claiming to be
108 /// scoped — or [`NameError::ReservedSeparator`] if either component contains
109 /// `/`. Nothing here validates what the namespace means: core owns the
110 /// grammar and reserves no value.
111 pub fn namespaced(namespace: String, local: String) -> Result<Self, NameError> {
112 Self::from_parts(Some(namespace), local)
113 }
114
115 /// Splits a canonical spelling back into its validated components.
116 ///
117 /// This is the exact inverse of [`Name::canonical`] and [`Name::to_wire`]:
118 /// the spelling is split at its first reserved separator and the components
119 /// are validated by the same rules [`Name::local`] and [`Name::namespaced`]
120 /// apply, so no caller has to reproduce the split to obtain core's collision
121 /// key.
122 ///
123 /// # Errors
124 ///
125 /// Returns [`NameError::EmptyLocal`] for an empty spelling or one ending in
126 /// the separator, [`NameError::EmptyNamespace`] for one beginning with it,
127 /// and [`NameError::ReservedSeparator`] for a spelling carrying more than
128 /// one.
129 pub fn parse_canonical(canonical: &str) -> Result<Self, NameError> {
130 match canonical.split_once('/') {
131 Some((namespace, local)) => {
132 Self::from_parts(Some(namespace.to_owned()), local.to_owned())
133 }
134 None => Self::from_parts(None, canonical.to_owned()),
135 }
136 }
137
138 fn from_parts(namespace: Option<String>, local: String) -> Result<Self, NameError> {
139 if local.is_empty() {
140 return Err(NameError::EmptyLocal);
141 }
142 if local.contains('/') {
143 return Err(NameError::ReservedSeparator);
144 }
145 if matches!(namespace.as_deref(), Some("")) {
146 return Err(NameError::EmptyNamespace);
147 }
148 if namespace
149 .as_deref()
150 .is_some_and(|value| value.contains('/'))
151 {
152 return Err(NameError::ReservedSeparator);
153 }
154 let canonical = namespace
155 .as_ref()
156 .map_or_else(|| local.clone(), |value| format!("{value}/{local}"));
157 Ok(Self {
158 namespace,
159 local,
160 canonical,
161 })
162 }
163
164 /// Returns the optional namespace.
165 #[must_use]
166 pub fn namespace(&self) -> Option<&str> {
167 self.namespace.as_deref()
168 }
169
170 /// Returns the nonempty local component.
171 #[must_use]
172 pub fn local_name(&self) -> &str {
173 &self.local
174 }
175
176 /// Returns the stable canonical spelling used for collision and routing.
177 #[must_use]
178 pub fn canonical(&self) -> &str {
179 &self.canonical
180 }
181
182 /// Renders the uninterpreted wire spelling advertised to a model.
183 ///
184 /// The result is a [`crate::value::tool_call::Name`], the open leaf value a
185 /// model emission also arrives as, which is what makes the advertise/route
186 /// round trip typed on both sides.
187 #[must_use]
188 pub fn to_wire(&self) -> tool_call::Name {
189 tool_call::Name::new(self.canonical.clone())
190 }
191}
192
193/// An owned, provider-neutral model descriptor.
194///
195/// [`Descriptor::input_schema`] is a [`Payload`] — uninterpreted owned bytes —
196/// and it is the per-tool channel a composition layer constrains sampling
197/// through. Core never parses it, so a strict JSON schema, a grammar, or a
198/// provider-specific envelope around either are all expressible here, and the
199/// adapter that writes the bytes is the same one that reads them. This is why
200/// [`crate::runtime::model::SamplingParams::output_schema`] being request-level
201/// is not a gap: the tool-level placement already exists, one level down.
202#[derive(Clone)]
203pub struct Descriptor {
204 name: Name,
205 description: String,
206 input_schema: Payload,
207}
208
209impl Debug for Descriptor {
210 /// Names the tool and sizes the two fields the model would read.
211 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
212 formatter
213 .debug_struct("Descriptor")
214 .field("name", &self.name)
215 .field("description", &redact::Bytes(self.description.len()))
216 .field("input_schema", &self.input_schema)
217 .finish()
218 }
219}
220
221impl Descriptor {
222 /// Creates a descriptor from owned fields.
223 #[must_use]
224 pub const fn new(name: Name, description: String, input_schema: Payload) -> Self {
225 Self {
226 name,
227 description,
228 input_schema,
229 }
230 }
231
232 /// Returns the canonical runtime name.
233 #[must_use]
234 pub const fn name(&self) -> &Name {
235 &self.name
236 }
237
238 /// Returns the model-facing description.
239 #[must_use]
240 pub fn description(&self) -> &str {
241 &self.description
242 }
243
244 /// Returns the provider-neutral input schema.
245 ///
246 /// Core assigns these bytes no meaning; they reach the provider unchanged as
247 /// [`ClientTool::input_schema`].
248 #[must_use]
249 pub const fn input_schema(&self) -> &Payload {
250 &self.input_schema
251 }
252
253 fn client_model_tool(&self) -> ClientTool {
254 // Matches `ClientTool`'s owned producer shape.
255 ClientTool::new(
256 self.name.to_wire(),
257 self.description.clone(),
258 self.input_schema.clone(),
259 )
260 }
261}
262
263/// Declarative admission classification from ADR-010.
264#[derive(Clone, Copy, Debug, Eq, PartialEq)]
265pub enum Approval {
266 /// Invalid or unknown admission facts; execution must fail closed.
267 Invalid,
268 /// Bypass the policy gate and continue normal execution checks.
269 NotRequired,
270 /// Require a gate decision.
271 Required,
272 /// Deny without consulting a gate.
273 Forbidden,
274}
275
276/// Owned admission facts captured with a client tool binding.
277///
278/// # There is no concurrency axis here, and that is a decision
279///
280/// A batch runs every executable slot concurrently, and nothing in this type
281/// says a tool must run alone. The three reference agents each have such a
282/// mechanism, so the *need* is real — but they spell it three different ways
283/// (a reader/writer lane, an execution-mode enum, a concurrency-safety flag),
284/// which is the signal that exclusivity is a policy rather than a floor.
285///
286/// The declaration and the scheduling cannot be separated. A field core never
287/// reads would be public surface with no production consumer; a field core does
288/// read makes core choose what exclusivity means — whether a mutating tool
289/// excludes every peer or only other mutators, whether the scope is the batch,
290/// the Step or the Session, and which side of the gate the wait happens on.
291///
292/// A composition layer expresses it with what it already owns: one
293/// `RwLock`-style lane captured by its own [`Executor`] implementations at
294/// registration, read-acquired by the concurrency-safe tools and
295/// write-acquired by the exclusive one. Nothing is lost by putting it there.
296/// The batch engine polls every slot in one future without spawning, so a slot
297/// parked on the lane yields to its siblings instead of starving them; the
298/// acquire future is cancellation-safe, so the engine's cancel-then-drop
299/// ordering still applies; and outcomes are materialised in source order (C14),
300/// so serialising execution does not change what gets committed. ADR-009
301/// already assigned "per-tool parallel opt-in" to composition, and ADR-022
302/// re-examined that and kept it.
303#[derive(Clone, Debug)]
304pub struct Requirements {
305 approval: Approval,
306 facts: Vec<Envelope>,
307}
308
309impl Requirements {
310 /// Creates owned admission requirements.
311 #[must_use]
312 pub const fn new(approval: Approval, facts: Vec<Envelope>) -> Self {
313 Self { approval, facts }
314 }
315
316 /// Returns the declarative approval classification.
317 #[must_use]
318 pub const fn approval(&self) -> Approval {
319 self.approval
320 }
321
322 /// Returns provider-neutral admission facts.
323 #[must_use]
324 pub fn facts(&self) -> &[Envelope] {
325 &self.facts
326 }
327}
328
329/// An ordinary executor failure that becomes a business result.
330///
331/// The message is what the model is told: reef records
332/// [`Display`] as the tool's output and the transcript keeps text,
333/// not types. So the message has to be complete on its own, and
334/// [`with_source`](Self::with_source) does not extend it — attaching a source
335/// keeps the concrete failure as a *value*, for whoever inspects this error in
336/// process, and changes nothing about what the model reads.
337///
338/// That inspection is why the source exists. An executor almost always fails
339/// *because* something underneath it did — an I/O error, a transport failure, a
340/// timeout — and a composition layer that wraps executors, retries them, or
341/// classifies their failures needs the reason by its type rather than by
342/// matching on a sentence:
343///
344/// ```
345/// use std::io;
346/// use reef_core::runtime::tool;
347///
348/// let failure = tool::ExecutorError::new("reading the manifest failed".to_owned())
349/// .with_source(io::Error::from(io::ErrorKind::NotFound));
350///
351/// // The message alone is what the model sees.
352/// assert_eq!(failure.to_string(), "reading the manifest failed");
353///
354/// // The reason is still recoverable by its own type.
355/// let cause = std::error::Error::source(&failure).expect("a source was attached");
356/// let cause = cause.downcast_ref::<io::Error>().expect("the concrete cause");
357/// assert_eq!(cause.kind(), io::ErrorKind::NotFound);
358/// ```
359#[derive(Clone)]
360pub struct ExecutorError {
361 message: String,
362 source: Option<Arc<dyn Error + Send + Sync>>,
363}
364
365impl ExecutorError {
366 /// Creates an owned executor diagnostic.
367 #[must_use]
368 pub const fn new(message: String) -> Self {
369 Self {
370 message,
371 source: None,
372 }
373 }
374
375 /// Retains the concrete failure this diagnostic is about.
376 ///
377 /// Returned from [`Error::source`], so the cause downcasts back to the
378 /// caller's own type. It does not affect the message, equality, or what the
379 /// model is told; see the type's own documentation for why.
380 #[must_use]
381 pub fn with_source(mut self, source: impl Error + Send + Sync + 'static) -> Self {
382 self.source = Some(Arc::new(source));
383 self
384 }
385}
386
387impl fmt::Debug for ExecutorError {
388 /// Renders the message and then every link of the chain, each through `Display`.
389 ///
390 /// Printing only the message would discard the reason
391 /// [`with_source`](Self::with_source) retains, which is the part a reader is
392 /// usually after. `Display` rather than the link's own `Debug`, because a
393 /// cause is whatever an executor handed back: text this crate neither writes
394 /// nor reviews, whose `Display` is the diagnostic the type is contracted to
395 /// produce. This is the same rendering [`HookError`] uses.
396 ///
397 /// [`HookError`]: crate::runtime::hook::HookError
398 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
399 let mut tuple = formatter.debug_tuple("ExecutorError");
400 tuple.field(&self.message);
401 let mut link = Error::source(self);
402 while let Some(error) = link {
403 tuple.field(&error.to_string());
404 link = error.source();
405 }
406 tuple.finish()
407 }
408}
409
410impl Display for ExecutorError {
411 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
412 formatter.write_str(&self.message)
413 }
414}
415
416/// Compares the diagnostic message and nothing else.
417///
418/// A retained source is an arbitrary third-party error with no equality of its
419/// own, so there is no answer to whether two of them are "the same"; comparing
420/// them by pointer would make two errors that say the same thing unequal, which
421/// is worse than not comparing them. The message is what this type is compared
422/// for — asserting on a diagnostic — so that is what equality means here.
423impl PartialEq for ExecutorError {
424 fn eq(&self, other: &Self) -> bool {
425 self.message == other.message
426 }
427}
428
429impl Eq for ExecutorError {}
430
431impl Error for ExecutorError {
432 fn source(&self) -> Option<&(dyn Error + 'static)> {
433 self.source
434 .as_ref()
435 .map(|source| source.as_ref() as &(dyn Error + 'static))
436 }
437}
438
439/// The closed per-call context supplied to one [`Executor::execute`].
440///
441/// This is trusted runtime-provided context, never a dependency-injection bag:
442/// optional capabilities such as process execution are constructor-injected into
443/// the concrete executor and never flow through here.
444///
445/// The struct has no public constructor and no public fields, so only a core
446/// adapter can mint one. Its emit capability is limited to
447/// [`crate::runtime::event::ToolEmitter`], which itself can only produce audit
448/// and error facts, so producer authority and outward event state never leak to
449/// an executor.
450#[derive(Debug)]
451pub struct Invocation {
452 session_id: Option<String>,
453 transcript: Arc<Snapshot>,
454 call_id: Id,
455 emitter: ToolEmitter,
456}
457
458impl Invocation {
459 /// Returns the trusted host-provided session identity, when one exists.
460 ///
461 /// Core does not require this to be nonempty or globally unique; treat it as
462 /// correlation metadata rather than an authorization credential. Model tool
463 /// arguments can never override it.
464 #[must_use]
465 pub fn session_id(&self) -> Option<&str> {
466 self.session_id.as_deref()
467 }
468
469 /// Returns the frozen Step-top transcript shared by every provider
470 /// resolution and every invocation in the same Step.
471 #[must_use]
472 pub fn transcript(&self) -> &Snapshot {
473 &self.transcript
474 }
475
476 /// Returns the model-assigned identity of this invocation within its Step.
477 #[must_use]
478 pub const fn call_id(&self) -> &Id {
479 &self.call_id
480 }
481
482 /// Returns the invocation-scoped audit/error emit capability.
483 #[must_use]
484 pub const fn emitter(&self) -> &ToolEmitter {
485 &self.emitter
486 }
487
488 pub(crate) const fn new(
489 session_id: Option<String>,
490 transcript: Arc<Snapshot>,
491 call_id: Id,
492 emitter: ToolEmitter,
493 ) -> Self {
494 Self {
495 session_id,
496 transcript,
497 call_id,
498 emitter,
499 }
500 }
501}
502
503/// A concrete executor with one registration-specific output type.
504///
505/// An executor returns whatever type is natural for it — a `String`, a struct, a
506/// byte buffer — and [`Registration::client`] pairs that type with the one
507/// mapper that turns it into a closed [`ToolResult`]. Nothing else in the crate
508/// sees [`Executor::Output`], which is why it can be anything.
509///
510/// **An ordinary failure is not `Err`.** `Err(ExecutorError)` says the adapter
511/// itself broke; a tool that ran and did not like what it found returns
512/// `Ok(...)` and lets the mapper produce
513/// [`crate::value::tool_call::ToolResult::BusinessError`],
514/// which the model reads and can act on.
515///
516/// ```
517/// use std::future::{Future, ready};
518/// use std::sync::Arc;
519///
520/// use reef_core::cancel;
521/// use reef_core::opaque;
522/// use reef_core::runtime::tool;
523/// use reef_core::value::tool_call;
524///
525/// #[derive(Debug)]
526/// struct Reverse;
527///
528/// impl tool::Executor for Reverse {
529/// type Output = String;
530///
531/// fn execute(
532/// &self,
533/// _invocation: &tool::Invocation,
534/// call: &tool_call::ToolCall,
535/// _cancellation: cancel::Token,
536/// ) -> impl Future<Output = Result<Self::Output, tool::ExecutorError>> + Send {
537/// // Arguments are uninterpreted bytes: reef never parsed them, and the
538/// // schema this tool published is what promised their shape.
539/// let arguments = String::from_utf8_lossy(call.arguments().as_bytes()).into_owned();
540/// ready(Ok(arguments.chars().rev().collect()))
541/// }
542/// }
543///
544/// let registration = tool::Registration::client(
545/// tool::Descriptor::new(
546/// tool::Name::local("text.reverse".to_owned()).unwrap(),
547/// "Reverses its arguments".to_owned(),
548/// opaque::Payload::copy_from_slice(br#"{"type":"object"}"#),
549/// ),
550/// tool::Requirements::new(tool::Approval::NotRequired, Vec::new()),
551/// Arc::new(Reverse),
552/// // The mapper is the only thing that sees `Output`.
553/// Arc::new(|output: String| Ok(tool_call::ToolResult::success_text(output))),
554/// );
555/// assert_eq!(registration.lane(), tool::Lane::Client);
556/// ```
557///
558/// # Cancellation
559///
560/// The future returned by [`execute`](Executor::execute) must be
561/// cancellation-safe; that method's own documentation states exactly what reef
562/// requires of it.
563pub trait Executor: Send + Sync + 'static {
564 /// Open adapter output consumed only by the paired registration mapper.
565 type Output: Send + 'static;
566
567 /// Executes one effective call under its closed invocation context; ordinary
568 /// errors become business results only when execution completion wins its
569 /// race with cancellation.
570 ///
571 /// The returned future must be cancellation-safe: its caller may drop it at
572 /// any await point after first cancelling the supplied token. Dropping the
573 /// future must synchronously release resources or initiate owned cleanup,
574 /// and it must not detach any work. If background work is unavoidable, the
575 /// future itself must own that work and its `Drop` path must abort it or
576 /// otherwise synchronously bring it under cleanup that remains owned.
577 fn execute(
578 &self,
579 invocation: &Invocation,
580 call: &ToolCall,
581 cancellation: Token,
582 ) -> impl Future<Output = Result<Self::Output, ExecutorError>> + Send;
583}
584
585/// A fatal failure while converting an open executor output to closed [`ToolResult`].
586#[derive(Clone, Debug, Eq, PartialEq)]
587#[non_exhaustive]
588pub enum MappingError {
589 /// Required/absent/null output presence was inconsistent.
590 InvalidPresence(String),
591 /// Metadata could not be represented by the portable closed value.
592 UnsupportedMetadata(String),
593 /// A model-facing part was not valid tool output.
594 ToolPart(ToolPartError),
595 /// An opaque extension envelope was invalid.
596 OpaqueEnvelope(EnvelopeError),
597 /// The adapter violated its output protocol.
598 Protocol(String),
599}
600
601impl Display for MappingError {
602 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
603 match self {
604 Self::InvalidPresence(context) => {
605 write!(formatter, "invalid output presence: {context}")
606 }
607 Self::UnsupportedMetadata(context) => {
608 write!(formatter, "unsupported metadata: {context}")
609 }
610 Self::ToolPart(error) => write!(formatter, "invalid tool part: {error}"),
611 Self::OpaqueEnvelope(error) => write!(formatter, "invalid opaque envelope: {error}"),
612 Self::Protocol(context) => {
613 write!(formatter, "tool mapping protocol failure: {context}")
614 }
615 }
616 }
617}
618
619impl Error for MappingError {
620 fn source(&self) -> Option<&(dyn Error + 'static)> {
621 match self {
622 Self::ToolPart(error) => Some(error),
623 Self::OpaqueEnvelope(error) => Some(error),
624 Self::InvalidPresence(_) | Self::UnsupportedMetadata(_) | Self::Protocol(_) => None,
625 }
626 }
627}
628
629type ErasedFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
630type DeferredMapping = Box<dyn FnOnce() -> Result<ToolResult, MappingError> + Send>;
631
632enum ErasedExecutionError {
633 Cancelled,
634 Mapping(MappingError),
635}
636
637fn linearize_execution<'a>(
638 mut execution: ErasedFuture<'a, Result<DeferredMapping, ExecutorError>>,
639 cancellation: Token,
640 executor_cancellation: Token,
641) -> ErasedFuture<'a, Result<ToolResult, ErasedExecutionError>> {
642 Box::pin(async move {
643 let mut cancellation_wait = Box::pin(cancellation.cancelled());
644 let outcome = std::future::poll_fn(|context| {
645 if cancellation_wait.as_mut().poll(context).is_ready() {
646 return Poll::Ready(None);
647 }
648 execution.as_mut().poll(context).map(Some)
649 })
650 .await;
651 match outcome {
652 None => {
653 executor_cancellation.cancel();
654 // Executor's cancellation-safety contract makes dropping
655 // the unfinished future the synchronous cleanup boundary. The batch
656 // engine joins only the outer worker that calls this routing primitive.
657 drop(execution);
658 Err(ErasedExecutionError::Cancelled)
659 }
660 Some(Ok(mapper)) => mapper().map_err(ErasedExecutionError::Mapping),
661 // The message and not the chain: this text is model-visible content,
662 // and how a chain of failures should read to a model is the
663 // composition layer's decision, not reef's. `ExecutorError`
664 // documents the message as the complete rendered reason for exactly
665 // this reason; a retained source stays a value for whoever inspects
666 // it in process.
667 Some(Err(error)) => Ok(ToolResult::error_text(error.to_string())),
668 }
669 })
670}
671
672trait ErasedExecutor: Send + Sync {
673 fn execute_mapped<'a>(
674 &'a self,
675 invocation: &'a Invocation,
676 call: &'a ToolCall,
677 cancellation: Token,
678 ) -> ErasedFuture<'a, Result<ToolResult, ErasedExecutionError>>;
679}
680
681struct TypedExecutor<E: Executor> {
682 executor: Arc<E>,
683 mapper: Arc<dyn Fn(E::Output) -> Result<ToolResult, MappingError> + Send + Sync>,
684}
685
686impl<E> ErasedExecutor for TypedExecutor<E>
687where
688 E: Executor,
689{
690 fn execute_mapped<'a>(
691 &'a self,
692 invocation: &'a Invocation,
693 call: &'a ToolCall,
694 cancellation: Token,
695 ) -> ErasedFuture<'a, Result<ToolResult, ErasedExecutionError>> {
696 let executor_cancellation = cancellation.child_token();
697 let execution_token = executor_cancellation.clone();
698 let mapper = Arc::clone(&self.mapper);
699 let execution: ErasedFuture<'a, Result<DeferredMapping, ExecutorError>> =
700 Box::pin(async move {
701 self.executor
702 .execute(invocation, call, execution_token)
703 .await
704 .map(|output| Box::new(move || mapper(output)) as DeferredMapping)
705 });
706 linearize_execution(execution, cancellation, executor_cancellation)
707 }
708}
709
710/// The execution lane exposed to a model.
711#[derive(Clone, Copy, Debug, Eq, PartialEq)]
712#[non_exhaustive]
713pub enum Lane {
714 /// The host dispatches this tool through the captured local executor.
715 Client,
716 /// The model provider executes this capability natively.
717 Hosted,
718}
719
720/// One fully owned registration, suitable for static or dynamic providers.
721///
722/// A registration is one entry in a [`Registry`]: what the model is told about a
723/// tool ([`Descriptor`]), what admitting a call to it requires
724/// ([`Requirements`]), and who runs it. The last part is the choice between the
725/// two constructors, and it is the whole of the [`Lane`] distinction —
726/// [`Registration::client`] pairs an [`Executor`] with its mapper and reef
727/// dispatches the call itself, while [`Registration::hosted`] declares a
728/// capability the *provider* executes and carries the opaque envelope that
729/// configures it.
730///
731/// ```
732/// use reef_core::opaque;
733/// use reef_core::runtime::tool;
734///
735/// let hosted = tool::Registration::hosted(
736/// tool::Descriptor::new(
737/// tool::Name::local("web.search".to_owned()).unwrap(),
738/// "Provider-run web search".to_owned(),
739/// opaque::Payload::copy_from_slice(b"{}"),
740/// ),
741/// // Uninterpreted by reef, and passed to the provider unchanged.
742/// opaque::Envelope::try_new(
743/// "example.provider".to_owned(),
744/// "web_search".to_owned(),
745/// opaque::Payload::copy_from_slice(br#"{"max_results":5}"#),
746/// )
747/// .unwrap(),
748/// );
749/// assert_eq!(hosted.lane(), tool::Lane::Hosted);
750///
751/// let mut registry = tool::RegistryBuilder::new();
752/// registry.register(hosted);
753/// // Names are canonical and collisions fail closed, before any side effect.
754/// assert!(registry.build().is_ok());
755/// ```
756///
757/// [`Executor`] carries the client-lane example.
758#[derive(Clone)]
759pub struct Registration {
760 descriptor: Descriptor,
761 requirements: Option<Requirements>,
762 executor: Option<Arc<dyn ErasedExecutor>>,
763 hosted_extension: Option<Envelope>,
764}
765
766impl Debug for Registration {
767 /// Shows what was registered and whether a local dispatcher backs it.
768 ///
769 /// The executor is a trait object with no `Debug`, and its presence is the
770 /// fact that matters anyway: it is exactly what makes this a client lane
771 /// rather than a hosted one.
772 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
773 formatter
774 .debug_struct("Registration")
775 .field("descriptor", &self.descriptor)
776 .field("requirements", &self.requirements)
777 .field("executor", &redact::Presence(self.executor.is_some()))
778 .field("hosted_extension", &self.hosted_extension)
779 .finish()
780 }
781}
782
783impl Registration {
784 /// Statically pairs a client executor output with its only mapper.
785 #[must_use]
786 pub fn client<E, M>(
787 descriptor: Descriptor,
788 requirements: Requirements,
789 executor: Arc<E>,
790 mapper: Arc<M>,
791 ) -> Self
792 where
793 E: Executor,
794 M: Fn(E::Output) -> Result<ToolResult, MappingError> + Send + Sync + 'static,
795 {
796 Self {
797 descriptor,
798 requirements: Some(requirements),
799 executor: Some(Arc::new(TypedExecutor { executor, mapper })),
800 hosted_extension: None,
801 }
802 }
803
804 /// Creates a model-native registration with an owned provider extension and
805 /// no local dispatcher.
806 #[must_use]
807 pub fn hosted(descriptor: Descriptor, extension: Envelope) -> Self {
808 Self {
809 descriptor,
810 requirements: None,
811 executor: None,
812 hosted_extension: Some(extension),
813 }
814 }
815
816 /// Returns the owned model descriptor.
817 #[must_use]
818 pub const fn descriptor(&self) -> &Descriptor {
819 &self.descriptor
820 }
821
822 /// Returns the immutable execution lane.
823 #[must_use]
824 pub const fn lane(&self) -> Lane {
825 if self.executor.is_some() {
826 Lane::Client
827 } else {
828 Lane::Hosted
829 }
830 }
831}
832
833/// A stable static-registry construction failure.
834#[derive(Clone, Debug, Eq, PartialEq)]
835#[non_exhaustive]
836pub enum RegistryError {
837 /// Two static registrations used the same canonical name.
838 StaticCollision(Name),
839}
840
841impl Display for RegistryError {
842 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
843 match self {
844 Self::StaticCollision(name) => {
845 write!(formatter, "duplicate static tool: {}", name.canonical())
846 }
847 }
848 }
849}
850
851impl Error for RegistryError {}
852
853/// One dynamic-provider resolution diagnostic.
854#[derive(Clone, Debug, Eq, PartialEq)]
855pub struct ProviderDiagnostic(String);
856
857impl ProviderDiagnostic {
858 /// Creates an owned provider diagnostic.
859 #[must_use]
860 pub const fn new(message: String) -> Self {
861 Self(message)
862 }
863
864 /// Returns the provider diagnostic.
865 #[must_use]
866 pub fn message(&self) -> &str {
867 &self.0
868 }
869}
870
871/// One all-or-nothing dynamic provider observation.
872#[derive(Debug)]
873pub struct ProviderResolution {
874 entries: Vec<Registration>,
875 error: Option<ProviderDiagnostic>,
876}
877
878impl ProviderResolution {
879 /// Creates a successful provider observation.
880 #[must_use]
881 pub const fn success(entries: Vec<Registration>) -> Self {
882 Self {
883 entries,
884 error: None,
885 }
886 }
887
888 /// Creates a failed observation; all supplied partial entries are discarded.
889 #[must_use]
890 pub const fn failed(partial_entries: Vec<Registration>, error: ProviderDiagnostic) -> Self {
891 Self {
892 entries: partial_entries,
893 error: Some(error),
894 }
895 }
896}
897
898/// A dynamic tool source resolved exactly once by each Step resolution.
899///
900/// # The resolved tool set may differ every Step, and that is not a loophole
901///
902/// [`Provider::resolve`] runs once per Step, so a provider may legitimately
903/// return a different set at every Step of the same Run: tools that appear once
904/// a file is opened, a scope that narrows after a denial, a catalogue that a
905/// search step widens. This does **not** contradict the rule that configuration
906/// is fixed for a Run. What is frozen is the
907/// [`agent::Revision`](crate::runtime::agent::Revision) — the provider roster,
908/// the hook roster, the system instruction — not the *result* of consulting
909/// that roster. The roster is the configuration; the resolution is a per-Step
910/// observation of it, exactly like the transcript the same Step freezes.
911///
912/// Anyone reaching for a way to make the tool set vary within a Run therefore
913/// already has one, and any proposal to relax the Run-granularity rule on those
914/// grounds is answering a problem that does not exist. What a Run genuinely
915/// cannot do is add or remove a *provider*, change the model client, or change
916/// the hook set; that is a successor Run with a new revision.
917///
918/// # Why this boundary awaits
919///
920/// A tool set that varies per Step is usually one somebody has to go and ask
921/// for: a remote catalogue, a tenant entitlement lookup, a capability handshake.
922/// The other two composition-owned boundaries in this module — [`Gate`] and
923/// [`Executor`] — already await for the same reason, and this one is the
924/// resolution *they* are routed against, so a synchronous signature here would
925/// leave the only boundary that decides *which* tools exist as the only one
926/// unable to ask. Explicit boxed-future erasure follows ADR-013, exactly as
927/// [`Gate::decide`] does, so awaiting costs this registry boundary no
928/// object safety.
929///
930/// A background refresher is not an equivalent: it answers with whatever it
931/// last fetched, which is the one thing a Step-top resolution must not do when
932/// the Step's own request is the thing that has to see the new tool.
933pub trait Provider: Send + Sync + 'static {
934 /// Resolves owned entries from the provider's current state against the
935 /// exact frozen Step-top transcript later handed to every
936 /// [`Invocation`] in the same Step.
937 ///
938 /// Resolution is all-or-nothing: a [`ProviderResolution::failed`]
939 /// observation discards every partial entry and degrades this provider only.
940 /// Resolution runs once per Step, which is what lets the resolved tool set
941 /// differ between Steps without any Run-level binding changing.
942 ///
943 /// # Cancellation
944 ///
945 /// The returned future must be cancellation-safe on the same terms
946 /// [`Executor::execute`] states: the caller may drop it at any await point
947 /// after cancelling the supplied token, and dropping it must release
948 /// resources synchronously rather than detach work. Nothing observable has
949 /// happened at this point in the Step — no request is materialized and no
950 /// executor has run — so a dropped resolution leaves nothing to undo.
951 fn resolve<'a>(
952 &'a self,
953 transcript: &'a Snapshot,
954 cancellation: Token,
955 ) -> Pin<Box<dyn Future<Output = ProviderResolution> + Send + 'a>>;
956}
957
958/// Mutable registration surface consumed into an immutable registry.
959#[derive(Default)]
960pub struct RegistryBuilder {
961 static_entries: Vec<Registration>,
962 providers: Vec<Arc<dyn Provider>>,
963}
964
965impl Debug for RegistryBuilder {
966 /// Shows what has been registered so far and how many providers will run.
967 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
968 debug_registry(
969 "RegistryBuilder",
970 &self.static_entries,
971 &self.providers,
972 formatter,
973 )
974 }
975}
976
977// A registry and the builder it is frozen from hold the same two lanes, and a
978// provider is an `Arc<dyn Provider>` with no `Debug`, so both report the static
979// names they will expose and count the providers they will consult.
980fn debug_registry(
981 name: &str,
982 static_entries: &[Registration],
983 providers: &[Arc<dyn Provider>],
984 formatter: &mut Formatter<'_>,
985) -> fmt::Result {
986 formatter
987 .debug_struct(name)
988 .field(
989 "static_entries",
990 &static_entries
991 .iter()
992 .map(|entry| entry.descriptor.name.canonical())
993 .collect::<Vec<_>>(),
994 )
995 .field("providers", &providers.len())
996 .finish()
997}
998
999impl RegistryBuilder {
1000 /// Creates an empty registry builder.
1001 #[must_use]
1002 pub fn new() -> Self {
1003 Self::default()
1004 }
1005
1006 /// Adds one owned static registration.
1007 pub fn register(&mut self, registration: Registration) -> &mut Self {
1008 self.static_entries.push(registration);
1009 self
1010 }
1011
1012 /// Adds one dynamic provider handle.
1013 pub fn provider(&mut self, provider: Arc<dyn Provider>) -> &mut Self {
1014 self.providers.push(provider);
1015 self
1016 }
1017
1018 /// Validates all static names and freezes the registry.
1019 ///
1020 /// # Errors
1021 ///
1022 /// [`RegistryError::StaticCollision`], naming the tool, if two static
1023 /// registrations share one canonical name. It fails here rather than at
1024 /// resolution so that no model ever sees an ambiguous roster and no executor
1025 /// runs for a call whose routing was already undecidable — a collision is a
1026 /// wiring mistake, and the build is the last moment at which nothing has
1027 /// happened yet.
1028 ///
1029 /// Providers cannot be checked here, because they resolve per Step. A name
1030 /// that only collides once a provider has produced it is reported by
1031 /// [`Registry::resolve_step`] as [`StepResolutionError::Collision`] — the
1032 /// same fail-closed rule, applied at the only moment the full set exists, and
1033 /// still before any model request, gate, or executor sees it.
1034 pub fn build(self) -> Result<Registry, RegistryError> {
1035 let mut names = HashSet::new();
1036 for entry in &self.static_entries {
1037 if !names.insert(entry.descriptor.name.clone()) {
1038 return Err(RegistryError::StaticCollision(
1039 entry.descriptor.name.clone(),
1040 ));
1041 }
1042 }
1043 Ok(Registry {
1044 static_entries: self.static_entries,
1045 providers: self.providers,
1046 })
1047 }
1048}
1049
1050/// An immutable, shareable static registry and provider set.
1051#[derive(Clone)]
1052pub struct Registry {
1053 static_entries: Vec<Registration>,
1054 providers: Vec<Arc<dyn Provider>>,
1055}
1056
1057impl Debug for Registry {
1058 /// Shows the frozen static names and how many providers back them.
1059 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1060 debug_registry("Registry", &self.static_entries, &self.providers, formatter)
1061 }
1062}
1063
1064/// Filters model exposure before a Step snapshot materializes.
1065///
1066/// This is crate-private and ADR-027 records why. The correction point is real
1067/// and the runtime applies it, but the only production filter is [`ExposeAll`]:
1068/// a composition layer that wants a narrower Step roster narrows what its own
1069/// [`Provider`] returns, or filters `Request::tools` in an
1070/// [`ModelHooks::before_model`](crate::runtime::hook::ModelHooks::before_model)
1071/// registration paired with a
1072/// [`Block`](crate::runtime::hook::ToolCallDecision::Block) in
1073/// [`ToolHooks::before_tool_call`](crate::runtime::hook::ToolHooks::before_tool_call).
1074///
1075/// The `Sync` bound is what holding this filter across a provider's await costs
1076/// (ADR-024 D3), and it is the whole of it: the filter is only ever borrowed, so
1077/// nothing here has to be `Send`.
1078pub(crate) trait ExposureFilter: Sync {
1079 /// Returns whether one validated registration remains exposed and routable.
1080 fn exposed(&self, descriptor: &Descriptor, lane: Lane) -> bool;
1081}
1082
1083/// A filter that exposes every validated registration.
1084#[derive(Debug)]
1085pub(crate) struct ExposeAll;
1086
1087impl ExposureFilter for ExposeAll {
1088 fn exposed(&self, _descriptor: &Descriptor, _lane: Lane) -> bool {
1089 true
1090 }
1091}
1092
1093/// A dynamic collision discovered before model, gate, or executor activity.
1094#[derive(Clone, Debug, Eq, PartialEq)]
1095#[non_exhaustive]
1096pub enum StepResolutionError {
1097 /// A dynamic name collided within/across providers or with a static name.
1098 Collision(Name),
1099}
1100
1101impl Display for StepResolutionError {
1102 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1103 match self {
1104 Self::Collision(name) => write!(formatter, "Step tool collision: {}", name.canonical()),
1105 }
1106 }
1107}
1108
1109impl Error for StepResolutionError {}
1110
1111/// The result of one resolve-once Step boundary.
1112#[derive(Debug)]
1113pub struct StepResolution {
1114 snapshot: StepToolSnapshot,
1115 provider_diagnostics: Vec<ProviderDiagnostic>,
1116}
1117
1118impl StepResolution {
1119 /// Returns the immutable Step snapshot.
1120 #[must_use]
1121 pub const fn snapshot(&self) -> &StepToolSnapshot {
1122 &self.snapshot
1123 }
1124
1125 /// Transfers the immutable Step snapshot.
1126 #[must_use]
1127 pub fn into_snapshot(self) -> StepToolSnapshot {
1128 self.snapshot
1129 }
1130
1131 /// Splits this resolution into its owned snapshot and the ordered
1132 /// per-degraded-provider diagnostics.
1133 ///
1134 /// This is the crate-private twin of
1135 /// [`into_snapshot`](Self::into_snapshot) plus
1136 /// [`provider_diagnostics`](Self::provider_diagnostics), and it exists so
1137 /// the loop can publish one nonfatal Error per degraded provider without the
1138 /// public surface growing a second accessor for a value the pair above
1139 /// already exposes. The diagnostics stay in provider registration order.
1140 #[must_use]
1141 pub(crate) fn into_parts(self) -> (StepToolSnapshot, Vec<ProviderDiagnostic>) {
1142 (self.snapshot, self.provider_diagnostics)
1143 }
1144
1145 /// Returns one nonfatal diagnostic for each degraded provider.
1146 #[must_use]
1147 pub fn provider_diagnostics(&self) -> &[ProviderDiagnostic] {
1148 &self.provider_diagnostics
1149 }
1150}
1151
1152impl Registry {
1153 /// Resolves every provider once against one frozen transcript snapshot,
1154 /// validates the full set, and then freezes one owned Step snapshot that
1155 /// reuses that exact transcript version.
1156 ///
1157 /// Providers are resolved in registration order, one await at a time. The
1158 /// order is the registration order for the same reason the hook fan-outs
1159 /// use it — it is the only order a composition layer declared — and the
1160 /// sequencing is deliberate rather than incidental: a concurrent fan-out
1161 /// would make the diagnostic order of degraded providers depend on which
1162 /// remote answered first, and this value is compared in tests and logs.
1163 ///
1164 /// Every validated registration is exposed. Narrowing the roster is a
1165 /// composition-layer decision taken one rail earlier, in what a [`Provider`]
1166 /// returns, or one rail later, in what an
1167 /// [`OnBeforeModel`](crate::runtime::hook::ModelHooks::before_model)
1168 /// registration leaves in `Request::tools`; ADR-027 records why core
1169 /// publishes neither a filter nor a mount point for one.
1170 ///
1171 /// # Errors
1172 ///
1173 /// Returns [`StepResolutionError::Collision`] before any model request, gate
1174 /// consultation, or executor dispatch can observe the ambiguity.
1175 pub async fn resolve_step(
1176 &self,
1177 transcript: Snapshot,
1178 cancellation: &Token,
1179 ) -> Result<StepResolution, StepResolutionError> {
1180 self.resolve_step_filtered(transcript, cancellation, &ExposeAll)
1181 .await
1182 }
1183
1184 /// Resolves as [`resolve_step`](Self::resolve_step) does, then drops every
1185 /// registration the correction hides from both the model and the router.
1186 ///
1187 /// The correction is applied after validation, so a name that collides is
1188 /// still an error even when the filter would have hidden it: hiding an
1189 /// ambiguity is not the same as not having one.
1190 pub(crate) async fn resolve_step_filtered(
1191 &self,
1192 transcript: Snapshot,
1193 cancellation: &Token,
1194 correction: &dyn ExposureFilter,
1195 ) -> Result<StepResolution, StepResolutionError> {
1196 let transcript = Arc::new(transcript);
1197 let mut entries = self.static_entries.clone();
1198 let mut provider_diagnostics = Vec::new();
1199 for provider in &self.providers {
1200 let resolution = provider.resolve(&transcript, cancellation.clone()).await;
1201 if let Some(error) = resolution.error {
1202 provider_diagnostics.push(error);
1203 } else {
1204 entries.extend(resolution.entries);
1205 }
1206 }
1207
1208 let mut names = HashSet::new();
1209 for entry in &entries {
1210 if !names.insert(entry.descriptor.name.clone()) {
1211 return Err(StepResolutionError::Collision(
1212 entry.descriptor.name.clone(),
1213 ));
1214 }
1215 }
1216 entries.retain(|entry| correction.exposed(&entry.descriptor, entry.lane()));
1217 Ok(StepResolution {
1218 snapshot: StepToolSnapshot {
1219 entries,
1220 transcript,
1221 },
1222 provider_diagnostics,
1223 })
1224 }
1225
1226 /// Resolves a registry that registered no dynamic provider, without a runtime.
1227 ///
1228 /// [`resolve_step`](Self::resolve_step) awaits its providers, and most
1229 /// fixtures across the runtime tests have none: they build a snapshot out of
1230 /// static registrations so that some other boundary has one to route
1231 /// against. Those tests are synchronous, and making each of them claim a
1232 /// reactor to drive a future that cannot park would say something false
1233 /// about what they exercise. The `Pending` arm is the assertion that the
1234 /// caller really is such a fixture.
1235 #[cfg(test)]
1236 pub(crate) fn resolve_step_without_providers(
1237 &self,
1238 transcript: Snapshot,
1239 cancellation: &Token,
1240 correction: &dyn ExposureFilter,
1241 ) -> Result<StepResolution, StepResolutionError> {
1242 let mut resolving =
1243 Box::pin(self.resolve_step_filtered(transcript, cancellation, correction));
1244 match resolving
1245 .as_mut()
1246 .poll(&mut Context::from_waker(Waker::noop()))
1247 {
1248 Poll::Ready(resolved) => resolved,
1249 Poll::Pending => {
1250 panic!("a registry with no dynamic provider resolves on its first poll")
1251 }
1252 }
1253 }
1254}
1255
1256/// The gate's only valid business decisions.
1257#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1258pub enum GateVerdict {
1259 /// Invalid/unknown verdict; the call fails fatally.
1260 Invalid,
1261 /// Admit the effective call.
1262 Allow,
1263 /// Deny as a business result.
1264 Deny,
1265}
1266
1267/// A gate operation failure distinct from an ordinary Deny.
1268#[derive(Clone, Debug, Eq, PartialEq)]
1269#[non_exhaustive]
1270pub enum GateOperationError {
1271 /// The gate operation observed cancellation.
1272 Cancelled,
1273 /// The composition-owned resolver failed after publication.
1274 ResolverFailed(String),
1275 /// Publishing the composition-owned approval request failed.
1276 PublicationFailed(String),
1277}
1278
1279impl Display for GateOperationError {
1280 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1281 match self {
1282 Self::Cancelled => formatter.write_str("tool gate cancelled"),
1283 Self::ResolverFailed(context) => {
1284 write!(formatter, "tool gate resolver failed: {context}")
1285 }
1286 Self::PublicationFailed(context) => {
1287 write!(formatter, "tool gate publication failed: {context}")
1288 }
1289 }
1290 }
1291}
1292
1293impl Error for GateOperationError {}
1294
1295/// Policy-neutral admission boundary over the final effective call.
1296///
1297/// Explicit boxed-future erasure follows ADR-013 so composition adapters may
1298/// await approval without making this registry boundary non-object-safe.
1299pub trait Gate: Send + Sync {
1300 /// Returns exactly one admission verdict or typed operation error.
1301 fn decide<'a>(
1302 &'a self,
1303 call: &'a ToolCall,
1304 requirements: &'a Requirements,
1305 cancellation: Token,
1306 ) -> Pin<Box<dyn Future<Output = Result<GateVerdict, GateOperationError>> + Send + 'a>>;
1307}
1308
1309/// A fatal or cancellation outcome from routing one local call.
1310///
1311/// Unknown tool names are deliberately absent: an unexposed name is an ordinary
1312/// business rejection, not a control-path failure, so the model can be told
1313/// about it in the transcript instead of the Run failing.
1314#[derive(Clone, Debug, Eq, PartialEq)]
1315#[non_exhaustive]
1316pub enum ExecutionError {
1317 /// A hosted/model-native capability was sent to the local path.
1318 Hosted(String),
1319 /// Admission facts were invalid.
1320 InvalidApproval,
1321 /// The gate returned an invalid verdict.
1322 InvalidGateVerdict,
1323 /// Cancellation won the control path.
1324 Cancelled,
1325 /// A gate operation failed rather than denied.
1326 ///
1327 /// Core never constructs [`Gate`](Self::Gate) with
1328 /// [`GateOperationError::Cancelled`]; that path is always [`Self::Cancelled`].
1329 /// A consumer-built `Gate(Cancelled)` is not equal to [`Self::Cancelled`] and
1330 /// ranks as a fatal latch failure, not a cancellation.
1331 Gate(GateOperationError),
1332 /// Output mapping failed fatally.
1333 Mapping(MappingError),
1334}
1335
1336impl Display for ExecutionError {
1337 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1338 match self {
1339 Self::Hosted(name) => {
1340 write!(formatter, "hosted tool is not locally dispatchable: {name}")
1341 }
1342 Self::InvalidApproval => formatter.write_str("invalid tool approval classification"),
1343 Self::InvalidGateVerdict => formatter.write_str("invalid tool gate verdict"),
1344 Self::Cancelled => formatter.write_str("tool run cancelled"),
1345 Self::Gate(error) => Display::fmt(error, formatter),
1346 Self::Mapping(error) => write!(formatter, "tool output mapping failed: {error}"),
1347 }
1348 }
1349}
1350
1351impl Error for ExecutionError {
1352 fn source(&self) -> Option<&(dyn Error + 'static)> {
1353 match self {
1354 Self::Mapping(error) => Some(error),
1355 Self::Gate(error) => Some(error),
1356 Self::Hosted(_)
1357 | Self::InvalidApproval
1358 | Self::InvalidGateVerdict
1359 | Self::Cancelled => None,
1360 }
1361 }
1362}
1363
1364/// The furthest stable disposition reached by a started `ToolCall`.
1365///
1366/// Only
1367/// [`Self::Executed`], [`Self::Denied`], and [`Self::Rejected`] can be produced
1368/// by [`StepToolSnapshot::execute`]; the remaining states are reached by the
1369/// hook and terminal-unwind paths that observe the same closed vocabulary.
1370#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1371#[non_exhaustive]
1372pub enum CallDisposition {
1373 /// Entered tool execution.
1374 Executed,
1375 /// A hook supplied a result without execution.
1376 ShortCircuited,
1377 /// A hook blocked execution.
1378 Blocked,
1379 /// The configured gate denied execution.
1380 Denied,
1381 /// Core rejected an unavailable/forbidden/ungated call.
1382 Rejected,
1383 /// Output-token truncation left the call incomplete.
1384 Truncated,
1385 /// Terminal unwinding began before another stable disposition.
1386 NotExecuted,
1387}
1388
1389/// One closed business outcome of routing an accepted effective call.
1390///
1391/// A successful route always carries both the model-visible closed result and
1392/// the disposition fact later published by lifecycle observations, so callers
1393/// never re-derive the disposition from the result's shape.
1394#[derive(Clone, Debug)]
1395pub struct ExecutionOutcome {
1396 result: ToolResult,
1397 disposition: CallDisposition,
1398}
1399
1400impl ExecutionOutcome {
1401 /// Returns the model-visible closed result.
1402 #[must_use]
1403 pub const fn result(&self) -> &ToolResult {
1404 &self.result
1405 }
1406
1407 /// Returns the stable disposition reached by this call.
1408 #[must_use]
1409 pub const fn disposition(&self) -> CallDisposition {
1410 self.disposition
1411 }
1412
1413 /// Transfers the closed result and its disposition.
1414 #[must_use]
1415 pub fn into_parts(self) -> (ToolResult, CallDisposition) {
1416 (self.result, self.disposition)
1417 }
1418}
1419
1420/// One immutable model-exposure and host-routing snapshot.
1421#[derive(Debug)]
1422pub struct StepToolSnapshot {
1423 entries: Vec<Registration>,
1424 transcript: Arc<Snapshot>,
1425}
1426
1427impl StepToolSnapshot {
1428 /// Creates the crate-private shallow twin used by `StepSnapshot`.
1429 ///
1430 /// Registrations retain the same executor/mapper handles and the transcript
1431 /// retains the same owned `Arc<Snapshot>`; no provider is resolved again.
1432 #[must_use]
1433 pub(crate) fn shallow_clone(&self) -> Self {
1434 Self {
1435 entries: self.entries.clone(),
1436 transcript: Arc::clone(&self.transcript),
1437 }
1438 }
1439
1440 /// Returns the frozen Step-top transcript shared by this Step's provider
1441 /// resolution and every invocation minted from this snapshot.
1442 #[must_use]
1443 pub fn transcript(&self) -> &Snapshot {
1444 &self.transcript
1445 }
1446
1447 /// Returns every frozen exposed descriptor and lane in deterministic order.
1448 #[must_use]
1449 pub fn exposure(&self) -> impl ExactSizeIterator<Item = (&Descriptor, Lane)> {
1450 self.entries
1451 .iter()
1452 .map(|entry| (&entry.descriptor, entry.lane()))
1453 }
1454
1455 /// Materializes the client/local lane for [`crate::runtime::model::RequestPlan`].
1456 #[must_use]
1457 pub fn client_model_tools(&self) -> Vec<ClientTool> {
1458 self.entries
1459 .iter()
1460 .filter(|entry| entry.lane() == Lane::Client)
1461 .map(|entry| entry.descriptor.client_model_tool())
1462 .collect()
1463 }
1464
1465 /// Materializes the hosted/model-native lane for
1466 /// [`crate::runtime::model::RequestPlan`].
1467 #[must_use]
1468 pub fn hosted_model_extensions(&self) -> Vec<Envelope> {
1469 self.entries
1470 .iter()
1471 .filter_map(|entry| entry.hosted_extension.clone())
1472 .collect()
1473 }
1474
1475 /// Applies both model-visible lanes from this exact Step snapshot.
1476 pub fn apply_to_plan(&self, plan: &mut RequestPlan) {
1477 plan.extend_tools(self.client_model_tools())
1478 .extend_extensions(self.hosted_model_extensions());
1479 }
1480
1481 /// Mints one invocation whose transcript is this snapshot's exact owned
1482 /// frozen view, so no caller can substitute another transcript version.
1483 ///
1484 /// Minting requires both a core-resolved snapshot and a
1485 /// [`ToolEmitter`], whose outward authority and [`crate::value::lifecycle::Coord`]
1486 /// are stamped by core. Neither the outward producer nor any run state is
1487 /// reachable through this seam. Outside a live run, pass
1488 /// [`ToolEmitter::closed`].
1489 #[must_use]
1490 pub fn invocation(
1491 &self,
1492 session_id: Option<String>,
1493 call_id: Id,
1494 emitter: ToolEmitter,
1495 ) -> Invocation {
1496 Invocation::new(session_id, Arc::clone(&self.transcript), call_id, emitter)
1497 }
1498
1499 /// Routes one accepted effective call through ADR-010's admission branches.
1500 ///
1501 /// # Errors
1502 ///
1503 /// Returns [`ExecutionError`] only for control-path failures: hosted
1504 /// misrouting, invalid admission facts or verdicts, cancellation, gate
1505 /// operation failures, and fatal output mapping. Unknown, forbidden,
1506 /// ungated, denied, and ordinarily failing calls are business outcomes.
1507 pub async fn execute(
1508 &self,
1509 invocation: &Invocation,
1510 call: &ToolCall,
1511 gate: Option<&dyn Gate>,
1512 cancellation: &Token,
1513 ) -> Result<ExecutionOutcome, ExecutionError> {
1514 if cancellation.is_cancelled() {
1515 return Err(ExecutionError::Cancelled);
1516 }
1517 // A registration is keyed by a validated `Name`, so the binding is
1518 // recovered by parsing the emission back into one — the inverse of the
1519 // `to_wire` spelling that advertised it — rather than by comparing
1520 // strings. An emission the grammar rejects cannot name any registration,
1521 // and it stays a business result: the model has to be told which name it
1522 // asked for, which is why the raw emission is reported unchanged.
1523 let emitted = call.name().as_str();
1524 let Some(entry) = Name::parse_canonical(emitted).ok().and_then(|name| {
1525 self.entries
1526 .iter()
1527 .find(|candidate| candidate.descriptor.name == name)
1528 }) else {
1529 return Ok(rejected(format!("unknown tool: {emitted}")));
1530 };
1531 let (requirements, executor) = match (&entry.requirements, &entry.executor) {
1532 (Some(requirements), Some(executor)) => (requirements, executor),
1533 _ => return Err(ExecutionError::Hosted(emitted.to_owned())),
1534 };
1535
1536 match requirements.approval {
1537 Approval::Invalid => return Err(ExecutionError::InvalidApproval),
1538 Approval::Forbidden => return Ok(rejected("forbidden tool".to_owned())),
1539 Approval::NotRequired => {}
1540 Approval::Required => {
1541 let Some(gate) = gate else {
1542 return Ok(rejected(
1543 "approval required but no tool gate is configured".to_owned(),
1544 ));
1545 };
1546 match gate.decide(call, requirements, cancellation.clone()).await {
1547 Ok(GateVerdict::Allow) => {}
1548 Ok(GateVerdict::Deny) => {
1549 return Ok(ExecutionOutcome {
1550 result: ToolResult::error_text("denied by approver".to_owned()),
1551 disposition: CallDisposition::Denied,
1552 });
1553 }
1554 Ok(GateVerdict::Invalid) => return Err(ExecutionError::InvalidGateVerdict),
1555 Err(GateOperationError::Cancelled) => return Err(ExecutionError::Cancelled),
1556 Err(error) => return Err(ExecutionError::Gate(error)),
1557 }
1558 }
1559 }
1560 if cancellation.is_cancelled() {
1561 return Err(ExecutionError::Cancelled);
1562 }
1563 match executor
1564 .execute_mapped(invocation, call, cancellation.clone())
1565 .await
1566 {
1567 Ok(result) => Ok(ExecutionOutcome {
1568 result,
1569 disposition: CallDisposition::Executed,
1570 }),
1571 Err(ErasedExecutionError::Cancelled) => Err(ExecutionError::Cancelled),
1572 Err(ErasedExecutionError::Mapping(error)) => Err(ExecutionError::Mapping(error)),
1573 }
1574 }
1575}
1576
1577fn rejected(message: String) -> ExecutionOutcome {
1578 // Matches the closed `ToolResult::error_text` business-result producer.
1579 ExecutionOutcome {
1580 result: ToolResult::error_text(message),
1581 disposition: CallDisposition::Rejected,
1582 }
1583}