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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum ToolRunner {
15 Runtime,
17 Bridge,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ToolConcurrency {
24 ParallelSafe,
26 Exclusive,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub(crate) enum PlanIntrinsicTool {
33 EnterPlanMode,
34 WritePlan,
35 ReadPlan,
36 ExitPlanMode,
37 UpdateTodos,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub(crate) enum RuntimeIntrinsicTool {
46 Plan(PlanIntrinsicTool),
47 RequestPermissions,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub(crate) enum ToolActionProposalMode {
53 Disabled,
55 Enabled,
57 LowRiskWorkspacePatch,
60}
61
62#[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 #[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 #[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 #[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 #[must_use]
137 pub fn external_binding(&self) -> Option<&merry_core::ExternalToolBinding> {
138 self.external_binding.as_ref()
139 }
140
141 #[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 #[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 #[must_use]
170 pub fn with_permissioned_network_lane(mut self) -> Self {
171 self.permissioned_network_lane = true;
172 self
173 }
174
175 #[must_use]
180 pub fn with_parallel_safe_execution(mut self) -> Self {
181 self.concurrency = ToolConcurrency::ParallelSafe;
182 self
183 }
184
185 #[must_use]
191 pub fn read_only(spec: ToolSpec, executor: Arc<dyn ToolExecutor>) -> Self {
192 Self::new(spec, executor, ToolActionKind::ReadOnly)
193 }
194
195 #[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 #[must_use]
213 pub fn spec(&self) -> &ToolSpec {
214 &self.spec
215 }
216
217 #[must_use]
219 pub fn action_kind(&self) -> ToolActionKind {
220 self.action_kind
221 }
222
223 #[must_use]
225 pub fn runner(&self) -> ToolRunner {
226 self.runner
227 }
228
229 #[must_use]
231 pub fn concurrency(&self) -> ToolConcurrency {
232 self.concurrency
233 }
234
235 #[must_use]
237 pub const fn proposals_enabled(&self) -> bool {
238 !matches!(self.proposal_mode, ToolActionProposalMode::Disabled)
239 }
240
241 #[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 #[must_use]
252 pub const fn permissioned_network_lane(&self) -> bool {
253 self.permissioned_network_lane
254 }
255
256 #[must_use]
258 pub(crate) const fn proposal_mode(&self) -> ToolActionProposalMode {
259 self.proposal_mode
260 }
261
262 #[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}