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::tools::tool::{Tool, ToolCategory};
19
20/// Events emitted by signal-category tools that the caller must interpret.
21/// These tools return a result string, but the caller should parse these
22/// into structured events for proper handling (e.g., prompting the user,
23/// switching mode, triggering compaction).
24#[derive(Debug, Clone)]
25pub enum SignalEvent {
26    /// The model requests a mode switch.
27    SwitchMode { mode: AgentMode },
28    /// The model asks the user a question with options.
29    Question {
30        question: String,
31        answers: Vec<String>,
32    },
33    /// The model requests conversation compaction.
34    AutoCompact { focus: String },
35    /// The model requests invocation of a skill by name.
36    InvokeSkill { skill_name: String },
37}
38
39#[derive(Default)]
40pub struct ToolManager {
41    tools: Vec<Tool>,
42}
43
44impl ToolManager {
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// Register all built-in tools.
50    pub fn register_defaults(&mut self) {
51        self.register_tool(crate::tools::auto_compact::auto_compact_tool_entry());
52        self.register_tool(crate::tools::ls::ls_tool_entry());
53        self.register_tool(crate::tools::read::read_tool_entry());
54        self.register_tool(crate::tools::write::write_tool_entry());
55        self.register_tool(crate::tools::edit::edit_tool_entry());
56        self.register_tool(crate::tools::grep::grep_tool_entry());
57        self.register_tool(crate::tools::run::run_tool_entry());
58        self.register_tool(crate::tools::glob::glob_tool_entry());
59        self.register_tool(crate::tools::web_search::web_search_tool_entry());
60        self.register_tool(crate::tools::web_search::web_fetch_tool_entry());
61        self.register_tool(crate::tools::switch_mode::switch_mode_tool_entry());
62        self.register_tool(crate::tools::question::question_tool_entry());
63        self.register_tool(crate::tools::invoke_skill::invoke_skill_tool_entry());
64        self.register_tool(crate::tools::screenshot::screenshot_tool_entry());
65    }
66
67    pub fn register_tool(&mut self, tool: Tool) {
68        self.tools.push(tool);
69    }
70
71    /// Returns the tool definitions for all registered tools.
72    pub fn get_all_tool_definitions(&self) -> Vec<ToolDefinition> {
73        self.tools.iter().map(|t| t.to_definition()).collect()
74    }
75
76    /// Returns the tool definitions appropriate for the given agent mode.
77    pub fn tools_for_mode(&self, mode: AgentMode) -> Vec<ToolDefinition> {
78        match mode {
79            AgentMode::Agent => self.get_all_tool_definitions(),
80            AgentMode::Casual => self
81                .tools
82                .iter()
83                .filter(|t| t.name == "web_search" || t.name == "web_fetch")
84                .map(|t| t.to_definition())
85                .collect(),
86            AgentMode::Planning => self
87                .tools
88                .iter()
89                .filter(|t| {
90                    t.category == ToolCategory::ReadOnly || t.category == ToolCategory::Signal
91                })
92                .map(|t| t.to_definition())
93                .collect(),
94            AgentMode::Research => self
95                .tools
96                .iter()
97                .filter(|t| {
98                    t.category == ToolCategory::ReadOnly || t.category == ToolCategory::Signal
99                })
100                .map(|t| t.to_definition())
101                .collect(),
102        }
103    }
104
105    /// Returns the category of a tool by name, or `None` if not found.
106    pub fn category_of(&self, tool_name: &str) -> Option<ToolCategory> {
107        self.tools
108            .iter()
109            .find(|t| t.name == tool_name)
110            .map(|t| t.category)
111    }
112
113    /// Returns `true` if the tool requires user approval before execution.
114    /// Destructive tools (write, edit, run) and signal tools (switch_mode,
115    /// question, auto_compact) require approval.
116    pub fn needs_approval(&self, tool_name: &str) -> bool {
117        self.category_of(tool_name)
118            .map(|c| c == ToolCategory::Destructive || c == ToolCategory::Signal)
119            .unwrap_or(false)
120    }
121
122    /// Returns `true` if the tool is a signal tool (switch_mode, question, auto_compact).
123    /// Signal tools are handled specially by the agent loop rather than executed generically.
124    pub fn is_signal_tool(&self, tool_name: &str) -> bool {
125        self.category_of(tool_name) == Some(ToolCategory::Signal)
126    }
127
128    /// Parse a signal tool's result string into a structured `SignalEvent`.
129    ///
130    /// Signal tools return plain strings, but the agent loop needs structured
131    /// data to dispatch them correctly. This method interprets the tool call
132    /// arguments (not the result string) to produce the appropriate event.
133    ///
134    /// Returns `None` if the tool is not a signal tool or the arguments are invalid.
135    pub fn parse_signal_event(
136        &self,
137        tool_name: &str,
138        arguments: &serde_json::Value,
139    ) -> Option<SignalEvent> {
140        match tool_name {
141            "switch_mode" => {
142                let mode_str = arguments.get("mode").and_then(|v| v.as_str()).unwrap_or("");
143                mode_str
144                    .parse::<AgentMode>()
145                    .ok()
146                    .map(|mode| SignalEvent::SwitchMode { mode })
147            }
148            "question" => {
149                let question = arguments
150                    .get("question")
151                    .and_then(|v| v.as_str())
152                    .unwrap_or("")
153                    .to_string();
154                let answers: Vec<String> = arguments
155                    .get("answers")
156                    .and_then(|v| v.as_array())
157                    .map(|arr| {
158                        arr.iter()
159                            .filter_map(|item| item.as_str().map(|s| s.to_string()))
160                            .collect()
161                    })
162                    .unwrap_or_default();
163                Some(SignalEvent::Question { question, answers })
164            }
165            "auto_compact" => {
166                let focus = arguments
167                    .get("focus")
168                    .and_then(|v| v.as_str())
169                    .unwrap_or("")
170                    .to_string();
171                Some(SignalEvent::AutoCompact { focus })
172            }
173            "invoke_skill" => {
174                let skill_name = arguments
175                    .get("skill_name")
176                    .and_then(|v| v.as_str())
177                    .unwrap_or("")
178                    .to_string();
179                if skill_name.is_empty() {
180                    None
181                } else {
182                    Some(SignalEvent::InvokeSkill { skill_name })
183                }
184            }
185            _ => None,
186        }
187    }
188
189    pub async fn execute_tool_call(
190        &self,
191        tool_name: &str,
192        arguments: &serde_json::Value,
193    ) -> String {
194        if let Some(tool) = self.tools.iter().find(|t| t.name == tool_name) {
195            tool::execute_tool_call(tool, arguments).await
196        } else {
197            format!("Error: Tool '{}' not found", tool_name)
198        }
199    }
200}