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) intrinsic: Option<RuntimeIntrinsicTool>,
76 pub(super) runner: ToolRunner,
77 pub(super) concurrency: ToolConcurrency,
78}
79
80impl RegisteredTool {
81 #[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 #[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 #[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 #[must_use]
134 pub fn external_binding(&self) -> Option<&merry_core::ExternalToolBinding> {
135 self.external_binding.as_ref()
136 }
137
138 #[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 #[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 #[must_use]
167 pub fn with_parallel_safe_execution(mut self) -> Self {
168 self.concurrency = ToolConcurrency::ParallelSafe;
169 self
170 }
171
172 #[must_use]
178 pub fn read_only(spec: ToolSpec, executor: Arc<dyn ToolExecutor>) -> Self {
179 Self::new(spec, executor, ToolActionKind::ReadOnly)
180 }
181
182 #[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 #[must_use]
199 pub fn spec(&self) -> &ToolSpec {
200 &self.spec
201 }
202
203 #[must_use]
205 pub fn action_kind(&self) -> ToolActionKind {
206 self.action_kind
207 }
208
209 #[must_use]
211 pub fn runner(&self) -> ToolRunner {
212 self.runner
213 }
214
215 #[must_use]
217 pub fn concurrency(&self) -> ToolConcurrency {
218 self.concurrency
219 }
220
221 #[must_use]
223 pub const fn proposals_enabled(&self) -> bool {
224 !matches!(self.proposal_mode, ToolActionProposalMode::Disabled)
225 }
226
227 #[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 #[must_use]
238 pub(crate) const fn proposal_mode(&self) -> ToolActionProposalMode {
239 self.proposal_mode
240 }
241
242 #[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}