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(&self, _callback: crate::tools::browse::BrowseProgressCallback) {}
236
237    /// Custom rendering for tool call (TUI visualization).
238    /// Return None to use the default tool_renderer.rs formatter.
239    fn render_call(&self, _params: &serde_json::Value) -> Option<RenderOutput> {
240        None
241    }
242
243    /// Custom rendering for tool result (TUI visualization).
244    /// Return None to use the default tool_renderer.rs formatter.
245    fn render_result(&self, _result: &AgentToolResult) -> Option<RenderOutput> {
246        None
247    }
248
249    /// Execution mode for parallel safety.
250    /// Defaults to ParallelSafe. Override for file-mutating or sequential tools.
251    fn execution_mode(&self) -> ToolExecutionMode {
252        ToolExecutionMode::ParallelSafe
253    }
254
255    /// Return the current active tab ID, if this tool manages browser tabs.
256    /// Defaults to `None`. Browser tools override this to return the tab ID
257    /// of the currently-open tab during execution, so the agent loop can
258    /// populate `ToolExecutionUpdate.tab_id`.
259    fn current_tab_id(&self) -> Option<uuid::Uuid> {
260        None
261    }
262
263    /// Receive a shared slot where the tool can write the current tab ID.
264    /// The agent loop creates the slot and passes it before `on_progress`;
265    /// the tool writes `Some(tab_id)` when it opens a tab and `None` when
266    /// it closes it. Defaults to a no-op — only tab-aware tools override.
267    fn set_tab_id_slot(&self, _slot: Arc<parking_lot::Mutex<Option<uuid::Uuid>>>) {}
268
269    /// Convert to ToolDefinition
270    fn to_definition(&self) -> ToolDefinition {
271        ToolDefinition {
272            name: self.name().to_string(),
273            description: self.description().to_string(),
274            input_schema: serde_json::from_value(self.parameters_schema()).unwrap_or_default(),
275        }
276    }
277}
278
279// Built-in tools
280/// Bash shell execution tool.
281pub mod bash;
282/// Browser tools (engine abstraction always compiled).
283pub mod browse;
284/// Context7 documentation tools.
285pub mod context7;
286/// In-place file edit tool.
287pub mod edit;
288/// Diff-based edit helpers.
289pub mod edit_diff;
290/// Serialised file-mutation queue.
291pub mod file_mutation_queue;
292/// File-fsystem find tool.
293pub mod find;
294/// Image generation tool (OpenRouter API).
295pub mod generate_image;
296/// GitHub integration tool (gh CLI-based).
297pub mod github;
298/// GitHub repository search tool (legacy REST API).
299pub mod github_search;
300/// Content search (grep) tool.
301pub mod grep;
302/// Shared HTTP client singleton.
303pub mod http_client;
304/// Directory listing tool.
305pub mod ls;
306/// Path security (traversal protection).
307pub mod path_security;
308/// Path manipulation utilities.
309pub mod path_utils;
310/// Questionnaire tool — interactive multi-question TUI overlay.
311pub mod questionnaire;
312/// File reading tool.
313pub mod read;
314/// Rendering utilities for tool output.
315pub mod render_utils;
316/// Search result cache and get_search_results tool.
317pub mod search_cache;
318/// Sub-agent delegation tool.
319pub mod subagent;
320/// Tool definition wrapper helpers.
321pub mod tool_definition_wrapper;
322/// Output truncation helpers.
323pub mod truncate;
324/// Multi-engine web search tool (oxibrowser search module).
325pub mod web_search;
326/// File writing tool.
327pub mod write;
328
329// Re-export for convenience
330pub use bash::BashTool;
331pub use edit::EditTool;
332pub use find::FindTool;
333pub use grep::GrepTool;
334pub use ls::LsTool;
335pub use read::ReadTool;
336// pub use search_cache;
337
338pub use crate::mcp::McpTool;
339pub use context7::{Context7QueryDocsTool, Context7ResolveLibraryIdTool};
340pub use questionnaire::{QuestionnaireBridge, QuestionnaireTool};
341pub use subagent::SubagentTool;
342pub use write::WriteTool;
343
344/// Tool registry for managing available tools
345#[derive(Clone)]
346pub struct ToolRegistry {
347    tools: Arc<parking_lot::RwLock<std::collections::HashMap<String, Arc<dyn AgentTool>>>>,
348}
349
350impl Default for ToolRegistry {
351    fn default() -> Self {
352        Self::new()
353    }
354}
355
356impl ToolRegistry {
357    /// Creates an empty tool registry.
358    pub fn new() -> Self {
359        Self {
360            tools: Arc::new(parking_lot::RwLock::new(std::collections::HashMap::new())),
361        }
362    }
363
364    /// Register a tool
365    pub fn register(&self, tool: impl AgentTool + 'static) {
366        let name = tool.name().to_string();
367        self.tools.write().insert(name, Arc::new(tool));
368    }
369
370    /// Register a tool that is already wrapped in an `Arc`.
371    /// This is the primary path for extensions that produce `Arc<dyn AgentTool>`.
372    pub fn register_arc(&self, tool: Arc<dyn AgentTool>) {
373        let name = tool.name().to_string();
374        self.tools.write().insert(name, tool);
375    }
376
377    /// Get a tool by name
378    pub fn get(&self, name: &str) -> Option<Arc<dyn AgentTool>> {
379        self.tools.read().get(name).cloned()
380    }
381
382    /// Unregister a tool by name.
383    /// Returns `true` if the tool was present and removed.
384    pub fn unregister(&self, name: &str) -> bool {
385        self.tools.write().remove(name).is_some()
386    }
387
388    /// List all registered tool names
389    pub fn names(&self) -> Vec<String> {
390        self.tools.read().keys().cloned().collect()
391    }
392
393    /// Get all tool definitions
394    pub fn definitions(&self) -> Vec<ToolDefinition> {
395        self.tools
396            .read()
397            .values()
398            .map(|t| t.to_definition())
399            .collect()
400    }
401
402    /// Get all tools as a slice
403    pub fn get_tools(&self) -> Vec<Arc<dyn AgentTool>> {
404        self.tools.read().values().cloned().collect()
405    }
406
407    /// Check whether all tools in `required` are registered.
408    ///
409    /// Useful for validating program/module dependencies before execution.
410    ///
411    /// # Example
412    ///
413    /// ```
414    /// use oxi_agent::ToolRegistry;
415    /// let registry = ToolRegistry::new();
416    /// assert!(!registry.has_all(&["read", "write"]));
417    /// ```
418    pub fn has_all(&self, required: &[&str]) -> bool {
419        let tools = self.tools.read();
420        required.iter().all(|name| tools.contains_key(*name))
421    }
422
423    /// Return the subset of `required` tool names that are **not** registered.
424    ///
425    /// # Example
426    ///
427    /// ```
428    /// use oxi_agent::ToolRegistry;
429    /// let registry = ToolRegistry::new();
430    /// let missing = registry.missing(&["read", "exec", "nonexistent"]);
431    /// assert_eq!(missing, vec!["read", "exec", "nonexistent"]);
432    /// ```
433    pub fn missing<'a>(&self, required: &[&'a str]) -> Vec<&'a str> {
434        let tools = self.tools.read();
435        required
436            .iter()
437            .filter(|name| !tools.contains_key(**name))
438            .copied()
439            .collect()
440    }
441
442    /// Create a registry with all built-in tools
443    ///
444    /// # Examples
445    ///
446    /// ```
447    /// use oxi_agent::ToolRegistry;
448    /// let registry = ToolRegistry::with_builtins();
449    /// let tools = registry.names();
450    /// assert!(tools.contains(&"read".to_string()));
451    /// assert!(tools.contains(&"write".to_string()));
452    /// assert!(tools.contains(&"bash".to_string()));
453    /// ```
454    pub fn with_builtins() -> Self {
455        Self::with_builtins_cwd(PathBuf::from("."), &[])
456    }
457
458    /// Create a registry with all built-in tools, using the given cwd.
459    ///
460    /// Pass `disabled_tools` to selectively disable built-in tools
461    /// (e.g. `["web_search", "github_search"]` for a minimal setup).
462    pub fn with_builtins_cwd(cwd: PathBuf, disabled_tools: &[String]) -> Self {
463        let registry = Self::new();
464        let disabled: std::collections::HashSet<&str> =
465            disabled_tools.iter().map(|s| s.as_str()).collect();
466
467        // Helper to create shared cache on demand
468        let cache_once: std::cell::OnceCell<Arc<search_cache::SearchCache>> =
469            std::cell::OnceCell::new();
470
471        // MCP: use OnceCell to avoid re-creating McpManager on repeated calls
472        let mcp_once: std::cell::OnceCell<Arc<crate::mcp::McpManager>> = std::cell::OnceCell::new();
473        let mcp_manager = mcp_once
474            .get_or_init(|| Arc::new(crate::mcp::McpManager::new()))
475            .clone();
476
477        // Register all builtin tools — essential ones ignore disabled list
478        let mut all_tools: Vec<Box<dyn AgentTool>> = vec![
479            Box::new(ReadTool::with_cwd(cwd.clone())),
480            Box::new(WriteTool::with_cwd(cwd.clone())),
481            Box::new(EditTool::with_cwd(cwd.clone())),
482            Box::new(BashTool::with_cwd(cwd.clone())),
483            Box::new(GrepTool::with_cwd(cwd.clone())),
484            Box::new(FindTool::with_cwd(cwd.clone())),
485            Box::new(LsTool::with_cwd(cwd.clone())),
486            Box::new(web_search::WebSearchTool::new(
487                cache_once
488                    .get_or_init(|| Arc::new(search_cache::SearchCache::new()))
489                    .clone(),
490            )),
491            Box::new(search_cache::GetSearchResultsTool::new(
492                cache_once
493                    .get_or_init(|| Arc::new(search_cache::SearchCache::new()))
494                    .clone(),
495            )),
496            Box::new(github::GitHubTool::new(
497                cache_once
498                    .get_or_init(|| Arc::new(search_cache::SearchCache::new()))
499                    .clone(),
500            )),
501            Box::new(SubagentTool::with_cwd(cwd)),
502        ];
503
504        all_tools.push(Box::new(crate::mcp::McpTool::new(mcp_manager)));
505        all_tools.push(Box::new(context7::Context7ResolveLibraryIdTool::new()));
506        all_tools.push(Box::new(context7::Context7QueryDocsTool::new()));
507        all_tools.push(Box::new(generate_image::GenerateImageTool::new()));
508
509        for tool in all_tools {
510            if tool.essential() || !disabled.contains(tool.name()) {
511                // web_search ↔ get_search_results coupling
512                if tool.name() == "get_search_results" && disabled.contains("web_search") {
513                    continue;
514                }
515                registry.register_arc(Arc::from(tool));
516            }
517        }
518
519        registry
520    }
521
522    /// Extend this registry with all tools from another registry.
523    ///
524    /// Useful for composing tool sets from multiple sources
525    /// (e.g., coding tools + kernel tools + browser tools).
526    ///
527    /// # Example
528    ///
529    /// ```ignore
530    /// let base = ToolRegistry::new();
531    /// base.extend_from(&other_registry);
532    /// ```
533    pub fn extend_from(&self, other: &ToolRegistry) {
534        for name in other.names() {
535            if let Some(tool) = other.get(&name) {
536                self.register_arc(tool);
537            }
538        }
539    }
540
541    /// Create registry with selected builtins only.
542    pub fn with_selected_tools(cwd: PathBuf, names: &[&str]) -> Self {
543        let full = Self::with_builtins_cwd(cwd, &[]);
544        let registry = Self::new();
545        let set: std::collections::HashSet<&str> = names.iter().copied().collect();
546        for name in full.names() {
547            if set.contains(name.as_str()) {
548                if let Some(tool) = full.get(&name) {
549                    registry.register_arc(tool);
550                }
551            }
552        }
553        registry
554    }
555}