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) permissioned_network_lane: bool,
76    pub(super) intrinsic: Option<RuntimeIntrinsicTool>,
77    pub(super) runner: ToolRunner,
78    pub(super) concurrency: ToolConcurrency,
79}
80
81impl RegisteredTool {
82    /// Creates a registered tool with an explicit runtime-owned action category.
83    ///
84    /// The spec is provider-visible after adapter rendering, but the executor
85    /// remains a runtime-owned boundary. The action category stays inside
86    /// runtime and is not rendered into the provider-visible tool spec.
87    #[must_use]
88    pub fn new(
89        spec: ToolSpec,
90        executor: Arc<dyn ToolExecutor>,
91        action_kind: ToolActionKind,
92    ) -> Self {
93        Self {
94            spec,
95            external_binding: None,
96            executor,
97            action_kind,
98            proposal_mode: ToolActionProposalMode::Disabled,
99            permissioned_network_lane: false,
100            intrinsic: None,
101            runner: ToolRunner::Runtime,
102            concurrency: ToolConcurrency::Exclusive,
103        }
104    }
105
106    /// Creates a runtime-owned intrinsic control tool bound to its typed
107    /// dispatch target.
108    ///
109    /// Intrinsic tools always carry [`ToolActionKind::RuntimeControl`] and are
110    /// intercepted by runtime dispatch before the generic executor path.
111    #[must_use]
112    pub(crate) fn intrinsic(spec: ToolSpec, intrinsic: RuntimeIntrinsicTool) -> Self {
113        Self {
114            spec,
115            external_binding: None,
116            executor: Arc::new(IntrinsicToolExecutor),
117            action_kind: ToolActionKind::RuntimeControl,
118            proposal_mode: ToolActionProposalMode::Disabled,
119            permissioned_network_lane: false,
120            intrinsic: Some(intrinsic),
121            runner: ToolRunner::Runtime,
122            concurrency: ToolConcurrency::Exclusive,
123        }
124    }
125
126    /// Attaches a stable adapter binding for session catalog persistence.
127    ///
128    /// Binding metadata is never rendered into the model's tool definition.
129    #[must_use]
130    pub fn with_external_binding(mut self, binding: merry_core::ExternalToolBinding) -> Self {
131        self.external_binding = Some(binding);
132        self
133    }
134
135    /// Returns the adapter identity, if this tool belongs to an external catalog.
136    #[must_use]
137    pub fn external_binding(&self) -> Option<&merry_core::ExternalToolBinding> {
138        self.external_binding.as_ref()
139    }
140
141    /// Enables read-only proposal evidence for a mutating tool.
142    ///
143    /// Runtime calls [`ToolExecutor::propose`] only for registered tools that
144    /// explicitly opt in here. The hook is still skipped for read-only tools.
145    #[must_use]
146    pub fn with_action_proposal(mut self) -> Self {
147        if self.proposal_mode == ToolActionProposalMode::Disabled {
148            self.proposal_mode = ToolActionProposalMode::Enabled;
149        }
150        self
151    }
152
153    /// Opts a [`ToolActionKind::WorkspaceWrite`] tool into the low-risk
154    /// workspace patch lane when the runtime enables
155    /// [`crate::RuntimeBuilder::allow_low_risk_apply_patches`].
156    ///
157    /// Automatically enables read-only action proposals so callers cannot
158    /// misconfigure the patch lane without proposal preflight.
159    #[must_use]
160    pub fn with_low_risk_workspace_patch_lane(mut self) -> Self {
161        self.proposal_mode = ToolActionProposalMode::LowRiskWorkspacePatch;
162        self
163    }
164
165    /// Opts a [`ToolActionKind::Network`] tool into the unified runtime
166    /// network-admission lane (SSRF + [`crate::LivePolicyHandle`] +
167    /// domain-level permission review) when the runtime enables
168    /// [`crate::RuntimeBuilder::allow_permissioned_network_tools`].
169    #[must_use]
170    pub fn with_permissioned_network_lane(mut self) -> Self {
171        self.permissioned_network_lane = true;
172        self
173    }
174
175    /// Opts this tool into bounded concurrent execution within one model batch.
176    ///
177    /// Use this only when concurrent calls cannot race through writes,
178    /// processes, network access, permissions, or runtime-control state.
179    #[must_use]
180    pub fn with_parallel_safe_execution(mut self) -> Self {
181        self.concurrency = ToolConcurrency::ParallelSafe;
182        self
183    }
184
185    /// Creates a registered read-only tool.
186    ///
187    /// Use this only for tools that do not write workspace state or execute
188    /// commands. Network access is controlled by runtime profile, not by this
189    /// constructor.
190    #[must_use]
191    pub fn read_only(spec: ToolSpec, executor: Arc<dyn ToolExecutor>) -> Self {
192        Self::new(spec, executor, ToolActionKind::ReadOnly)
193    }
194
195    /// Creates a tool whose execution is delegated to an external SDK bridge.
196    #[must_use]
197    pub fn bridge(spec: ToolSpec) -> Self {
198        Self {
199            spec,
200            external_binding: None,
201            executor: Arc::new(BridgeExecutor),
202            action_kind: ToolActionKind::ReadOnly,
203            proposal_mode: ToolActionProposalMode::Disabled,
204            permissioned_network_lane: false,
205            intrinsic: None,
206            runner: ToolRunner::Bridge,
207            concurrency: ToolConcurrency::Exclusive,
208        }
209    }
210
211    /// Borrows the provider-visible tool specification.
212    #[must_use]
213    pub fn spec(&self) -> &ToolSpec {
214        &self.spec
215    }
216
217    /// Returns the runtime-owned action category for this tool.
218    #[must_use]
219    pub fn action_kind(&self) -> ToolActionKind {
220        self.action_kind
221    }
222
223    /// Returns where this tool is executed.
224    #[must_use]
225    pub fn runner(&self) -> ToolRunner {
226        self.runner
227    }
228
229    /// Returns the runtime execution policy for batched calls.
230    #[must_use]
231    pub fn concurrency(&self) -> ToolConcurrency {
232        self.concurrency
233    }
234
235    /// Returns whether this tool opted into action proposal evidence.
236    #[must_use]
237    pub const fn proposals_enabled(&self) -> bool {
238        !matches!(self.proposal_mode, ToolActionProposalMode::Disabled)
239    }
240
241    /// Returns whether this tool opted into the low-risk workspace patch lane.
242    #[must_use]
243    pub const fn low_risk_workspace_patch_lane(&self) -> bool {
244        matches!(
245            self.proposal_mode,
246            ToolActionProposalMode::LowRiskWorkspacePatch
247        )
248    }
249
250    /// Returns whether this tool opted into the unified runtime network-admission lane.
251    #[must_use]
252    pub const fn permissioned_network_lane(&self) -> bool {
253        self.permissioned_network_lane
254    }
255
256    /// Returns the typed proposal policy for this tool.
257    #[must_use]
258    pub(crate) const fn proposal_mode(&self) -> ToolActionProposalMode {
259        self.proposal_mode
260    }
261
262    /// Returns the typed runtime-intrinsic dispatch target, if any.
263    #[must_use]
264    pub(crate) const fn runtime_intrinsic(&self) -> Option<RuntimeIntrinsicTool> {
265        self.intrinsic
266    }
267
268    pub(crate) fn executor(&self) -> Arc<dyn ToolExecutor> {
269        Arc::clone(&self.executor)
270    }
271}
272
273struct IntrinsicToolExecutor;
274
275impl ToolExecutor for IntrinsicToolExecutor {
276    fn execute<'a>(
277        &'a self,
278        call: PendingToolCall,
279        _context: ToolExecutionContext,
280    ) -> ToolExecutorFuture<'a> {
281        Box::pin(async move {
282            Err(ToolExecutionError::infrastructure(format!(
283                "intrinsic runtime tool {} reached the generic executor",
284                call.name().as_str()
285            )))
286        })
287    }
288}
289
290pub(super) struct BridgeExecutor;
291
292impl ToolExecutor for BridgeExecutor {
293    fn execute<'a>(
294        &'a self,
295        call: PendingToolCall,
296        _context: ToolExecutionContext,
297    ) -> ToolExecutorFuture<'a> {
298        Box::pin(async move {
299            Err(ToolExecutionError::infrastructure(format!(
300                "bridge tool {} must be executed by a bridge runner",
301                call.name().as_str()
302            )))
303        })
304    }
305}
306
307impl std::fmt::Debug for RegisteredTool {
308    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
309        formatter
310            .debug_struct("RegisteredTool")
311            .field("spec", &self.spec)
312            .field("action_kind", &self.action_kind)
313            .field("proposal_mode", &self.proposal_mode)
314            .field("intrinsic", &self.intrinsic)
315            .field("runner", &self.runner)
316            .field("concurrency", &self.concurrency)
317            .finish_non_exhaustive()
318    }
319}
320
321#[derive(Debug, Clone, Default)]
322pub(crate) struct ToolRegistry {
323    pub(super) tools: BTreeMap<ToolName, RegisteredToolEntry>,
324    pub(super) order: Vec<ToolName>,
325}
326
327#[derive(Debug, Clone)]
328pub(super) struct RegisteredToolEntry {
329    pub(super) tool: RegisteredTool,
330    pub(super) input_validator: CompiledToolInputValidator,
331}
332
333impl ToolRegistry {
334    pub(crate) fn from_registered(tools: Vec<RegisteredTool>) -> Result<Self, ToolRegistryError> {
335        let mut registry = BTreeMap::new();
336        let mut order = Vec::with_capacity(tools.len());
337
338        for tool in tools {
339            let name = tool.spec().name().clone();
340            if name.as_str() == FINAL_OUTPUT_TOOL_NAME {
341                return Err(ToolRegistryError::ReservedName { name });
342            }
343            let input_validator = CompiledToolInputValidator::compile(tool.spec().input_schema())
344                .map_err(|source| ToolRegistryError::InvalidToolInputSchema {
345                name: name.clone(),
346                message: source.to_string(),
347            })?;
348            let entry = RegisteredToolEntry {
349                tool,
350                input_validator,
351            };
352            if registry.insert(name.clone(), entry).is_some() {
353                return Err(ToolRegistryError::DuplicateName { name });
354            }
355            order.push(name);
356        }
357
358        Ok(Self {
359            tools: registry,
360            order,
361        })
362    }
363
364    pub(crate) fn tool_specs(&self) -> Vec<ToolSpec> {
365        self.order
366            .iter()
367            .filter_map(|name| self.tools.get(name))
368            .map(|entry| entry.tool.spec().clone())
369            .collect()
370    }
371
372    pub(crate) fn external_tool_catalog(
373        &self,
374    ) -> Result<merry_core::SessionToolCatalog, merry_core::CoreError> {
375        merry_core::SessionToolCatalog::new(
376            self.order
377                .iter()
378                .filter_map(|name| {
379                    let tool = &self.tools.get(name)?.tool;
380                    Some(merry_core::SessionToolCatalogEntry::new(
381                        tool.spec().clone(),
382                        tool.external_binding()?.clone(),
383                    ))
384                })
385                .collect(),
386        )
387    }
388
389    pub(crate) fn registered_tool(&self, name: &ToolName) -> Option<&RegisteredTool> {
390        self.tools.get(name).map(|entry| &entry.tool)
391    }
392
393    pub(crate) fn validate_tool_input(
394        &self,
395        call: &PendingToolCall,
396    ) -> Option<Result<(), ToolInputValidationError>> {
397        self.tools
398            .get(call.name())
399            .map(|entry| entry.input_validator.validate_call(call))
400    }
401
402    pub(crate) fn first_bridge_tool_name(&self) -> Option<&ToolName> {
403        self.tools
404            .iter()
405            .find_map(|(name, entry)| (entry.tool.runner() == ToolRunner::Bridge).then_some(name))
406    }
407}
408
409#[derive(Debug, Clone, PartialEq, Eq)]
410pub(crate) enum ToolRegistryError {
411    DuplicateName { name: ToolName },
412    ReservedName { name: ToolName },
413    InvalidToolInputSchema { name: ToolName, message: String },
414}