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/// An ordinary executor failure that becomes a business result.
264///
265/// The message is what the model is told: reef records
266/// [`Display`] as the tool's output and the transcript keeps text,
267/// not types. So the message has to be complete on its own, and
268/// [`with_source`](Self::with_source) does not extend it — attaching a source
269/// keeps the concrete failure as a *value*, for whoever inspects this error in
270/// process, and changes nothing about what the model reads.
271///
272/// That inspection is why the source exists. An executor almost always fails
273/// *because* something underneath it did — an I/O error, a transport failure, a
274/// timeout — and a composition layer that wraps executors, retries them, or
275/// classifies their failures needs the reason by its type rather than by
276/// matching on a sentence:
277///
278/// ```
279/// use std::io;
280/// use reef_core::runtime::tool;
281///
282/// let failure = tool::ExecutorError::new("reading the manifest failed".to_owned())
283/// .with_source(io::Error::from(io::ErrorKind::NotFound));
284///
285/// // The message alone is what the model sees.
286/// assert_eq!(failure.to_string(), "reading the manifest failed");
287///
288/// // The reason is still recoverable by its own type.
289/// let cause = std::error::Error::source(&failure).expect("a source was attached");
290/// let cause = cause.downcast_ref::<io::Error>().expect("the concrete cause");
291/// assert_eq!(cause.kind(), io::ErrorKind::NotFound);
292/// ```
293#[derive(Clone)]
294pub struct ExecutorError {
295 message: String,
296 source: Option<Arc<dyn Error + Send + Sync>>,
297}
298
299impl ExecutorError {
300 /// Creates an owned executor diagnostic.
301 #[must_use]
302 pub const fn new(message: String) -> Self {
303 Self {
304 message,
305 source: None,
306 }
307 }
308
309 /// Retains the concrete failure this diagnostic is about.
310 ///
311 /// Returned from [`Error::source`], so the cause downcasts back to the
312 /// caller's own type. It does not affect the message, equality, or what the
313 /// model is told; see the type's own documentation for why.
314 #[must_use]
315 pub fn with_source(mut self, source: impl Error + Send + Sync + 'static) -> Self {
316 self.source = Some(Arc::new(source));
317 self
318 }
319}
320
321impl fmt::Debug for ExecutorError {
322 /// Renders the message and then every link of the chain, each through `Display`.
323 ///
324 /// Printing only the message would discard the reason
325 /// [`with_source`](Self::with_source) retains, which is the part a reader is
326 /// usually after. `Display` rather than the link's own `Debug`, because a
327 /// cause is whatever an executor handed back: text this crate neither writes
328 /// nor reviews, whose `Display` is the diagnostic the type is contracted to
329 /// produce. This is the same rendering [`HookError`] uses.
330 ///
331 /// [`HookError`]: crate::runtime::hook::HookError
332 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
333 let mut tuple = formatter.debug_tuple("ExecutorError");
334 tuple.field(&self.message);
335 let mut link = Error::source(self);
336 while let Some(error) = link {
337 tuple.field(&error.to_string());
338 link = error.source();
339 }
340 tuple.finish()
341 }
342}
343
344impl Display for ExecutorError {
345 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
346 formatter.write_str(&self.message)
347 }
348}
349
350/// Compares the diagnostic message and nothing else.
351///
352/// A retained source is an arbitrary third-party error with no equality of its
353/// own, so there is no answer to whether two of them are "the same"; comparing
354/// them by pointer would make two errors that say the same thing unequal, which
355/// is worse than not comparing them. The message is what this type is compared
356/// for — asserting on a diagnostic — so that is what equality means here.
357impl PartialEq for ExecutorError {
358 fn eq(&self, other: &Self) -> bool {
359 self.message == other.message
360 }
361}
362
363impl Eq for ExecutorError {}
364
365impl Error for ExecutorError {
366 fn source(&self) -> Option<&(dyn Error + 'static)> {
367 self.source
368 .as_ref()
369 .map(|source| source.as_ref() as &(dyn Error + 'static))
370 }
371}
372
373/// The closed per-call context supplied to one [`Executor::execute`].
374///
375/// This is trusted runtime-provided context, never a dependency-injection bag:
376/// optional capabilities such as process execution are constructor-injected into
377/// the concrete executor and never flow through here.
378///
379/// The struct has no public constructor and no public fields, so only a core
380/// adapter can mint one. Its emit capability is limited to
381/// [`crate::runtime::event::ToolEmitter`], which itself can only produce audit
382/// and error facts, so producer authority and outward event state never leak to
383/// an executor.
384#[derive(Debug)]
385pub struct Invocation {
386 session_id: Option<String>,
387 transcript: Snapshot,
388 call_id: Id,
389 emitter: ToolEmitter,
390}
391
392impl Invocation {
393 /// Returns the trusted host-provided session identity, when one exists.
394 ///
395 /// Core does not require this to be nonempty or globally unique; treat it as
396 /// correlation metadata rather than an authorization credential. Model tool
397 /// arguments can never override it.
398 #[must_use]
399 pub fn session_id(&self) -> Option<&str> {
400 self.session_id.as_deref()
401 }
402
403 /// Returns the frozen Step-top transcript shared by every provider
404 /// resolution and every invocation in the same Step.
405 #[must_use]
406 pub const fn transcript(&self) -> &Snapshot {
407 &self.transcript
408 }
409
410 /// Returns the model-assigned identity of this invocation within its Step.
411 #[must_use]
412 pub const fn call_id(&self) -> &Id {
413 &self.call_id
414 }
415
416 /// Returns the invocation-scoped audit/error emit capability.
417 #[must_use]
418 pub const fn emitter(&self) -> &ToolEmitter {
419 &self.emitter
420 }
421
422 pub(crate) const fn new(
423 session_id: Option<String>,
424 transcript: Snapshot,
425 call_id: Id,
426 emitter: ToolEmitter,
427 ) -> Self {
428 Self {
429 session_id,
430 transcript,
431 call_id,
432 emitter,
433 }
434 }
435}
436
437/// A concrete executor with one registration-specific output type.
438///
439/// An executor returns whatever type is natural for it — a `String`, a struct, a
440/// byte buffer — and [`Registration::client`] pairs that type with the one
441/// mapper that turns it into a closed [`ToolResult`]. Nothing else in the crate
442/// sees [`Executor::Output`], which is why it can be anything.
443///
444/// **An ordinary failure is not `Err`.** `Err(ExecutorError)` says the adapter
445/// itself broke; a tool that ran and did not like what it found returns
446/// `Ok(...)` and lets the mapper produce
447/// [`crate::value::tool_call::ToolResult::BusinessError`],
448/// which the model reads and can act on.
449///
450/// ```
451/// use std::future::{Future, ready};
452/// use std::sync::Arc;
453///
454/// use reef_core::cancel;
455/// use reef_core::opaque;
456/// use reef_core::runtime::tool;
457/// use reef_core::value::tool_call;
458///
459/// #[derive(Debug)]
460/// struct Reverse;
461///
462/// impl tool::Executor for Reverse {
463/// type Output = String;
464///
465/// fn execute(
466/// &self,
467/// _invocation: &tool::Invocation,
468/// call: &tool_call::ToolCall,
469/// _cancellation: cancel::Token,
470/// ) -> impl Future<Output = Result<Self::Output, tool::ExecutorError>> + Send {
471/// // Arguments are uninterpreted bytes: reef never parsed them, and the
472/// // schema this tool published is what promised their shape.
473/// let arguments = String::from_utf8_lossy(call.arguments().as_bytes()).into_owned();
474/// ready(Ok(arguments.chars().rev().collect()))
475/// }
476/// }
477///
478/// let registration = tool::Registration::client(
479/// tool::Descriptor::new(
480/// tool::Name::local("text.reverse".to_owned()).unwrap(),
481/// "Reverses its arguments".to_owned(),
482/// opaque::Payload::copy_from_slice(br#"{"type":"object"}"#),
483/// ),
484/// Arc::new(Reverse),
485/// // The mapper is the only thing that sees `Output`.
486/// Arc::new(|output: String| Ok(tool_call::ToolResult::success_text(output))),
487/// );
488/// assert_eq!(registration.lane(), tool::Lane::Client);
489/// ```
490///
491/// # Cancellation
492///
493/// The future returned by [`execute`](Executor::execute) must be
494/// cancellation-safe; that method's own documentation states exactly what reef
495/// requires of it.
496pub trait Executor: Send + Sync + 'static {
497 /// Open adapter output consumed only by the paired registration mapper.
498 type Output: Send + 'static;
499
500 /// Executes one effective call under its closed invocation context; ordinary
501 /// errors become business results only when execution completion wins its
502 /// race with cancellation.
503 ///
504 /// The returned future must be cancellation-safe: its caller may drop it at
505 /// any await point after first cancelling the supplied token. Dropping the
506 /// future must synchronously release resources or initiate owned cleanup,
507 /// and it must not detach any work. If background work is unavoidable, the
508 /// future itself must own that work and its `Drop` path must abort it or
509 /// otherwise synchronously bring it under cleanup that remains owned.
510 fn execute(
511 &self,
512 invocation: &Invocation,
513 call: &ToolCall,
514 cancellation: Token,
515 ) -> impl Future<Output = Result<Self::Output, ExecutorError>> + Send;
516}
517
518/// A fatal failure while converting an open executor output to closed [`ToolResult`].
519///
520/// This consumer-constructed enum is exhaustive: adding another mapping category
521/// is a breaking API change. Every current variant follows the same fatal
522/// [`ExecutionError::Mapping`] route.
523#[derive(Clone, Debug, Eq, PartialEq)]
524pub enum MappingError {
525 /// Required/absent/null output presence was inconsistent.
526 InvalidPresence(String),
527 /// Metadata could not be represented by the portable closed value.
528 UnsupportedMetadata(String),
529 /// A model-facing part was not valid tool output.
530 ToolPart(ToolPartError),
531 /// An opaque extension envelope was invalid.
532 OpaqueEnvelope(EnvelopeError),
533 /// The adapter violated its output protocol.
534 Protocol(String),
535}
536
537impl Display for MappingError {
538 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
539 match self {
540 Self::InvalidPresence(context) => {
541 write!(formatter, "invalid output presence: {context}")
542 }
543 Self::UnsupportedMetadata(context) => {
544 write!(formatter, "unsupported metadata: {context}")
545 }
546 Self::ToolPart(error) => write!(formatter, "invalid tool part: {error}"),
547 Self::OpaqueEnvelope(error) => write!(formatter, "invalid opaque envelope: {error}"),
548 Self::Protocol(context) => {
549 write!(formatter, "tool mapping protocol failure: {context}")
550 }
551 }
552 }
553}
554
555impl Error for MappingError {
556 fn source(&self) -> Option<&(dyn Error + 'static)> {
557 match self {
558 Self::ToolPart(error) => Some(error),
559 Self::OpaqueEnvelope(error) => Some(error),
560 Self::InvalidPresence(_) | Self::UnsupportedMetadata(_) | Self::Protocol(_) => None,
561 }
562 }
563}
564
565type ErasedFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
566type DeferredMapping = Box<dyn FnOnce() -> Result<ToolResult, MappingError> + Send>;
567
568enum ErasedExecutionError {
569 Cancelled,
570 Mapping(MappingError),
571}
572
573fn linearize_execution<'a>(
574 mut execution: ErasedFuture<'a, Result<DeferredMapping, ExecutorError>>,
575 cancellation: Token,
576 executor_cancellation: Token,
577) -> ErasedFuture<'a, Result<ToolResult, ErasedExecutionError>> {
578 Box::pin(async move {
579 let mut cancellation_wait = Box::pin(cancellation.cancelled());
580 let outcome = std::future::poll_fn(|context| {
581 if cancellation_wait.as_mut().poll(context).is_ready() {
582 return Poll::Ready(None);
583 }
584 execution.as_mut().poll(context).map(Some)
585 })
586 .await;
587 match outcome {
588 None => {
589 executor_cancellation.cancel();
590 // Executor's cancellation-safety contract makes dropping
591 // the unfinished future the synchronous cleanup boundary. The batch
592 // engine joins only the outer worker that calls this routing primitive.
593 drop(execution);
594 Err(ErasedExecutionError::Cancelled)
595 }
596 Some(Ok(mapper)) => mapper().map_err(ErasedExecutionError::Mapping),
597 // The message and not the chain: this text is model-visible content,
598 // and how a chain of failures should read to a model is the
599 // composition layer's decision, not reef's. `ExecutorError`
600 // documents the message as the complete rendered reason for exactly
601 // this reason; a retained source stays a value for whoever inspects
602 // it in process.
603 Some(Err(error)) => Ok(ToolResult::error_text(error.to_string())),
604 }
605 })
606}
607
608trait ErasedExecutor: Send + Sync {
609 fn execute_mapped<'a>(
610 &'a self,
611 invocation: &'a Invocation,
612 call: &'a ToolCall,
613 cancellation: Token,
614 ) -> ErasedFuture<'a, Result<ToolResult, ErasedExecutionError>>;
615}
616
617struct TypedExecutor<E: Executor> {
618 executor: Arc<E>,
619 mapper: Arc<dyn Fn(E::Output) -> Result<ToolResult, MappingError> + Send + Sync>,
620}
621
622impl<E> ErasedExecutor for TypedExecutor<E>
623where
624 E: Executor,
625{
626 fn execute_mapped<'a>(
627 &'a self,
628 invocation: &'a Invocation,
629 call: &'a ToolCall,
630 cancellation: Token,
631 ) -> ErasedFuture<'a, Result<ToolResult, ErasedExecutionError>> {
632 let executor_cancellation = cancellation.child_token();
633 let execution_token = executor_cancellation.clone();
634 let mapper = Arc::clone(&self.mapper);
635 let execution: ErasedFuture<'a, Result<DeferredMapping, ExecutorError>> =
636 Box::pin(async move {
637 self.executor
638 .execute(invocation, call, execution_token)
639 .await
640 .map(|output| Box::new(move || mapper(output)) as DeferredMapping)
641 });
642 linearize_execution(execution, cancellation, executor_cancellation)
643 }
644}
645
646/// The execution lane exposed to a model.
647#[derive(Clone, Copy, Debug, Eq, PartialEq)]
648#[non_exhaustive]
649pub enum Lane {
650 /// The host dispatches this tool through the captured local executor.
651 Client,
652 /// The model provider executes this capability natively.
653 Hosted,
654}
655
656/// One fully owned registration, suitable for static or dynamic providers.
657///
658/// A registration is one entry in a [`Registry`]: what the model is told about a
659/// tool ([`Descriptor`]) and who runs it. The latter is the choice between the
660/// two constructors, and it is the whole of the [`Lane`] distinction —
661/// [`Registration::client`] pairs an [`Executor`] with its mapper and reef
662/// dispatches the call itself, while [`Registration::hosted`] declares a
663/// capability the *provider* executes and carries the opaque envelope that
664/// configures it.
665///
666/// ```
667/// use reef_core::opaque;
668/// use reef_core::runtime::tool;
669///
670/// let hosted = tool::Registration::hosted(
671/// tool::Descriptor::new(
672/// tool::Name::local("web.search".to_owned()).unwrap(),
673/// "Provider-run web search".to_owned(),
674/// opaque::Payload::copy_from_slice(b"{}"),
675/// ),
676/// // Uninterpreted by reef, and passed to the provider unchanged.
677/// opaque::Envelope::try_new(
678/// "example.provider".to_owned(),
679/// "web_search".to_owned(),
680/// opaque::Payload::copy_from_slice(br#"{"max_results":5}"#),
681/// )
682/// .unwrap(),
683/// );
684/// assert_eq!(hosted.lane(), tool::Lane::Hosted);
685///
686/// let mut registry = tool::RegistryBuilder::new();
687/// registry.register(hosted);
688/// // Names are canonical and collisions fail closed, before any side effect.
689/// assert!(registry.build().is_ok());
690/// ```
691///
692/// [`Executor`] carries the client-lane example.
693#[derive(Clone)]
694pub struct Registration {
695 descriptor: Descriptor,
696 executor: Option<Arc<dyn ErasedExecutor>>,
697 hosted_extension: Option<Envelope>,
698}
699
700impl Debug for Registration {
701 /// Shows what was registered and whether a local dispatcher backs it.
702 ///
703 /// The executor is a trait object with no `Debug`, and its presence is the
704 /// fact that matters anyway: it is exactly what makes this a client lane
705 /// rather than a hosted one.
706 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
707 formatter
708 .debug_struct("Registration")
709 .field("descriptor", &self.descriptor)
710 .field("executor", &redact::Presence(self.executor.is_some()))
711 .field("hosted_extension", &self.hosted_extension)
712 .finish()
713 }
714}
715
716impl Registration {
717 /// Statically pairs a client executor output with its only mapper.
718 #[must_use]
719 pub fn client<E, M>(descriptor: Descriptor, executor: Arc<E>, mapper: Arc<M>) -> Self
720 where
721 E: Executor,
722 M: Fn(E::Output) -> Result<ToolResult, MappingError> + Send + Sync + 'static,
723 {
724 Self {
725 descriptor,
726 executor: Some(Arc::new(TypedExecutor { executor, mapper })),
727 hosted_extension: None,
728 }
729 }
730
731 /// Creates a model-native registration with an owned provider extension and
732 /// no local dispatcher.
733 #[must_use]
734 pub fn hosted(descriptor: Descriptor, extension: Envelope) -> Self {
735 Self {
736 descriptor,
737 executor: None,
738 hosted_extension: Some(extension),
739 }
740 }
741
742 /// Returns the owned model descriptor.
743 #[must_use]
744 pub const fn descriptor(&self) -> &Descriptor {
745 &self.descriptor
746 }
747
748 /// Returns the immutable execution lane.
749 #[must_use]
750 pub const fn lane(&self) -> Lane {
751 if self.executor.is_some() {
752 Lane::Client
753 } else {
754 Lane::Hosted
755 }
756 }
757}
758
759/// A stable static-registry construction failure.
760#[derive(Clone, Debug, Eq, PartialEq)]
761#[non_exhaustive]
762pub enum RegistryError {
763 /// Two static registrations used the same canonical name.
764 StaticCollision(Name),
765}
766
767impl Display for RegistryError {
768 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
769 match self {
770 Self::StaticCollision(name) => {
771 write!(formatter, "duplicate static tool: {}", name.canonical())
772 }
773 }
774 }
775}
776
777impl Error for RegistryError {}
778
779/// A nonfatal failure from one dynamic provider resolution.
780///
781/// The message is the stable operator diagnostic rendered by [`Display`]. A
782/// concrete underlying failure can be retained with
783/// [`with_source`](Self::with_source), so an outward [`Kind::Error`] consumer can
784/// inspect and downcast the complete error chain without changing that
785/// diagnostic. Equality compares the message only because an arbitrary error
786/// source has no meaningful general equality operation.
787///
788/// [`Kind::Error`]: crate::runtime::event::Kind::Error
789#[derive(Clone)]
790pub struct ProviderError {
791 message: String,
792 source: Option<Arc<dyn Error + Send + Sync>>,
793}
794
795impl ProviderError {
796 /// Creates an owned provider error without an underlying cause.
797 #[must_use]
798 pub const fn new(message: String) -> Self {
799 Self {
800 message,
801 source: None,
802 }
803 }
804
805 /// Retains the concrete failure that caused this provider to degrade.
806 ///
807 /// The source is returned from [`Error::source`] and does not affect the
808 /// displayed message or equality.
809 #[must_use]
810 pub fn with_source(mut self, source: impl Error + Send + Sync + 'static) -> Self {
811 self.source = Some(Arc::new(source));
812 self
813 }
814}
815
816impl fmt::Debug for ProviderError {
817 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
818 let mut tuple = formatter.debug_tuple("ProviderError");
819 tuple.field(&self.message);
820 let mut link = Error::source(self);
821 while let Some(error) = link {
822 tuple.field(&error.to_string());
823 link = error.source();
824 }
825 tuple.finish()
826 }
827}
828
829impl Display for ProviderError {
830 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
831 formatter.write_str(&self.message)
832 }
833}
834
835impl PartialEq for ProviderError {
836 fn eq(&self, other: &Self) -> bool {
837 self.message == other.message
838 }
839}
840
841impl Eq for ProviderError {}
842
843impl Error for ProviderError {
844 fn source(&self) -> Option<&(dyn Error + 'static)> {
845 self.source
846 .as_ref()
847 .map(|source| source.as_ref() as &(dyn Error + 'static))
848 }
849}
850
851/// One all-or-nothing dynamic provider observation.
852#[derive(Debug)]
853pub struct ProviderResolution {
854 entries: Vec<Registration>,
855 error: Option<ProviderError>,
856}
857
858impl ProviderResolution {
859 /// Creates a successful provider observation.
860 #[must_use]
861 pub const fn success(entries: Vec<Registration>) -> Self {
862 Self {
863 entries,
864 error: None,
865 }
866 }
867
868 /// Creates a failed observation; all supplied partial entries are discarded.
869 #[must_use]
870 pub const fn failed(partial_entries: Vec<Registration>, error: ProviderError) -> Self {
871 Self {
872 entries: partial_entries,
873 error: Some(error),
874 }
875 }
876}
877
878/// A dynamic tool source resolved exactly once by each Step resolution.
879///
880/// # The resolved tool set may differ every Step, and that is not a loophole
881///
882/// [`Provider::resolve`] runs once per Step, so a provider may legitimately
883/// return a different set at every Step of the same Run: tools that appear once
884/// a file is opened, a scope that narrows after a denial, a catalogue that a
885/// search step widens. This does **not** contradict the rule that configuration
886/// is fixed for a Run. What is frozen is the
887/// [`agent::Revision`](crate::runtime::agent::Revision) — the provider roster,
888/// the hook roster, the system instruction — not the *result* of consulting
889/// that roster. The roster is the configuration; the resolution is a per-Step
890/// observation of it, exactly like the transcript the same Step freezes.
891///
892/// Anyone reaching for a way to make the tool set vary within a Run therefore
893/// already has one, and any proposal to relax the Run-granularity rule on those
894/// grounds is answering a problem that does not exist. What a Run genuinely
895/// cannot do is add or remove a *provider*, change the model client, or change
896/// the hook set; that is a successor Run with a new revision.
897///
898/// # Why this boundary awaits
899///
900/// A tool set that varies per Step is usually one somebody has to go and ask
901/// for: a remote catalogue, a tenant entitlement lookup, a capability handshake.
902/// [`Executor`] already awaits for the same reason, and this boundary produces
903/// the resolution that execution is routed against, so a synchronous signature
904/// here would leave the only boundary that decides *which* tools exist as the
905/// only one unable to ask. Explicit boxed-future erasure follows ADR-013, so
906/// awaiting costs this registry boundary no object safety.
907///
908/// A background refresher is not an equivalent: it answers with whatever it
909/// last fetched, which is the one thing a Step-top resolution must not do when
910/// the Step's own request is the thing that has to see the new tool.
911pub trait Provider: Send + Sync + 'static {
912 /// Resolves owned entries from the provider's current state against the
913 /// exact frozen Step-top transcript later handed to every
914 /// [`Invocation`] in the same Step.
915 ///
916 /// Resolution is all-or-nothing: a [`ProviderResolution::failed`]
917 /// observation discards every partial entry and degrades this provider only.
918 /// Resolution runs once per Step, which is what lets the resolved tool set
919 /// differ between Steps without any Run-level binding changing.
920 ///
921 /// # Cancellation
922 ///
923 /// The returned future must be cancellation-safe on the same terms
924 /// [`Executor::execute`] states: the caller may drop it at any await point
925 /// after cancelling the supplied token, and dropping it must release
926 /// resources synchronously rather than detach work. Nothing observable has
927 /// happened at this point in the Step — no request is materialized and no
928 /// executor has run — so a dropped resolution leaves nothing to undo.
929 fn resolve<'a>(
930 &'a self,
931 transcript: &'a Snapshot,
932 cancellation: Token,
933 ) -> Pin<Box<dyn Future<Output = ProviderResolution> + Send + 'a>>;
934}
935
936/// Mutable registration surface consumed into an immutable registry.
937#[derive(Default)]
938pub struct RegistryBuilder {
939 static_entries: Vec<Registration>,
940 providers: Vec<Arc<dyn Provider>>,
941}
942
943impl Debug for RegistryBuilder {
944 /// Shows what has been registered so far and how many providers will run.
945 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
946 debug_registry(
947 "RegistryBuilder",
948 &self.static_entries,
949 &self.providers,
950 formatter,
951 )
952 }
953}
954
955// A registry and the builder it is frozen from hold the same two lanes, and a
956// provider is an `Arc<dyn Provider>` with no `Debug`, so both report the static
957// names they will expose and count the providers they will consult.
958fn debug_registry(
959 name: &str,
960 static_entries: &[Registration],
961 providers: &[Arc<dyn Provider>],
962 formatter: &mut Formatter<'_>,
963) -> fmt::Result {
964 formatter
965 .debug_struct(name)
966 .field(
967 "static_entries",
968 &static_entries
969 .iter()
970 .map(|entry| entry.descriptor.name.canonical())
971 .collect::<Vec<_>>(),
972 )
973 .field("providers", &providers.len())
974 .finish()
975}
976
977impl RegistryBuilder {
978 /// Creates an empty registry builder.
979 #[must_use]
980 pub fn new() -> Self {
981 Self::default()
982 }
983
984 /// Adds one owned static registration.
985 pub fn register(&mut self, registration: Registration) -> &mut Self {
986 self.static_entries.push(registration);
987 self
988 }
989
990 /// Adds one dynamic provider handle.
991 pub fn provider(&mut self, provider: Arc<dyn Provider>) -> &mut Self {
992 self.providers.push(provider);
993 self
994 }
995
996 /// Validates all static names and freezes the registry.
997 ///
998 /// # Errors
999 ///
1000 /// [`RegistryError::StaticCollision`], naming the tool, if two static
1001 /// registrations share one canonical name. It fails here rather than at
1002 /// resolution so that no model ever sees an ambiguous roster and no executor
1003 /// runs for a call whose routing was already undecidable — a collision is a
1004 /// wiring mistake, and the build is the last moment at which nothing has
1005 /// happened yet.
1006 ///
1007 /// Providers cannot be checked here, because they resolve per Step. A name
1008 /// that only collides once a provider has produced it is reported by
1009 /// [`Registry::resolve_step`] as [`StepResolutionError::Collision`] — the
1010 /// same fail-closed rule, applied at the only moment the full set exists, and
1011 /// still before any model request or executor sees it.
1012 pub fn build(self) -> Result<Registry, RegistryError> {
1013 let mut names = HashSet::new();
1014 for entry in &self.static_entries {
1015 if !names.insert(entry.descriptor.name.clone()) {
1016 return Err(RegistryError::StaticCollision(
1017 entry.descriptor.name.clone(),
1018 ));
1019 }
1020 }
1021 Ok(Registry {
1022 static_entries: self.static_entries,
1023 providers: self.providers,
1024 })
1025 }
1026}
1027
1028/// An immutable, shareable static registry and provider set.
1029#[derive(Clone)]
1030pub struct Registry {
1031 static_entries: Vec<Registration>,
1032 providers: Vec<Arc<dyn Provider>>,
1033}
1034
1035impl Debug for Registry {
1036 /// Shows the frozen static names and how many providers back them.
1037 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1038 debug_registry("Registry", &self.static_entries, &self.providers, formatter)
1039 }
1040}
1041
1042/// Filters model exposure before a Step snapshot materializes.
1043///
1044/// This is crate-private and ADR-027 records why. The correction point is real
1045/// and the runtime applies it, but the only production filter is [`ExposeAll`]:
1046/// a composition layer that wants a narrower Step roster narrows what its own
1047/// [`Provider`] returns, or filters `Request::tools` in an
1048/// [`ModelHooks::before_model`](crate::runtime::hook::ModelHooks::before_model)
1049/// registration paired with a
1050/// [`Block`](crate::runtime::hook::ToolCallDecision::Block) in
1051/// [`ToolHooks::before_tool_call`](crate::runtime::hook::ToolHooks::before_tool_call).
1052///
1053/// The `Sync` bound is what holding this filter across a provider's await costs
1054/// (ADR-024 D3), and it is the whole of it: the filter is only ever borrowed, so
1055/// nothing here has to be `Send`.
1056pub(crate) trait ExposureFilter: Sync {
1057 /// Returns whether one validated registration remains exposed and routable.
1058 fn exposed(&self, descriptor: &Descriptor, lane: Lane) -> bool;
1059}
1060
1061/// A filter that exposes every validated registration.
1062#[derive(Debug)]
1063pub(crate) struct ExposeAll;
1064
1065impl ExposureFilter for ExposeAll {
1066 fn exposed(&self, _descriptor: &Descriptor, _lane: Lane) -> bool {
1067 true
1068 }
1069}
1070
1071/// A dynamic collision discovered before model or executor activity.
1072#[derive(Clone, Debug, Eq, PartialEq)]
1073#[non_exhaustive]
1074pub enum StepResolutionError {
1075 /// A dynamic name collided within/across providers or with a static name.
1076 Collision(Name),
1077}
1078
1079impl Display for StepResolutionError {
1080 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1081 match self {
1082 Self::Collision(name) => write!(formatter, "Step tool collision: {}", name.canonical()),
1083 }
1084 }
1085}
1086
1087impl Error for StepResolutionError {}
1088
1089/// The result of one resolve-once Step boundary.
1090#[derive(Debug)]
1091pub struct StepResolution {
1092 snapshot: StepToolSnapshot,
1093 provider_errors: Vec<ProviderError>,
1094}
1095
1096impl StepResolution {
1097 /// Returns the immutable Step snapshot.
1098 #[must_use]
1099 pub const fn snapshot(&self) -> &StepToolSnapshot {
1100 &self.snapshot
1101 }
1102
1103 /// Transfers the immutable Step snapshot.
1104 #[must_use]
1105 pub fn into_snapshot(self) -> StepToolSnapshot {
1106 self.snapshot
1107 }
1108
1109 /// Splits this resolution into its owned snapshot and the ordered
1110 /// per-degraded-provider diagnostics.
1111 ///
1112 /// This is the crate-private twin of
1113 /// [`into_snapshot`](Self::into_snapshot) plus
1114 /// [`provider_errors`](Self::provider_errors), and it exists so
1115 /// the loop can publish one nonfatal Error per degraded provider without the
1116 /// public surface growing a second accessor for a value the pair above
1117 /// already exposes. The diagnostics stay in provider registration order.
1118 #[must_use]
1119 pub(crate) fn into_parts(self) -> (StepToolSnapshot, Vec<ProviderError>) {
1120 (self.snapshot, self.provider_errors)
1121 }
1122
1123 /// Returns one nonfatal diagnostic for each degraded provider.
1124 #[must_use]
1125 pub fn provider_errors(&self) -> &[ProviderError] {
1126 &self.provider_errors
1127 }
1128}
1129
1130impl Registry {
1131 /// Resolves every provider once against one frozen transcript snapshot,
1132 /// validates the full set, and then freezes one owned Step snapshot that
1133 /// reuses that exact transcript version.
1134 ///
1135 /// Providers are resolved in registration order, one await at a time. The
1136 /// order is the registration order for the same reason the hook fan-outs
1137 /// use it — it is the only order a composition layer declared — and the
1138 /// sequencing is deliberate rather than incidental: a concurrent fan-out
1139 /// would make the diagnostic order of degraded providers depend on which
1140 /// remote answered first, and this value is compared in tests and logs.
1141 ///
1142 /// Every validated registration is exposed. Narrowing the roster is a
1143 /// composition-layer decision taken one rail earlier, in what a [`Provider`]
1144 /// returns, or one rail later, in what an
1145 /// [`OnBeforeModel`](crate::runtime::hook::ModelHooks::before_model)
1146 /// registration leaves in `Request::tools`; ADR-027 records why core
1147 /// publishes neither a filter nor a mount point for one.
1148 ///
1149 /// # Errors
1150 ///
1151 /// Returns [`StepResolutionError::Collision`] before any model request or
1152 /// executor dispatch can observe the ambiguity.
1153 pub async fn resolve_step(
1154 &self,
1155 transcript: Snapshot,
1156 cancellation: &Token,
1157 ) -> Result<StepResolution, StepResolutionError> {
1158 self.resolve_step_filtered(transcript, cancellation, &ExposeAll)
1159 .await
1160 }
1161
1162 /// Resolves as [`resolve_step`](Self::resolve_step) does, then drops every
1163 /// registration the correction hides from both the model and the router.
1164 ///
1165 /// The correction is applied after validation, so a name that collides is
1166 /// still an error even when the filter would have hidden it: hiding an
1167 /// ambiguity is not the same as not having one.
1168 pub(crate) async fn resolve_step_filtered(
1169 &self,
1170 transcript: Snapshot,
1171 cancellation: &Token,
1172 correction: &dyn ExposureFilter,
1173 ) -> Result<StepResolution, StepResolutionError> {
1174 let mut entries = self.static_entries.clone();
1175 let mut provider_errors = Vec::new();
1176 for provider in &self.providers {
1177 let resolution = provider.resolve(&transcript, cancellation.clone()).await;
1178 if let Some(error) = resolution.error {
1179 provider_errors.push(error);
1180 } else {
1181 entries.extend(resolution.entries);
1182 }
1183 }
1184
1185 let mut names = HashSet::new();
1186 for entry in &entries {
1187 if !names.insert(entry.descriptor.name.clone()) {
1188 return Err(StepResolutionError::Collision(
1189 entry.descriptor.name.clone(),
1190 ));
1191 }
1192 }
1193 entries.retain(|entry| correction.exposed(&entry.descriptor, entry.lane()));
1194 Ok(StepResolution {
1195 snapshot: StepToolSnapshot {
1196 entries,
1197 transcript,
1198 },
1199 provider_errors,
1200 })
1201 }
1202
1203 /// Resolves a registry that registered no dynamic provider, without a runtime.
1204 ///
1205 /// [`resolve_step`](Self::resolve_step) awaits its providers, and most
1206 /// fixtures across the runtime tests have none: they build a snapshot out of
1207 /// static registrations so that some other boundary has one to route
1208 /// against. Those tests are synchronous, and making each of them claim a
1209 /// reactor to drive a future that cannot park would say something false
1210 /// about what they exercise. The `Pending` arm is the assertion that the
1211 /// caller really is such a fixture.
1212 #[cfg(test)]
1213 pub(crate) fn resolve_step_without_providers(
1214 &self,
1215 transcript: Snapshot,
1216 cancellation: &Token,
1217 correction: &dyn ExposureFilter,
1218 ) -> Result<StepResolution, StepResolutionError> {
1219 let mut resolving =
1220 Box::pin(self.resolve_step_filtered(transcript, cancellation, correction));
1221 match resolving
1222 .as_mut()
1223 .poll(&mut Context::from_waker(Waker::noop()))
1224 {
1225 Poll::Ready(resolved) => resolved,
1226 Poll::Pending => {
1227 panic!("a registry with no dynamic provider resolves on its first poll")
1228 }
1229 }
1230 }
1231}
1232
1233/// A fatal or cancellation outcome from routing one local call.
1234///
1235/// Unknown tool names are deliberately absent: an unexposed name is an ordinary
1236/// business rejection, not a control-path failure, so the model can be told
1237/// about it in the transcript instead of the Run failing.
1238#[derive(Clone, Debug, Eq, PartialEq)]
1239#[non_exhaustive]
1240pub enum ExecutionError {
1241 /// A hosted/model-native capability was sent to the local path.
1242 Hosted(String),
1243 /// Cancellation won the control path.
1244 Cancelled,
1245 /// Output mapping failed fatally.
1246 Mapping(MappingError),
1247}
1248
1249impl Display for ExecutionError {
1250 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1251 match self {
1252 Self::Hosted(name) => {
1253 write!(formatter, "hosted tool is not locally dispatchable: {name}")
1254 }
1255 Self::Cancelled => formatter.write_str("tool run cancelled"),
1256 Self::Mapping(error) => write!(formatter, "tool output mapping failed: {error}"),
1257 }
1258 }
1259}
1260
1261impl Error for ExecutionError {
1262 fn source(&self) -> Option<&(dyn Error + 'static)> {
1263 match self {
1264 Self::Mapping(error) => Some(error),
1265 Self::Hosted(_) | Self::Cancelled => None,
1266 }
1267 }
1268}
1269
1270/// The furthest stable disposition reached by a started `ToolCall`.
1271///
1272/// Only [`Self::Executed`] and [`Self::Rejected`] can be produced by
1273/// [`StepToolSnapshot::execute`]; the remaining states are reached by the hook
1274/// and terminal-unwind paths that observe the same closed vocabulary.
1275#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1276#[non_exhaustive]
1277pub enum CallDisposition {
1278 /// Entered tool execution.
1279 Executed,
1280 /// A hook supplied a result without execution.
1281 ShortCircuited,
1282 /// A hook blocked execution.
1283 Blocked,
1284 /// Core rejected an unavailable call.
1285 Rejected,
1286 /// Output-token truncation left the call incomplete.
1287 Truncated,
1288 /// Terminal unwinding began before another stable disposition.
1289 NotExecuted,
1290}
1291
1292/// One closed business outcome of routing an accepted effective call.
1293///
1294/// A successful route always carries both the model-visible closed result and
1295/// the disposition fact later published by lifecycle observations, so callers
1296/// never re-derive the disposition from the result's shape.
1297#[derive(Clone, Debug)]
1298pub struct ExecutionOutcome {
1299 result: ToolResult,
1300 disposition: CallDisposition,
1301}
1302
1303impl ExecutionOutcome {
1304 /// Returns the model-visible closed result.
1305 #[must_use]
1306 pub const fn result(&self) -> &ToolResult {
1307 &self.result
1308 }
1309
1310 /// Returns the stable disposition reached by this call.
1311 #[must_use]
1312 pub const fn disposition(&self) -> CallDisposition {
1313 self.disposition
1314 }
1315
1316 /// Transfers the closed result and its disposition.
1317 #[must_use]
1318 pub fn into_parts(self) -> (ToolResult, CallDisposition) {
1319 (self.result, self.disposition)
1320 }
1321}
1322
1323/// One immutable model-exposure and host-routing snapshot.
1324#[derive(Debug)]
1325pub struct StepToolSnapshot {
1326 entries: Vec<Registration>,
1327 transcript: Snapshot,
1328}
1329
1330impl StepToolSnapshot {
1331 /// Creates the crate-private shallow twin used by `StepSnapshot`.
1332 ///
1333 /// Registrations retain the same executor/mapper handles and the transcript
1334 /// retains the same shared item backing; no provider is resolved again.
1335 #[must_use]
1336 pub(crate) fn shallow_clone(&self) -> Self {
1337 Self {
1338 entries: self.entries.clone(),
1339 transcript: self.transcript.clone(),
1340 }
1341 }
1342
1343 /// Returns the frozen Step-top transcript shared by this Step's provider
1344 /// resolution and every invocation minted from this snapshot.
1345 #[must_use]
1346 pub const fn transcript(&self) -> &Snapshot {
1347 &self.transcript
1348 }
1349
1350 /// Returns every frozen exposed descriptor and lane in deterministic order.
1351 #[must_use]
1352 pub fn exposure(&self) -> impl ExactSizeIterator<Item = (&Descriptor, Lane)> {
1353 self.entries
1354 .iter()
1355 .map(|entry| (&entry.descriptor, entry.lane()))
1356 }
1357
1358 /// Materializes the client/local lane for [`crate::runtime::model::RequestPlan`].
1359 #[must_use]
1360 pub fn client_model_tools(&self) -> Vec<ClientTool> {
1361 self.entries
1362 .iter()
1363 .filter(|entry| entry.lane() == Lane::Client)
1364 .map(|entry| entry.descriptor.client_model_tool())
1365 .collect()
1366 }
1367
1368 /// Materializes the hosted/model-native lane for
1369 /// [`crate::runtime::model::RequestPlan`].
1370 #[must_use]
1371 pub fn hosted_model_extensions(&self) -> Vec<Envelope> {
1372 self.entries
1373 .iter()
1374 .filter_map(|entry| entry.hosted_extension.clone())
1375 .collect()
1376 }
1377
1378 /// Applies both model-visible lanes from this exact Step snapshot.
1379 pub fn apply_to_plan(&self, plan: &mut RequestPlan) {
1380 plan.extend_tools(self.client_model_tools())
1381 .extend_extensions(self.hosted_model_extensions());
1382 }
1383
1384 /// Mints one invocation whose transcript shares this snapshot's exact
1385 /// immutable backing, so no caller can substitute another transcript version.
1386 ///
1387 /// Minting requires both a core-resolved snapshot and a
1388 /// [`ToolEmitter`], whose outward authority and [`crate::value::lifecycle::Coord`]
1389 /// are stamped by core. Neither the outward producer nor any run state is
1390 /// reachable through this seam. Outside a live run, pass
1391 /// [`ToolEmitter::closed`].
1392 #[must_use]
1393 pub fn invocation(
1394 &self,
1395 session_id: Option<String>,
1396 call_id: Id,
1397 emitter: ToolEmitter,
1398 ) -> Invocation {
1399 Invocation::new(session_id, self.transcript.clone(), call_id, emitter)
1400 }
1401
1402 /// Routes one accepted effective call to its captured executor.
1403 ///
1404 /// # Errors
1405 ///
1406 /// Returns [`ExecutionError`] only for control-path failures: hosted
1407 /// misrouting, cancellation, and fatal output mapping. Unknown names and
1408 /// ordinary executor failures are business outcomes.
1409 pub async fn execute(
1410 &self,
1411 invocation: &Invocation,
1412 call: &ToolCall,
1413 cancellation: &Token,
1414 ) -> Result<ExecutionOutcome, ExecutionError> {
1415 if cancellation.is_cancelled() {
1416 return Err(ExecutionError::Cancelled);
1417 }
1418 // A registration is keyed by a validated `Name`, so the binding is
1419 // recovered by parsing the emission back into one — the inverse of the
1420 // `to_wire` spelling that advertised it — rather than by comparing
1421 // strings. An emission the grammar rejects cannot name any registration,
1422 // and it stays a business result: the model has to be told which name it
1423 // asked for, which is why the raw emission is reported unchanged.
1424 let emitted = call.name().as_str();
1425 let Some(entry) = Name::parse_canonical(emitted).ok().and_then(|name| {
1426 self.entries
1427 .iter()
1428 .find(|candidate| candidate.descriptor.name == name)
1429 }) else {
1430 return Ok(rejected(format!("unknown tool: {emitted}")));
1431 };
1432 let Some(executor) = &entry.executor else {
1433 return Err(ExecutionError::Hosted(emitted.to_owned()));
1434 };
1435
1436 match executor
1437 .execute_mapped(invocation, call, cancellation.clone())
1438 .await
1439 {
1440 Ok(result) => Ok(ExecutionOutcome {
1441 result,
1442 disposition: CallDisposition::Executed,
1443 }),
1444 Err(ErasedExecutionError::Cancelled) => Err(ExecutionError::Cancelled),
1445 Err(ErasedExecutionError::Mapping(error)) => Err(ExecutionError::Mapping(error)),
1446 }
1447 }
1448}
1449
1450fn rejected(message: String) -> ExecutionOutcome {
1451 // Matches the closed `ToolResult::error_text` business-result producer.
1452 ExecutionOutcome {
1453 result: ToolResult::error_text(message),
1454 disposition: CallDisposition::Rejected,
1455 }
1456}