1use std::collections::BTreeMap;
2use std::fmt;
3use std::path::PathBuf;
4use std::sync::Arc;
5
6use serde::{Deserialize, Serialize};
7
8use crate::artifacts::ContextArtifactAccess;
9use crate::discovery::{
10 DiscoveryAuthState, DiscoveryCacheStatus, DiscoveryCatalogItem, DiscoveryCatalogSource,
11 DiscoveryItemStatus, DiscoveryLifecycleState, DiscoveryPromotionState, DiscoveryRedaction,
12 DiscoverySchemaFormat, DiscoverySchemaReference, DiscoverySourceKind,
13};
14use crate::events::{ThreadId, TurnId};
15use crate::extension::ToolProviderId;
16use crate::goals::ThreadGoalController;
17use crate::inference::ModelSchemaPolicy;
18use crate::policy_mode::PolicyMode;
19use crate::remote_runner::RemoteWorkspace;
20use crate::trace::SubagentTraceSink;
21use crate::{ToolSchemaPolicy, normalize_tool_schema};
22
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
24pub struct ToolSpec {
25 pub name: String,
26 pub description: String,
27 pub parameters: serde_json::Value,
28}
29
30impl ToolSpec {
31 pub fn freeform_input_field(&self) -> Option<&'static str> {
42 match self.name.as_str() {
43 "apply_patch" => Some("patch"),
44 _ => None,
45 }
46 }
47
48 pub fn normalized_for_model(&self, policy: ToolSchemaPolicy) -> Self {
49 let mut spec = self.clone();
50 spec.parameters = normalize_tool_schema(&spec.name, &spec.parameters, policy).schema;
51 spec
52 }
53
54 pub fn normalized_for_model_profile(&self, policy: ModelSchemaPolicy) -> Self {
55 match policy {
56 ModelSchemaPolicy::StandardRequiredFirst => {
57 self.normalized_for_model(ToolSchemaPolicy::warning())
58 }
59 ModelSchemaPolicy::RequiredFirstFlat => {
60 self.normalized_for_model(ToolSchemaPolicy::strict())
61 }
62 }
63 }
64
65 pub fn discovery_item(
66 &self,
67 provider_id: impl Into<String>,
68 schema_uri: impl Into<String>,
69 ) -> DiscoveryCatalogItem {
70 let provider_id = provider_id.into();
71 DiscoveryCatalogItem {
72 id: format!("tool:{provider_id}/{}", self.name),
73 group_id: format!("tools:{provider_id}"),
74 source: DiscoveryCatalogSource {
75 kind: DiscoverySourceKind::InternalTools,
76 id: provider_id.clone(),
77 display_name: provider_id,
78 origin: None,
79 auth_state: DiscoveryAuthState::NotRequired,
80 redaction: DiscoveryRedaction::none(),
81 },
82 name: self.name.clone(),
83 title: self.name.clone(),
84 description: Some(self.description.clone()),
85 status: DiscoveryItemStatus::Available,
86 lifecycle: DiscoveryLifecycleState::Discovered,
87 promotion: DiscoveryPromotionState::NotPromoted,
88 cache_status: DiscoveryCacheStatus::Cold,
89 schema: Some(DiscoverySchemaReference {
90 format: DiscoverySchemaFormat::JsonSchema,
91 uri: schema_uri.into(),
92 content_hash: None,
93 byte_count: None,
94 redaction: DiscoveryRedaction::none(),
95 }),
96 tags: vec!["tool".to_string()],
97 hints: Vec::new(),
98 redaction: DiscoveryRedaction::none(),
99 last_refreshed_at: None,
100 }
101 }
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
105pub enum ToolChoice {
106 Auto,
107 Any,
108 None,
109 Specific(String),
110}
111
112#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
113pub struct ToolCall {
114 pub id: String,
115 pub name: String,
116 pub arguments: serde_json::Value,
117 pub raw_arguments: String,
118 pub thread_id: ThreadId,
119 pub turn_id: TurnId,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
123pub struct ToolResult {
124 pub id: String,
125 pub name: String,
126 pub text: String,
127 pub data: serde_json::Value,
128 pub is_error: bool,
129}
130
131#[derive(Clone, Default)]
132pub struct ToolExecutionHandles {
133 pub workspace: Option<Arc<dyn ScopedWorkspaceHandle>>,
134 pub remote_workspace: Option<Arc<RemoteWorkspace>>,
140 pub process_runner: Option<Arc<dyn ScopedProcessRunner>>,
141 pub subagent_trace_sink: Option<Arc<dyn SubagentTraceSink>>,
142 pub context_artifacts: Option<Arc<dyn ContextArtifactAccess>>,
143 pub goal_controller: Option<Arc<dyn ThreadGoalController>>,
144 pub swarm_progress_sink: Option<Arc<dyn crate::subagents::AgentSwarmProgressSink>>,
146}
147
148impl fmt::Debug for ToolExecutionHandles {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 f.debug_struct("ToolExecutionHandles")
151 .field("workspace", &self.workspace.is_some())
152 .field("remote_workspace", &self.remote_workspace.is_some())
153 .field("process_runner", &self.process_runner.is_some())
154 .field("subagent_trace_sink", &self.subagent_trace_sink.is_some())
155 .field("context_artifacts", &self.context_artifacts.is_some())
156 .field("goal_controller", &self.goal_controller.is_some())
157 .field("swarm_progress_sink", &self.swarm_progress_sink.is_some())
158 .finish()
159 }
160}
161
162pub trait ScopedWorkspaceHandle: Send + Sync + 'static {
163 fn workspace_root(&self) -> Option<PathBuf>;
164}
165
166pub trait ScopedProcessRunner: Send + Sync + 'static {
167 fn runner_name(&self) -> &str;
168}
169
170#[derive(Debug, Clone)]
171pub struct LocalWorkspaceHandle {
172 root: PathBuf,
173}
174
175impl LocalWorkspaceHandle {
176 pub fn new(root: impl Into<PathBuf>) -> Self {
177 Self { root: root.into() }
178 }
179}
180
181impl ScopedWorkspaceHandle for LocalWorkspaceHandle {
182 fn workspace_root(&self) -> Option<PathBuf> {
183 Some(self.root.clone())
184 }
185}
186
187#[derive(Debug, Clone, Default)]
188pub struct LocalProcessRunnerHandle;
189
190impl ScopedProcessRunner for LocalProcessRunnerHandle {
191 fn runner_name(&self) -> &str {
192 "local-process"
193 }
194}
195
196#[derive(Debug, Clone)]
197pub struct ToolExecutionContext {
198 pub thread_id: ThreadId,
199 pub turn_id: TurnId,
200 pub effective_mode: PolicyMode,
201 pub command_shell: Option<String>,
202 pub deadline_remaining_seconds: Option<u64>,
203 pub handles: ToolExecutionHandles,
204}
205
206impl ToolExecutionContext {
207 pub fn new(
208 thread_id: impl Into<ThreadId>,
209 turn_id: impl Into<TurnId>,
210 effective_mode: PolicyMode,
211 ) -> Self {
212 Self {
213 thread_id: thread_id.into(),
214 turn_id: turn_id.into(),
215 effective_mode,
216 command_shell: None,
217 deadline_remaining_seconds: None,
218 handles: ToolExecutionHandles::default(),
219 }
220 }
221
222 pub fn with_command_shell(mut self, shell: impl Into<String>) -> Self {
223 let shell = shell.into();
224 if !shell.trim().is_empty() {
225 self.command_shell = Some(shell);
226 }
227 self
228 }
229
230 pub fn with_deadline_remaining_seconds(mut self, seconds: u64) -> Self {
231 self.deadline_remaining_seconds = Some(seconds);
232 self
233 }
234
235 pub fn with_workspace_handle(mut self, handle: Arc<dyn ScopedWorkspaceHandle>) -> Self {
236 self.handles.workspace = Some(handle);
237 self
238 }
239
240 pub fn with_remote_workspace(mut self, remote: Arc<RemoteWorkspace>) -> Self {
241 self.handles.remote_workspace = Some(remote);
242 self
243 }
244
245 pub fn with_process_runner(mut self, runner: Arc<dyn ScopedProcessRunner>) -> Self {
246 self.handles.process_runner = Some(runner);
247 self
248 }
249
250 pub fn with_subagent_trace_sink(mut self, sink: Arc<dyn SubagentTraceSink>) -> Self {
251 self.handles.subagent_trace_sink = Some(sink);
252 self
253 }
254
255 pub fn with_context_artifacts(mut self, store: Arc<dyn ContextArtifactAccess>) -> Self {
256 self.handles.context_artifacts = Some(store);
257 self
258 }
259
260 pub fn with_goal_controller(mut self, controller: Arc<dyn ThreadGoalController>) -> Self {
261 self.handles.goal_controller = Some(controller);
262 self
263 }
264
265 pub fn with_swarm_progress_sink(
266 mut self,
267 sink: Arc<dyn crate::subagents::AgentSwarmProgressSink>,
268 ) -> Self {
269 self.handles.swarm_progress_sink = Some(sink);
270 self
271 }
272
273 pub fn require_workspace(&self) -> anyhow::Result<Arc<dyn ScopedWorkspaceHandle>> {
274 self.handles
275 .workspace
276 .clone()
277 .ok_or_else(|| anyhow::anyhow!("workspace handle is not available"))
278 }
279
280 pub fn require_process_runner(&self) -> anyhow::Result<Arc<dyn ScopedProcessRunner>> {
281 self.handles
282 .process_runner
283 .clone()
284 .ok_or_else(|| anyhow::anyhow!("process runner is not available"))
285 }
286
287 pub fn require_context_artifacts(&self) -> anyhow::Result<Arc<dyn ContextArtifactAccess>> {
288 self.handles
289 .context_artifacts
290 .clone()
291 .ok_or_else(|| anyhow::anyhow!("context artifact store is not available"))
292 }
293
294 pub fn require_goal_controller(&self) -> anyhow::Result<Arc<dyn ThreadGoalController>> {
295 self.handles
296 .goal_controller
297 .clone()
298 .ok_or_else(|| anyhow::anyhow!("goal controller is not available"))
299 }
300}
301
302#[async_trait::async_trait]
303pub trait ToolExecutor: Send + Sync + 'static {
304 fn spec(&self) -> ToolSpec;
305
306 async fn execute(
307 &self,
308 ctx: ToolExecutionContext,
309 call: ToolCall,
310 ) -> anyhow::Result<ToolResult>;
311}
312
313#[derive(Default, Clone)]
314pub struct ToolRegistry {
315 tools: BTreeMap<String, Arc<dyn ToolExecutor>>,
316}
317
318impl ToolRegistry {
319 pub fn register(&mut self, tool: Arc<dyn ToolExecutor>) -> anyhow::Result<()> {
320 let name = tool.spec().name;
321 if self.tools.contains_key(&name) {
322 anyhow::bail!("tool {name:?} is already registered");
323 }
324 self.tools.insert(name, tool);
325 Ok(())
326 }
327
328 pub fn replace(&mut self, tool: Arc<dyn ToolExecutor>) {
332 self.tools.insert(tool.spec().name, tool);
333 }
334
335 pub fn specs(&self) -> Vec<ToolSpec> {
336 self.tools
337 .values()
338 .map(|tool| {
339 tool.spec()
340 .normalized_for_model(ToolSchemaPolicy::warning())
341 })
342 .collect()
343 }
344
345 pub fn specs_for_edit_tool(&self, edit_tool: Option<&str>) -> Vec<ToolSpec> {
346 self.specs_for_edit_tool_with_schema_policy(edit_tool, ModelSchemaPolicy::RequiredFirstFlat)
347 }
348
349 pub fn specs_for_edit_tool_with_schema_policy(
350 &self,
351 edit_tool: Option<&str>,
352 schema_policy: ModelSchemaPolicy,
353 ) -> Vec<ToolSpec> {
354 self.tools
355 .values()
356 .map(|tool| tool.spec())
357 .filter(|spec| keep_tool_for_edit_tool(&spec.name, edit_tool))
358 .map(|spec| spec.normalized_for_model_profile(schema_policy))
359 .collect()
360 }
361
362 pub fn get(&self, name: &str) -> Option<Arc<dyn ToolExecutor>> {
363 self.tools.get(name).cloned()
364 }
365
366 pub fn is_empty(&self) -> bool {
367 self.tools.is_empty()
368 }
369}
370
371fn keep_tool_for_edit_tool(name: &str, edit_tool: Option<&str>) -> bool {
372 match name {
373 "apply_patch" => true,
374 "write_file" | "edit" | "multi_edit" => !matches!(edit_tool, Some("patch")),
375 _ => true,
376 }
377}
378
379pub trait ToolContributor: Send + Sync + 'static {
380 fn id(&self) -> ToolProviderId;
381 fn contribute(&self, registry: &mut ToolRegistry) -> anyhow::Result<()>;
382}
383
384#[cfg(test)]
385mod tests {
386 use super::*;
387
388 #[test]
389 fn tool_spec_can_be_represented_as_discovery_item() {
390 let spec = ToolSpec {
391 name: "grep".to_string(),
392 description: "Search files".to_string(),
393 parameters: serde_json::json!({
394 "type": "object",
395 "properties": {
396 "query": { "type": "string" }
397 },
398 "required": ["query"]
399 }),
400 };
401
402 let item = spec.discovery_item(
403 "builtin-coding-tools",
404 "discovery/tools/builtin-coding-tools/grep.schema.json",
405 );
406 assert_eq!(item.id, "tool:builtin-coding-tools/grep");
407 assert_eq!(item.group_id, "tools:builtin-coding-tools");
408 assert_eq!(item.source.kind, DiscoverySourceKind::InternalTools);
409 assert_eq!(item.source.auth_state, DiscoveryAuthState::NotRequired);
410 assert_eq!(item.status, DiscoveryItemStatus::Available);
411 assert_eq!(item.lifecycle, DiscoveryLifecycleState::Discovered);
412 assert_eq!(
413 item.schema.as_ref().map(|schema| schema.format.clone()),
414 Some(DiscoverySchemaFormat::JsonSchema)
415 );
416 }
417
418 #[test]
419 fn apply_patch_is_kept_for_all_edit_tool_profiles() {
420 assert!(keep_tool_for_edit_tool("apply_patch", None));
421 assert!(keep_tool_for_edit_tool("apply_patch", Some("edit")));
422 assert!(keep_tool_for_edit_tool("apply_patch", Some("patch")));
423
424 assert!(keep_tool_for_edit_tool("edit", None));
425 assert!(keep_tool_for_edit_tool("edit", Some("edit")));
426 assert!(!keep_tool_for_edit_tool("edit", Some("patch")));
427 assert!(!keep_tool_for_edit_tool("multi_edit", Some("patch")));
428 assert!(!keep_tool_for_edit_tool("write_file", Some("patch")));
429 }
430}