Skip to main content

merry_runtime/tool/
registry.rs

1use crate::{
2    final_output::FINAL_OUTPUT_TOOL_NAME,
3    tool::{
4        executor::{ToolExecutionContext, ToolExecutionError, ToolExecutor, ToolExecutorFuture},
5        proposal::ToolActionKind,
6    },
7    tool_input_validation::{CompiledToolInputValidator, ToolInputValidationError},
8};
9use merry_core::{PendingToolCall, ToolName, ToolSpec};
10use std::{collections::BTreeMap, sync::Arc};
11
12/// Where a registered tool is executed.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum ToolRunner {
15    /// Merry/Rust runtime owns execution through a [`ToolExecutor`].
16    Runtime,
17    /// An external SDK runner executes after Merry emits a bridge event.
18    Bridge,
19}
20
21/// Runtime execution policy for calls that appear in the same model batch.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ToolConcurrency {
24    /// Calls may execute concurrently with adjacent parallel-safe calls.
25    ParallelSafe,
26    /// The call executes alone and acts as a barrier between concurrent waves.
27    Exclusive,
28}
29
30/// Typed Plan Mode / checklist intrinsic operations owned by the runtime.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub(crate) enum PlanIntrinsicTool {
33    EnterPlanMode,
34    WritePlan,
35    ReadPlan,
36    ExitPlanMode,
37    UpdateTodos,
38}
39
40/// Typed runtime-intrinsic dispatch target bound at tool registration time.
41///
42/// Storing the dispatch target on [`RegisteredTool`] eliminates name-based
43/// string dispatch inside tool execution.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub(crate) enum RuntimeIntrinsicTool {
46    Plan(PlanIntrinsicTool),
47    RequestPermissions,
48}
49
50/// Proposal preflight and low-risk workspace patch lane policy for a registered tool.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub(crate) enum ToolActionProposalMode {
53    /// Proposal preflight is disabled.
54    Disabled,
55    /// Runtime requests read-only proposal evidence before mutating execution.
56    Enabled,
57    /// Proposal preflight is enabled and this tool is eligible for the runtime's
58    /// opt-in low-risk workspace patch lane.
59    LowRiskWorkspacePatch,
60}
61
62/// Runtime-owned registered tool definition.
63///
64/// A registered tool binds a provider-visible spec to an executor. It does not
65/// start or automate a tool loop. [`crate::Runtime::submit_tool_result`] is the
66/// external/manual result path; [`crate::Runtime::execute_tool_call`] is the
67/// runtime-registered executor path.
68#[derive(Clone)]
69pub struct RegisteredTool {
70    pub(super) spec: ToolSpec,
71    pub(super) external_binding: Option<merry_core::ExternalToolBinding>,
72    pub(super) executor: Arc<dyn ToolExecutor>,
73    pub(super) action_kind: ToolActionKind,
74    pub(super) proposal_mode: ToolActionProposalMode,
75    pub(super) intrinsic: Option<RuntimeIntrinsicTool>,
76    pub(super) runner: ToolRunner,
77    pub(super) concurrency: ToolConcurrency,
78}
79
80impl RegisteredTool {
81    /// Creates a registered tool with an explicit runtime-owned action category.
82    ///
83    /// The spec is provider-visible after adapter rendering, but the executor
84    /// remains a runtime-owned boundary. The action category stays inside
85    /// runtime and is not rendered into the provider-visible tool spec.
86    #[must_use]
87    pub fn new(
88        spec: ToolSpec,
89        executor: Arc<dyn ToolExecutor>,
90        action_kind: ToolActionKind,
91    ) -> Self {
92        Self {
93            spec,
94            external_binding: None,
95            executor,
96            action_kind,
97            proposal_mode: ToolActionProposalMode::Disabled,
98            intrinsic: None,
99            runner: ToolRunner::Runtime,
100            concurrency: ToolConcurrency::Exclusive,
101        }
102    }
103
104    /// Creates a runtime-owned intrinsic control tool bound to its typed
105    /// dispatch target.
106    ///
107    /// Intrinsic tools always carry [`ToolActionKind::RuntimeControl`] and are
108    /// intercepted by runtime dispatch before the generic executor path.
109    #[must_use]
110    pub(crate) fn intrinsic(spec: ToolSpec, intrinsic: RuntimeIntrinsicTool) -> Self {
111        Self {
112            spec,
113            external_binding: None,
114            executor: Arc::new(IntrinsicToolExecutor),
115            action_kind: ToolActionKind::RuntimeControl,
116            proposal_mode: ToolActionProposalMode::Disabled,
117            intrinsic: Some(intrinsic),
118            runner: ToolRunner::Runtime,
119            concurrency: ToolConcurrency::Exclusive,
120        }
121    }
122
123    /// Attaches a stable adapter binding for session catalog persistence.
124    ///
125    /// Binding metadata is never rendered into the model's tool definition.
126    #[must_use]
127    pub fn with_external_binding(mut self, binding: merry_core::ExternalToolBinding) -> Self {
128        self.external_binding = Some(binding);
129        self
130    }
131
132    /// Returns the adapter identity, if this tool belongs to an external catalog.
133    #[must_use]
134    pub fn external_binding(&self) -> Option<&merry_core::ExternalToolBinding> {
135        self.external_binding.as_ref()
136    }
137
138    /// Enables read-only proposal evidence for a mutating tool.
139    ///
140    /// Runtime calls [`ToolExecutor::propose`] only for registered tools that
141    /// explicitly opt in here. The hook is still skipped for read-only tools.
142    #[must_use]
143    pub fn with_action_proposal(mut self) -> Self {
144        if self.proposal_mode == ToolActionProposalMode::Disabled {
145            self.proposal_mode = ToolActionProposalMode::Enabled;
146        }
147        self
148    }
149
150    /// Opts a [`ToolActionKind::WorkspaceWrite`] tool into the low-risk
151    /// workspace patch lane when the runtime enables
152    /// [`crate::RuntimeBuilder::allow_low_risk_apply_patches`].
153    ///
154    /// Automatically enables read-only action proposals so callers cannot
155    /// misconfigure the patch lane without proposal preflight.
156    #[must_use]
157    pub fn with_low_risk_workspace_patch_lane(mut self) -> Self {
158        self.proposal_mode = ToolActionProposalMode::LowRiskWorkspacePatch;
159        self
160    }
161
162    /// Opts this tool into bounded concurrent execution within one model batch.
163    ///
164    /// Use this only when concurrent calls cannot race through writes,
165    /// processes, network access, permissions, or runtime-control state.
166    #[must_use]
167    pub fn with_parallel_safe_execution(mut self) -> Self {
168        self.concurrency = ToolConcurrency::ParallelSafe;
169        self
170    }
171
172    /// Creates a registered read-only tool.
173    ///
174    /// Use this only for tools that do not write workspace state or execute
175    /// commands. Network access is controlled by runtime profile, not by this
176    /// constructor.
177    #[must_use]
178    pub fn read_only(spec: ToolSpec, executor: Arc<dyn ToolExecutor>) -> Self {
179        Self::new(spec, executor, ToolActionKind::ReadOnly)
180    }
181
182    /// Creates a tool whose execution is delegated to an external SDK bridge.
183    #[must_use]
184    pub fn bridge(spec: ToolSpec) -> Self {
185        Self {
186            spec,
187            external_binding: None,
188            executor: Arc::new(BridgeExecutor),
189            action_kind: ToolActionKind::ReadOnly,
190            proposal_mode: ToolActionProposalMode::Disabled,
191            intrinsic: None,
192            runner: ToolRunner::Bridge,
193            concurrency: ToolConcurrency::Exclusive,
194        }
195    }
196
197    /// Borrows the provider-visible tool specification.
198    #[must_use]
199    pub fn spec(&self) -> &ToolSpec {
200        &self.spec
201    }
202
203    /// Returns the runtime-owned action category for this tool.
204    #[must_use]
205    pub fn action_kind(&self) -> ToolActionKind {
206        self.action_kind
207    }
208
209    /// Returns where this tool is executed.
210    #[must_use]
211    pub fn runner(&self) -> ToolRunner {
212        self.runner
213    }
214
215    /// Returns the runtime execution policy for batched calls.
216    #[must_use]
217    pub fn concurrency(&self) -> ToolConcurrency {
218        self.concurrency
219    }
220
221    /// Returns whether this tool opted into action proposal evidence.
222    #[must_use]
223    pub const fn proposals_enabled(&self) -> bool {
224        !matches!(self.proposal_mode, ToolActionProposalMode::Disabled)
225    }
226
227    /// Returns whether this tool opted into the low-risk workspace patch lane.
228    #[must_use]
229    pub const fn low_risk_workspace_patch_lane(&self) -> bool {
230        matches!(
231            self.proposal_mode,
232            ToolActionProposalMode::LowRiskWorkspacePatch
233        )
234    }
235
236    /// Returns the typed proposal policy for this tool.
237    #[must_use]
238    pub(crate) const fn proposal_mode(&self) -> ToolActionProposalMode {
239        self.proposal_mode
240    }
241
242    /// Returns the typed runtime-intrinsic dispatch target, if any.
243    #[must_use]
244    pub(crate) const fn runtime_intrinsic(&self) -> Option<RuntimeIntrinsicTool> {
245        self.intrinsic
246    }
247
248    pub(crate) fn executor(&self) -> Arc<dyn ToolExecutor> {
249        Arc::clone(&self.executor)
250    }
251}
252
253struct IntrinsicToolExecutor;
254
255impl ToolExecutor for IntrinsicToolExecutor {
256    fn execute<'a>(
257        &'a self,
258        call: PendingToolCall,
259        _context: ToolExecutionContext,
260    ) -> ToolExecutorFuture<'a> {
261        Box::pin(async move {
262            Err(ToolExecutionError::infrastructure(format!(
263                "intrinsic runtime tool {} reached the generic executor",
264                call.name().as_str()
265            )))
266        })
267    }
268}
269
270pub(super) struct BridgeExecutor;
271
272impl ToolExecutor for BridgeExecutor {
273    fn execute<'a>(
274        &'a self,
275        call: PendingToolCall,
276        _context: ToolExecutionContext,
277    ) -> ToolExecutorFuture<'a> {
278        Box::pin(async move {
279            Err(ToolExecutionError::infrastructure(format!(
280                "bridge tool {} must be executed by a bridge runner",
281                call.name().as_str()
282            )))
283        })
284    }
285}
286
287impl std::fmt::Debug for RegisteredTool {
288    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289        formatter
290            .debug_struct("RegisteredTool")
291            .field("spec", &self.spec)
292            .field("action_kind", &self.action_kind)
293            .field("proposal_mode", &self.proposal_mode)
294            .field("intrinsic", &self.intrinsic)
295            .field("runner", &self.runner)
296            .field("concurrency", &self.concurrency)
297            .finish_non_exhaustive()
298    }
299}
300
301#[derive(Debug, Clone, Default)]
302pub(crate) struct ToolRegistry {
303    pub(super) tools: BTreeMap<ToolName, RegisteredToolEntry>,
304    pub(super) order: Vec<ToolName>,
305}
306
307#[derive(Debug, Clone)]
308pub(super) struct RegisteredToolEntry {
309    pub(super) tool: RegisteredTool,
310    pub(super) input_validator: CompiledToolInputValidator,
311}
312
313impl ToolRegistry {
314    pub(crate) fn from_registered(tools: Vec<RegisteredTool>) -> Result<Self, ToolRegistryError> {
315        let mut registry = BTreeMap::new();
316        let mut order = Vec::with_capacity(tools.len());
317
318        for tool in tools {
319            let name = tool.spec().name().clone();
320            if name.as_str() == FINAL_OUTPUT_TOOL_NAME {
321                return Err(ToolRegistryError::ReservedName { name });
322            }
323            let input_validator = CompiledToolInputValidator::compile(tool.spec().input_schema())
324                .map_err(|source| ToolRegistryError::InvalidToolInputSchema {
325                name: name.clone(),
326                message: source.to_string(),
327            })?;
328            let entry = RegisteredToolEntry {
329                tool,
330                input_validator,
331            };
332            if registry.insert(name.clone(), entry).is_some() {
333                return Err(ToolRegistryError::DuplicateName { name });
334            }
335            order.push(name);
336        }
337
338        Ok(Self {
339            tools: registry,
340            order,
341        })
342    }
343
344    pub(crate) fn tool_specs(&self) -> Vec<ToolSpec> {
345        self.order
346            .iter()
347            .filter_map(|name| self.tools.get(name))
348            .map(|entry| entry.tool.spec().clone())
349            .collect()
350    }
351
352    pub(crate) fn external_tool_catalog(
353        &self,
354    ) -> Result<merry_core::SessionToolCatalog, merry_core::CoreError> {
355        merry_core::SessionToolCatalog::new(
356            self.order
357                .iter()
358                .filter_map(|name| {
359                    let tool = &self.tools.get(name)?.tool;
360                    Some(merry_core::SessionToolCatalogEntry::new(
361                        tool.spec().clone(),
362                        tool.external_binding()?.clone(),
363                    ))
364                })
365                .collect(),
366        )
367    }
368
369    pub(crate) fn registered_tool(&self, name: &ToolName) -> Option<&RegisteredTool> {
370        self.tools.get(name).map(|entry| &entry.tool)
371    }
372
373    pub(crate) fn validate_tool_input(
374        &self,
375        call: &PendingToolCall,
376    ) -> Option<Result<(), ToolInputValidationError>> {
377        self.tools
378            .get(call.name())
379            .map(|entry| entry.input_validator.validate_call(call))
380    }
381
382    pub(crate) fn first_bridge_tool_name(&self) -> Option<&ToolName> {
383        self.tools
384            .iter()
385            .find_map(|(name, entry)| (entry.tool.runner() == ToolRunner::Bridge).then_some(name))
386    }
387}
388
389#[derive(Debug, Clone, PartialEq, Eq)]
390pub(crate) enum ToolRegistryError {
391    DuplicateName { name: ToolName },
392    ReservedName { name: ToolName },
393    InvalidToolInputSchema { name: ToolName, message: String },
394}