Skip to main content

tinyharness_lib/tools/
mod.rs

1pub mod auto_compact;
2pub mod edit;
3pub mod glob;
4pub mod grep;
5pub mod invoke_skill;
6pub mod ls;
7pub mod question;
8pub mod read;
9pub mod run;
10pub mod screenshot;
11pub mod switch_mode;
12pub mod tool;
13pub mod web_search;
14pub mod write;
15
16use crate::mode::AgentMode;
17use crate::provider::ToolDefinition;
18use crate::sandbox::Sandbox;
19use crate::tools::tool::{Tool, ToolCategory};
20
21/// Events emitted by signal-category tools that the caller must interpret.
22/// These tools return a result string, but the caller should parse these
23/// into structured events for proper handling (e.g., prompting the user,
24/// switching mode, triggering compaction).
25#[derive(Debug, Clone)]
26pub enum SignalEvent {
27    /// The model requests a mode switch.
28    SwitchMode { mode: AgentMode },
29    /// The model asks the user a question with options.
30    Question {
31        question: String,
32        answers: Vec<String>,
33    },
34    /// The model requests conversation compaction.
35    AutoCompact { focus: String },
36    /// The model requests invocation of a skill by name.
37    InvokeSkill { skill_name: String },
38}
39
40/// Controls which optional tools are advertised to the model.
41///
42/// Tools disabled here are filtered out of [`ToolManager::tools_for_mode`],
43/// so the model never sees them and cannot call them. All flags default to
44/// `true` — opt out explicitly.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct ToolAvailability {
47    /// Whether the model may request conversation compaction (`auto_compact`).
48    pub auto_compact: bool,
49    /// Whether the model may ask the user multiple-choice questions (`question`).
50    pub question: bool,
51}
52
53impl Default for ToolAvailability {
54    fn default() -> Self {
55        Self::all()
56    }
57}
58
59impl ToolAvailability {
60    /// Every optional tool available (the default).
61    pub fn all() -> Self {
62        ToolAvailability {
63            auto_compact: true,
64            question: true,
65        }
66    }
67
68    /// Whether the named tool is available under this configuration.
69    /// Tools not listed here are always available.
70    pub fn allows(&self, tool_name: &str) -> bool {
71        match tool_name {
72            "auto_compact" => self.auto_compact,
73            "question" => self.question,
74            _ => true,
75        }
76    }
77}
78
79#[derive(Default)]
80pub struct ToolManager {
81    tools: Vec<Tool>,
82    /// When set, path-based tools are confined to this sandbox root.
83    sandbox: Option<Sandbox>,
84}
85
86impl ToolManager {
87    pub fn new() -> Self {
88        Self::default()
89    }
90
91    /// Enable sandboxing: all path-based tools (`ls`, `read`, `write`,
92    /// `edit`, `grep`, `glob`) are confined to the sandbox root, and the
93    /// `run` tool's explicit `cwd` is checked against it.
94    pub fn set_sandbox(&mut self, sandbox: Sandbox) {
95        self.sandbox = Some(sandbox);
96    }
97
98    /// The active sandbox, if any.
99    pub fn sandbox(&self) -> Option<&Sandbox> {
100        self.sandbox.as_ref()
101    }
102
103    /// If a sandbox is active and this tool call would access a path outside
104    /// it, return the violation error message. Returns `None` if the call is
105    /// allowed (or no sandbox is active).
106    pub fn sandbox_check(&self, tool_name: &str, arguments: &serde_json::Value) -> Option<String> {
107        let sandbox = self.sandbox.as_ref()?;
108        check_tool_args_sandboxed(sandbox, tool_name, arguments)
109    }
110
111    /// Register all built-in tools.
112    pub fn register_defaults(&mut self) {
113        self.register_tool(crate::tools::auto_compact::auto_compact_tool_entry());
114        self.register_tool(crate::tools::ls::ls_tool_entry());
115        self.register_tool(crate::tools::read::read_tool_entry());
116        self.register_tool(crate::tools::write::write_tool_entry());
117        self.register_tool(crate::tools::edit::edit_tool_entry());
118        self.register_tool(crate::tools::grep::grep_tool_entry());
119        self.register_tool(crate::tools::run::run_tool_entry());
120        self.register_tool(crate::tools::glob::glob_tool_entry());
121        self.register_tool(crate::tools::web_search::web_search_tool_entry());
122        self.register_tool(crate::tools::web_search::web_fetch_tool_entry());
123        self.register_tool(crate::tools::switch_mode::switch_mode_tool_entry());
124        self.register_tool(crate::tools::question::question_tool_entry());
125        self.register_tool(crate::tools::invoke_skill::invoke_skill_tool_entry());
126        self.register_tool(crate::tools::screenshot::screenshot_tool_entry());
127    }
128
129    pub fn register_tool(&mut self, tool: Tool) {
130        self.tools.push(tool);
131    }
132
133    /// Register custom tools from [`crate::custom_tools::CustomToolManager`].
134    /// Tools whose names collide with built-in tools are silently skipped.
135    pub fn register_custom_tools(&mut self, tools: &[crate::custom_tools::CustomToolDefinition]) {
136        let existing: std::collections::HashSet<String> =
137            self.tools.iter().map(|t| t.name.clone()).collect();
138        for def in tools {
139            if existing.contains(&def.name) {
140                tracing::warn!(
141                    "Custom tool '{}' collides with an existing tool — skipping",
142                    def.name
143                );
144                continue;
145            }
146            match def.build_tool() {
147                Ok(tool) => self.register_tool(tool),
148                Err(e) => tracing::warn!("Failed to register custom tool '{}': {}", def.name, e),
149            }
150        }
151    }
152
153    /// Returns the tool definitions for all registered tools.
154    pub fn get_all_tool_definitions(&self) -> Vec<ToolDefinition> {
155        self.tools.iter().map(|t| t.to_definition()).collect()
156    }
157
158    /// Returns the tool definitions appropriate for the given agent mode.
159    ///
160    /// Tools disabled in `availability` (e.g. `auto_compact`, `question`) are
161    /// excluded, so the model never sees them.
162    pub fn tools_for_mode(
163        &self,
164        mode: AgentMode,
165        availability: ToolAvailability,
166    ) -> Vec<ToolDefinition> {
167        let is_available = |t: &&Tool| availability.allows(&t.name);
168        match mode {
169            AgentMode::Agent => self
170                .tools
171                .iter()
172                .filter(is_available)
173                .map(|t| t.to_definition())
174                .collect(),
175            AgentMode::Casual => self
176                .tools
177                .iter()
178                .filter(|t| is_available(t) && (t.name == "web_search" || t.name == "web_fetch"))
179                .map(|t| t.to_definition())
180                .collect(),
181            AgentMode::Planning => self
182                .tools
183                .iter()
184                .filter(|t| {
185                    is_available(t)
186                        && (t.category == ToolCategory::ReadOnly
187                            || t.category == ToolCategory::Signal)
188                })
189                .map(|t| t.to_definition())
190                .collect(),
191            AgentMode::Research => self
192                .tools
193                .iter()
194                .filter(|t| {
195                    is_available(t)
196                        && (t.category == ToolCategory::ReadOnly
197                            || t.category == ToolCategory::Signal)
198                })
199                .map(|t| t.to_definition())
200                .collect(),
201        }
202    }
203
204    /// Returns the category of a tool by name, or `None` if not found.
205    pub fn category_of(&self, tool_name: &str) -> Option<ToolCategory> {
206        self.tools
207            .iter()
208            .find(|t| t.name == tool_name)
209            .map(|t| t.category)
210    }
211
212    /// Returns `true` if the tool requires user approval before execution.
213    /// Destructive tools (write, edit, run) and signal tools (switch_mode,
214    /// question, auto_compact) require approval.
215    pub fn needs_approval(&self, tool_name: &str) -> bool {
216        self.category_of(tool_name)
217            .map(|c| c == ToolCategory::Destructive || c == ToolCategory::Signal)
218            .unwrap_or(false)
219    }
220
221    /// Returns `true` if the tool is a signal tool (switch_mode, question, auto_compact).
222    /// Signal tools are handled specially by the agent loop rather than executed generically.
223    pub fn is_signal_tool(&self, tool_name: &str) -> bool {
224        self.category_of(tool_name) == Some(ToolCategory::Signal)
225    }
226
227    /// Parse a signal tool's result string into a structured `SignalEvent`.
228    ///
229    /// Signal tools return plain strings, but the agent loop needs structured
230    /// data to dispatch them correctly. This method interprets the tool call
231    /// arguments (not the result string) to produce the appropriate event.
232    ///
233    /// Returns `None` if the tool is not a signal tool or the arguments are invalid.
234    pub fn parse_signal_event(
235        &self,
236        tool_name: &str,
237        arguments: &serde_json::Value,
238    ) -> Option<SignalEvent> {
239        match tool_name {
240            "switch_mode" => {
241                let mode_str = arguments.get("mode").and_then(|v| v.as_str()).unwrap_or("");
242                mode_str
243                    .parse::<AgentMode>()
244                    .ok()
245                    .map(|mode| SignalEvent::SwitchMode { mode })
246            }
247            "question" => {
248                let question = arguments
249                    .get("question")
250                    .and_then(|v| v.as_str())
251                    .unwrap_or("")
252                    .to_string();
253                let answers: Vec<String> = arguments
254                    .get("answers")
255                    .and_then(|v| v.as_array())
256                    .map(|arr| {
257                        arr.iter()
258                            .filter_map(|item| item.as_str().map(|s| s.to_string()))
259                            .collect()
260                    })
261                    .unwrap_or_default();
262                Some(SignalEvent::Question { question, answers })
263            }
264            "auto_compact" => {
265                let focus = arguments
266                    .get("focus")
267                    .and_then(|v| v.as_str())
268                    .unwrap_or("")
269                    .to_string();
270                Some(SignalEvent::AutoCompact { focus })
271            }
272            "invoke_skill" => {
273                let skill_name = arguments
274                    .get("skill_name")
275                    .and_then(|v| v.as_str())
276                    .unwrap_or("")
277                    .to_string();
278                if skill_name.is_empty() {
279                    None
280                } else {
281                    Some(SignalEvent::InvokeSkill { skill_name })
282                }
283            }
284            _ => None,
285        }
286    }
287
288    pub async fn execute_tool_call(
289        &self,
290        tool_name: &str,
291        arguments: &serde_json::Value,
292    ) -> String {
293        // Sandbox enforcement: reject any tool call that would touch a path
294        // outside the sandbox root. This happens before the tool handler runs,
295        // so it applies regardless of auto-accept mode.
296        if let Some(error) = self.sandbox_check(tool_name, arguments) {
297            return error;
298        }
299
300        if let Some(tool) = self.tools.iter().find(|t| t.name == tool_name) {
301            tool::execute_tool_call(tool, arguments).await
302        } else {
303            format!("Error: Tool '{}' not found", tool_name)
304        }
305    }
306}
307
308/// Enforce sandbox containment for a tool call's arguments.
309///
310/// Path-bearing tools (`ls`, `read`, `write`, `edit`, `grep`, `glob`) have
311/// their path/pattern arguments checked against the sandbox root. The `run`
312/// tool's explicit `cwd` (if any) is also checked; arbitrary command content
313/// cannot be statically sandboxed, but shell commands inherit the sandboxed
314/// process's CWD for relative paths, and the confirmation layer still applies.
315///
316/// Returns `Some(error)` to block the call, or `None` to allow it.
317fn check_tool_args_sandboxed(
318    sandbox: &Sandbox,
319    tool_name: &str,
320    arguments: &serde_json::Value,
321) -> Option<String> {
322    let arg_str = |name: &str| -> Option<String> {
323        arguments
324            .get(name)
325            .and_then(|v| v.as_str())
326            .map(|s| s.to_string())
327    };
328
329    match tool_name {
330        // Tools with a required "path" argument
331        "ls" | "read" | "write" | "edit" => {
332            let path = arg_str("path").unwrap_or_default();
333            sandbox.resolve_contained(&path).err()
334        }
335        // grep: optional "path" directory argument (defaults to ".")
336        "grep" => {
337            let path = arg_str("path").unwrap_or_else(|| ".".to_string());
338            sandbox.resolve_contained(&path).err()
339        }
340        // glob: the static prefix of the pattern must be inside the sandbox
341        "glob" => {
342            let pattern = arg_str("pattern").unwrap_or_default();
343            sandbox.check_glob_pattern(&pattern).err()
344        }
345        // run: only the explicit "cwd" can be checked statically
346        "run" => match arg_str("cwd") {
347            Some(cwd) if !cwd.trim().is_empty() => sandbox.resolve_contained(&cwd).err(),
348            _ => None,
349        },
350        // All other tools (web_search, web_fetch, signal tools, custom tools
351        // without a known path arg) are not subject to path containment.
352        _ => None,
353    }
354}
355
356#[cfg(all(test, target_os = "linux"))]
357mod tests {
358    use super::*;
359    use crate::sandbox::Sandbox;
360
361    fn sandboxed_manager(root: &std::path::Path) -> ToolManager {
362        let mut manager = ToolManager::new();
363        manager.register_defaults();
364        manager.set_sandbox(Sandbox::new(root).unwrap());
365        manager
366    }
367
368    #[tokio::test]
369    async fn sandbox_blocks_read_outside_root() {
370        let tmp = tempfile::tempdir().unwrap();
371        let manager = sandboxed_manager(tmp.path());
372        let result = manager
373            .execute_tool_call("read", &serde_json::json!({"path": "/etc/passwd"}))
374            .await;
375        assert!(
376            result.starts_with("Error: Sandbox violation"),
377            "result was: {result}"
378        );
379    }
380
381    #[tokio::test]
382    async fn sandbox_blocks_write_outside_root() {
383        let tmp = tempfile::tempdir().unwrap();
384        let manager = sandboxed_manager(tmp.path());
385        let target = tmp.path().join("../escape.txt");
386        let result = manager
387            .execute_tool_call(
388                "write",
389                &serde_json::json!({"path": target.to_str().unwrap(), "content": "x"}),
390            )
391            .await;
392        assert!(
393            result.starts_with("Error: Sandbox violation"),
394            "result was: {result}"
395        );
396        // Verify the file was NOT created
397        assert!(!target.canonicalize().map(|p| p.exists()).unwrap_or(false));
398    }
399
400    #[tokio::test]
401    async fn sandbox_allows_write_inside_root() {
402        let tmp = tempfile::tempdir().unwrap();
403        let manager = sandboxed_manager(tmp.path());
404        let target = tmp.path().join("ok.txt");
405        let result = manager
406            .execute_tool_call(
407                "write",
408                &serde_json::json!({"path": target.to_str().unwrap(), "content": "hello"}),
409            )
410            .await;
411        assert!(result.starts_with("Wrote"), "result was: {result}");
412        assert_eq!(std::fs::read_to_string(&target).unwrap(), "hello");
413    }
414
415    #[tokio::test]
416    async fn sandbox_blocks_ls_outside_root() {
417        let tmp = tempfile::tempdir().unwrap();
418        let manager = sandboxed_manager(tmp.path());
419        let result = manager
420            .execute_tool_call("ls", &serde_json::json!({"path": "/"}))
421            .await;
422        assert!(
423            result.starts_with("Error: Sandbox violation"),
424            "result was: {result}"
425        );
426    }
427
428    #[tokio::test]
429    async fn sandbox_blocks_grep_outside_root() {
430        let tmp = tempfile::tempdir().unwrap();
431        let manager = sandboxed_manager(tmp.path());
432        let result = manager
433            .execute_tool_call("grep", &serde_json::json!({"pattern": "x", "path": "/tmp"}))
434            .await;
435        assert!(
436            result.starts_with("Error: Sandbox violation"),
437            "result was: {result}"
438        );
439    }
440
441    #[tokio::test]
442    async fn sandbox_blocks_glob_outside_root() {
443        let tmp = tempfile::tempdir().unwrap();
444        let manager = sandboxed_manager(tmp.path());
445        let result = manager
446            .execute_tool_call("glob", &serde_json::json!({"pattern": "/etc/**/*"}))
447            .await;
448        assert!(
449            result.starts_with("Error: Sandbox violation"),
450            "result was: {result}"
451        );
452    }
453
454    #[tokio::test]
455    async fn sandbox_allows_relative_glob() {
456        let tmp = tempfile::tempdir().unwrap();
457        std::fs::write(tmp.path().join("a.rs"), "fn main() {}").unwrap();
458        let manager = sandboxed_manager(tmp.path());
459        let result = manager
460            .execute_tool_call("glob", &serde_json::json!({"pattern": "**/*.rs"}))
461            .await;
462        assert!(result.contains("a.rs"), "result was: {result}");
463    }
464
465    #[tokio::test]
466    async fn sandbox_blocks_run_with_outside_cwd() {
467        let tmp = tempfile::tempdir().unwrap();
468        let manager = sandboxed_manager(tmp.path());
469        let result = manager
470            .execute_tool_call("run", &serde_json::json!({"command": "pwd", "cwd": "/"}))
471            .await;
472        assert!(
473            result.starts_with("Error: Sandbox violation"),
474            "result was: {result}"
475        );
476    }
477
478    #[tokio::test]
479    async fn sandbox_allows_run_without_cwd() {
480        let tmp = tempfile::tempdir().unwrap();
481        let manager = sandboxed_manager(tmp.path());
482        let result = manager
483            .execute_tool_call("run", &serde_json::json!({"command": "echo hi"}))
484            .await;
485        assert!(result.contains("hi"), "result was: {result}");
486    }
487
488    #[tokio::test]
489    async fn sandbox_does_not_affect_non_path_tools() {
490        let tmp = tempfile::tempdir().unwrap();
491        let manager = sandboxed_manager(tmp.path());
492        // screenshot tool has no path arg — should not be blocked
493        let result = manager
494            .execute_tool_call("screenshot", &serde_json::json!({"description": "test"}))
495            .await;
496        assert!(
497            !result.starts_with("Error: Sandbox violation"),
498            "result was: {result}"
499        );
500    }
501
502    #[tokio::test]
503    async fn no_sandbox_allows_everything() {
504        let tmp = tempfile::tempdir().unwrap();
505        let mut manager = ToolManager::new();
506        manager.register_defaults();
507        // Without sandbox, reading outside CWD works
508        let result = manager
509            .execute_tool_call(
510                "ls",
511                &serde_json::json!({"path": tmp.path().to_str().unwrap()}),
512            )
513            .await;
514        assert!(
515            !result.contains("Sandbox violation"),
516            "result was: {result}"
517        );
518    }
519}