Skip to main content

oxi_agent/
tools.rs

1#![allow(unused_doc_comments)]
2/// Agent tools system
3/// This module provides the tool abstraction layer and built-in tools.
4use crate::types::ToolDefinition;
5use async_trait::async_trait;
6use serde_json::Value;
7use std::fmt;
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10use tokio::sync::oneshot;
11
12/// Context passed to tools at execution time.
13///
14/// This allows tools to operate on a specific workspace without being
15/// rebuilt. When `root_dir` is `Some`, tools use it as their base directory.
16/// When `None`, tools should fall back to `workspace_dir`.
17#[derive(Debug, Clone)]
18pub struct ToolContext {
19    /// Primary workspace directory (used when root_dir is None).
20    pub workspace_dir: PathBuf,
21    /// Optional explicit root directory for file tools.
22    /// Takes priority over workspace_dir if present.
23    pub root_dir: Option<PathBuf>,
24    /// Session identifier for logging/tracing.
25    pub session_id: Option<String>,
26}
27
28impl ToolContext {
29    /// Create a new context with the given workspace.
30    pub fn new(workspace_dir: impl Into<PathBuf>) -> Self {
31        Self {
32            workspace_dir: workspace_dir.into(),
33            root_dir: None,
34            session_id: None,
35        }
36    }
37
38    /// Get the effective root directory.
39    /// Returns root_dir if set, otherwise workspace_dir.
40    pub fn root(&self) -> &Path {
41        self.root_dir.as_deref().unwrap_or(&self.workspace_dir)
42    }
43
44    /// Set a session ID.
45    pub fn with_session(mut self, session_id: impl Into<String>) -> Self {
46        self.session_id = Some(session_id.into());
47        self
48    }
49
50    /// Set an explicit root directory.
51    pub fn with_root(mut self, root_dir: impl Into<PathBuf>) -> Self {
52        self.root_dir = Some(root_dir.into());
53        self
54    }
55}
56
57impl Default for ToolContext {
58    fn default() -> Self {
59        Self {
60            workspace_dir: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
61            root_dir: None,
62            session_id: None,
63        }
64    }
65}
66
67/// Result type for tool execution
68pub type ToolError = String;
69
70/// Result of tool execution
71#[derive(Debug)]
72pub struct AgentToolResult {
73    /// pub.
74    pub success: bool,
75    /// pub.
76    pub output: String,
77    /// pub.
78    pub metadata: Option<serde_json::Value>,
79    /// Optional content blocks (e.g., image blocks) to include in the tool result message.
80    /// When present, these are used as the content of the ToolResultMessage instead of
81    /// wrapping `output` in a Text block.
82    pub content_blocks: Option<Vec<oxi_ai::ContentBlock>>,
83    /// When `true`, signals that the agent loop should terminate after this batch
84    /// of tool calls completes.  Defaults to `false` so that the loop continues
85    /// unless a tool explicitly opts-in to termination.
86    pub terminate: bool,
87}
88
89impl AgentToolResult {
90    /// Creates a successful tool result with the given output text.
91    pub fn success(output: impl Into<String>) -> Self {
92        Self {
93            success: true,
94            output: output.into(),
95            metadata: None,
96            content_blocks: None,
97            terminate: false,
98        }
99    }
100
101    /// Creates an error tool result with the given error message.
102    pub fn error(output: impl Into<String>) -> Self {
103        Self {
104            success: false,
105            output: output.into(),
106            metadata: None,
107            content_blocks: None,
108            terminate: false,
109        }
110    }
111
112    /// Attaches structured metadata (JSON) to this result.
113    pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
114        self.metadata = Some(metadata);
115        self
116    }
117
118    /// Attaches rich content blocks (images, code, etc.) to this result.
119    pub fn with_content_blocks(mut self, blocks: Vec<oxi_ai::ContentBlock>) -> Self {
120        self.content_blocks = Some(blocks);
121        self
122    }
123
124    /// Mark this result as requesting agent-loop termination.
125    pub fn with_terminate(mut self) -> Self {
126        self.terminate = true;
127        self
128    }
129}
130
131impl fmt::Display for AgentToolResult {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        write!(f, "{}", self.output)
134    }
135}
136
137/// Callback type for progress updates
138pub type ProgressCallback = Arc<dyn Fn(String) + Send + Sync>;
139
140/// Tool execution mode for parallel safety.
141#[derive(Debug, Clone)]
142pub enum ToolExecutionMode {
143    /// Safe to run in parallel with any other tool
144    ParallelSafe,
145    /// Must run sequentially — no parallel execution
146    SequentialOnly,
147    /// Mutates a specific file — file_mutation_queue serializes same-file access
148    MutatesFile(std::path::PathBuf),
149    /// Read-only — always parallel safe
150    ReadOnly,
151}
152
153/// Render output for TUI visualization.
154#[derive(Debug, Clone)]
155pub struct RenderOutput {
156    /// Rendered text content (markdown or plain)
157    pub content: String,
158    /// Whether to show collapsed by default
159    pub collapsed: bool,
160    /// Optional summary text for TUI footer
161    pub summary: Option<String>,
162}
163
164/// Core trait for all agent tools
165#[async_trait]
166pub trait AgentTool: Send + Sync {
167    /// Tool name (used in function calls)
168    fn name(&self) -> &str;
169
170    /// Human-readable label
171    fn label(&self) -> &str;
172
173    /// Description for the model
174    fn description(&self) -> &str;
175
176    /// JSON Schema for parameters
177    fn parameters_schema(&self) -> Value;
178
179    /// Whether this tool is essential (cannot be disabled).
180    /// Essential tools: read, write, edit, bash, grep, find, ls
181    /// Optional tools: web_search, github, subagent, etc.
182    fn essential(&self) -> bool {
183        false
184    }
185
186    /// Execute the tool with the given tool call ID and parameters.
187    ///
188    /// The `ctx` parameter provides workspace information. File tools should
189    /// use `ctx.root()` to get the effective directory. Custom tools can use
190    /// `ctx.workspace_dir` for workspace-relative operations.
191    ///
192    /// # Examples
193    ///
194    /// ```ignore
195    /// use oxi_agent::{AgentTool, AgentToolResult, ToolContext};
196    /// use serde_json::json;
197    /// use async_trait::async_trait;
198    ///
199    /// struct MyTool;
200    ///
201    /// #[async_trait]
202    /// impl AgentTool for MyTool {
203    ///     fn name(&self) -> &str { "my_tool" }
204    ///     fn label(&self) -> &str { "My Tool" }
205    ///     fn description(&self) -> &str { "A custom tool" }
206    ///     fn parameters_schema(&self) -> Value { json!({
207    ///         "type": "object",
208    ///         "properties": {}
209    ///     }) }
210    ///
211    ///     async fn execute(&self, tool_call_id: &str, params: Value, _signal: Option<oneshot::Receiver<()>>, ctx: &ToolContext) -> Result<AgentToolResult, String> {
212    ///         println!("Tool '{}' called with params: {:?}, workspace: {:?}", tool_call_id, params, ctx.workspace_dir);
213    ///         Ok(AgentToolResult::success("Done!"))
214    ///     }
215    /// }
216    /// ```
217    async fn execute(
218        &self,
219        tool_call_id: &str,
220        params: Value,
221        signal: Option<oneshot::Receiver<()>>,
222        ctx: &ToolContext,
223    ) -> Result<AgentToolResult, ToolError>;
224
225    /// Called with progress updates during execution.
226    /// Tools can override this to emit streaming updates.
227    fn on_progress(&self, _callback: ProgressCallback) {
228        // Default no-op
229    }
230
231    /// Structured browse progress callback for browser tool context enrichment.
232    /// Default implementation is no-op. Only browse tools override this to
233    /// register a callback that enriches `ToolCallContext` with structured
234    /// data from `BrowseProgress` events.
235    fn on_browse_progress(
236        &self,
237        _callback: crate::tools::browse::BrowseProgressCallback,
238    ) {
239    }
240
241    /// Custom rendering for tool call (TUI visualization).
242    /// Return None to use the default tool_renderer.rs formatter.
243    fn render_call(&self, _params: &serde_json::Value) -> Option<RenderOutput> {
244        None
245    }
246
247    /// Custom rendering for tool result (TUI visualization).
248    /// Return None to use the default tool_renderer.rs formatter.
249    fn render_result(&self, _result: &AgentToolResult) -> Option<RenderOutput> {
250        None
251    }
252
253    /// Execution mode for parallel safety.
254    /// Defaults to ParallelSafe. Override for file-mutating or sequential tools.
255    fn execution_mode(&self) -> ToolExecutionMode {
256        ToolExecutionMode::ParallelSafe
257    }
258
259    /// Return the current active tab ID, if this tool manages browser tabs.
260    /// Defaults to `None`. Browser tools override this to return the tab ID
261    /// of the currently-open tab during execution, so the agent loop can
262    /// populate `ToolExecutionUpdate.tab_id`.
263    fn current_tab_id(&self) -> Option<uuid::Uuid> {
264        None
265    }
266
267    /// Receive a shared slot where the tool can write the current tab ID.
268    /// The agent loop creates the slot and passes it before `on_progress`;
269    /// the tool writes `Some(tab_id)` when it opens a tab and `None` when
270    /// it closes it. Defaults to a no-op — only tab-aware tools override.
271    fn set_tab_id_slot(&self, _slot: Arc<parking_lot::Mutex<Option<uuid::Uuid>>>) {}
272
273    /// Convert to ToolDefinition
274    fn to_definition(&self) -> ToolDefinition {
275        ToolDefinition {
276            name: self.name().to_string(),
277            description: self.description().to_string(),
278            input_schema: serde_json::from_value(self.parameters_schema()).unwrap_or_default(),
279        }
280    }
281}
282
283// Built-in tools
284/// Bash shell execution tool.
285pub mod bash;
286/// Browser tools (engine abstraction always compiled).
287pub mod browse;
288/// Context7 documentation tools.
289pub mod context7;
290/// In-place file edit tool.
291pub mod edit;
292/// Diff-based edit helpers.
293pub mod edit_diff;
294/// Serialised file-mutation queue.
295pub mod file_mutation_queue;
296/// File-fsystem find tool.
297pub mod find;
298/// Image generation tool (OpenRouter API).
299pub mod generate_image;
300/// GitHub integration tool (gh CLI-based).
301pub mod github;
302/// GitHub repository search tool (legacy REST API).
303pub mod github_search;
304/// Content search (grep) tool.
305pub mod grep;
306/// Shared HTTP client singleton.
307pub mod http_client;
308/// Directory listing tool.
309pub mod ls;
310/// Path security (traversal protection).
311pub mod path_security;
312/// Path manipulation utilities.
313pub mod path_utils;
314/// Questionnaire tool — interactive multi-question TUI overlay.
315pub mod questionnaire;
316/// File reading tool.
317pub mod read;
318/// Rendering utilities for tool output.
319pub mod render_utils;
320/// Search result cache and get_search_results tool.
321pub mod search_cache;
322/// Sub-agent delegation tool.
323pub mod subagent;
324/// Tool definition wrapper helpers.
325pub mod tool_definition_wrapper;
326/// Output truncation helpers.
327pub mod truncate;
328/// Multi-engine web search tool (a3s-search library + DuckDuckGo fallback).
329pub mod web_search;
330/// File writing tool.
331pub mod write;
332
333// Re-export for convenience
334pub use bash::BashTool;
335pub use edit::EditTool;
336pub use find::FindTool;
337pub use grep::GrepTool;
338pub use ls::LsTool;
339pub use read::ReadTool;
340// pub use search_cache;
341
342pub use crate::mcp::McpTool;
343pub use context7::{Context7QueryDocsTool, Context7ResolveLibraryIdTool};
344pub use questionnaire::{QuestionnaireBridge, QuestionnaireTool};
345pub use subagent::SubagentTool;
346pub use write::WriteTool;
347
348/// Tool registry for managing available tools
349#[derive(Clone)]
350pub struct ToolRegistry {
351    tools: Arc<parking_lot::RwLock<std::collections::HashMap<String, Arc<dyn AgentTool>>>>,
352}
353
354impl Default for ToolRegistry {
355    fn default() -> Self {
356        Self::new()
357    }
358}
359
360impl ToolRegistry {
361    /// Creates an empty tool registry.
362    pub fn new() -> Self {
363        Self {
364            tools: Arc::new(parking_lot::RwLock::new(std::collections::HashMap::new())),
365        }
366    }
367
368    /// Register a tool
369    pub fn register(&self, tool: impl AgentTool + 'static) {
370        let name = tool.name().to_string();
371        self.tools.write().insert(name, Arc::new(tool));
372    }
373
374    /// Register a tool that is already wrapped in an `Arc`.
375    /// This is the primary path for extensions that produce `Arc<dyn AgentTool>`.
376    pub fn register_arc(&self, tool: Arc<dyn AgentTool>) {
377        let name = tool.name().to_string();
378        self.tools.write().insert(name, tool);
379    }
380
381    /// Get a tool by name
382    pub fn get(&self, name: &str) -> Option<Arc<dyn AgentTool>> {
383        self.tools.read().get(name).cloned()
384    }
385
386    /// Unregister a tool by name.
387    /// Returns `true` if the tool was present and removed.
388    pub fn unregister(&self, name: &str) -> bool {
389        self.tools.write().remove(name).is_some()
390    }
391
392    /// List all registered tool names
393    pub fn names(&self) -> Vec<String> {
394        self.tools.read().keys().cloned().collect()
395    }
396
397    /// Get all tool definitions
398    pub fn definitions(&self) -> Vec<ToolDefinition> {
399        self.tools
400            .read()
401            .values()
402            .map(|t| t.to_definition())
403            .collect()
404    }
405
406    /// Get all tools as a slice
407    pub fn get_tools(&self) -> Vec<Arc<dyn AgentTool>> {
408        self.tools.read().values().cloned().collect()
409    }
410
411    /// Check whether all tools in `required` are registered.
412    ///
413    /// Useful for validating program/module dependencies before execution.
414    ///
415    /// # Example
416    ///
417    /// ```
418    /// use oxi_agent::ToolRegistry;
419    /// let registry = ToolRegistry::new();
420    /// assert!(!registry.has_all(&["read", "write"]));
421    /// ```
422    pub fn has_all(&self, required: &[&str]) -> bool {
423        let tools = self.tools.read();
424        required.iter().all(|name| tools.contains_key(*name))
425    }
426
427    /// Return the subset of `required` tool names that are **not** registered.
428    ///
429    /// # Example
430    ///
431    /// ```
432    /// use oxi_agent::ToolRegistry;
433    /// let registry = ToolRegistry::new();
434    /// let missing = registry.missing(&["read", "exec", "nonexistent"]);
435    /// assert_eq!(missing, vec!["read", "exec", "nonexistent"]);
436    /// ```
437    pub fn missing<'a>(&self, required: &[&'a str]) -> Vec<&'a str> {
438        let tools = self.tools.read();
439        required
440            .iter()
441            .filter(|name| !tools.contains_key(**name))
442            .copied()
443            .collect()
444    }
445
446    /// Create a registry with all built-in tools
447    ///
448    /// # Examples
449    ///
450    /// ```
451    /// use oxi_agent::ToolRegistry;
452    /// let registry = ToolRegistry::with_builtins();
453    /// let tools = registry.names();
454    /// assert!(tools.contains(&"read".to_string()));
455    /// assert!(tools.contains(&"write".to_string()));
456    /// assert!(tools.contains(&"bash".to_string()));
457    /// ```
458    pub fn with_builtins() -> Self {
459        Self::with_builtins_cwd(PathBuf::from("."), &[])
460    }
461
462    /// Create a registry with all built-in tools, using the given cwd.
463    ///
464    /// Pass `disabled_tools` to selectively disable built-in tools
465    /// (e.g. `["web_search", "github_search"]` for a minimal setup).
466    pub fn with_builtins_cwd(cwd: PathBuf, disabled_tools: &[String]) -> Self {
467        let registry = Self::new();
468        let disabled: std::collections::HashSet<&str> =
469            disabled_tools.iter().map(|s| s.as_str()).collect();
470
471        // Helper to create shared cache on demand
472        let cache_once: std::cell::OnceCell<Arc<search_cache::SearchCache>> =
473            std::cell::OnceCell::new();
474
475        // MCP: use OnceCell to avoid re-creating McpManager on repeated calls
476        let mcp_once: std::cell::OnceCell<Arc<crate::mcp::McpManager>> = std::cell::OnceCell::new();
477        let mcp_manager = mcp_once
478            .get_or_init(|| Arc::new(crate::mcp::McpManager::new()))
479            .clone();
480
481        // Register all builtin tools — essential ones ignore disabled list
482        let mut all_tools: Vec<Box<dyn AgentTool>> = vec![
483            Box::new(ReadTool::with_cwd(cwd.clone())),
484            Box::new(WriteTool::with_cwd(cwd.clone())),
485            Box::new(EditTool::with_cwd(cwd.clone())),
486            Box::new(BashTool::with_cwd(cwd.clone())),
487            Box::new(GrepTool::with_cwd(cwd.clone())),
488            Box::new(FindTool::with_cwd(cwd.clone())),
489            Box::new(LsTool::with_cwd(cwd.clone())),
490            Box::new(web_search::WebSearchTool::new(
491                cache_once
492                    .get_or_init(|| Arc::new(search_cache::SearchCache::new()))
493                    .clone(),
494            )),
495            Box::new(search_cache::GetSearchResultsTool::new(
496                cache_once
497                    .get_or_init(|| Arc::new(search_cache::SearchCache::new()))
498                    .clone(),
499            )),
500            Box::new(github::GitHubTool::new(
501                cache_once
502                    .get_or_init(|| Arc::new(search_cache::SearchCache::new()))
503                    .clone(),
504            )),
505            Box::new(SubagentTool::with_cwd(cwd)),
506        ];
507
508        all_tools.push(Box::new(crate::mcp::McpTool::new(mcp_manager)));
509        all_tools.push(Box::new(context7::Context7ResolveLibraryIdTool::new()));
510        all_tools.push(Box::new(context7::Context7QueryDocsTool::new()));
511        all_tools.push(Box::new(generate_image::GenerateImageTool::new()));
512
513        for tool in all_tools {
514            if tool.essential() || !disabled.contains(tool.name()) {
515                // web_search ↔ get_search_results coupling
516                if tool.name() == "get_search_results" && disabled.contains("web_search") {
517                    continue;
518                }
519                registry.register_arc(Arc::from(tool));
520            }
521        }
522
523        registry
524    }
525
526    /// Extend this registry with all tools from another registry.
527    ///
528    /// Useful for composing tool sets from multiple sources
529    /// (e.g., coding tools + kernel tools + browser tools).
530    ///
531    /// # Example
532    ///
533    /// ```ignore
534    /// let base = ToolRegistry::new();
535    /// base.extend_from(&other_registry);
536    /// ```
537    pub fn extend_from(&self, other: &ToolRegistry) {
538        for name in other.names() {
539            if let Some(tool) = other.get(&name) {
540                self.register_arc(tool);
541            }
542        }
543    }
544
545    /// Create registry with selected builtins only.
546    pub fn with_selected_tools(cwd: PathBuf, names: &[&str]) -> Self {
547        let full = Self::with_builtins_cwd(cwd, &[]);
548        let registry = Self::new();
549        let set: std::collections::HashSet<&str> = names.iter().copied().collect();
550        for name in full.names() {
551            if set.contains(name.as_str()) {
552                if let Some(tool) = full.get(&name) {
553                    registry.register_arc(tool);
554                }
555            }
556        }
557        registry
558    }
559}