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    /// When `auto_compact_enabled` is false, the `auto_compact` tool is excluded.
78    pub fn tools_for_mode(
79        &self,
80        mode: AgentMode,
81        auto_compact_enabled: bool,
82    ) -> Vec<ToolDefinition> {
83        let filter_compact = |t: &&Tool| {
84            if t.name == "auto_compact" {
85                auto_compact_enabled
86            } else {
87                true
88            }
89        };
90        match mode {
91            AgentMode::Agent => self
92                .tools
93                .iter()
94                .filter(filter_compact)
95                .map(|t| t.to_definition())
96                .collect(),
97            AgentMode::Casual => self
98                .tools
99                .iter()
100                .filter(|t| filter_compact(t) && (t.name == "web_search" || t.name == "web_fetch"))
101                .map(|t| t.to_definition())
102                .collect(),
103            AgentMode::Planning => self
104                .tools
105                .iter()
106                .filter(|t| {
107                    filter_compact(t)
108                        && (t.category == ToolCategory::ReadOnly
109                            || t.category == ToolCategory::Signal)
110                })
111                .map(|t| t.to_definition())
112                .collect(),
113            AgentMode::Research => self
114                .tools
115                .iter()
116                .filter(|t| {
117                    filter_compact(t)
118                        && (t.category == ToolCategory::ReadOnly
119                            || t.category == ToolCategory::Signal)
120                })
121                .map(|t| t.to_definition())
122                .collect(),
123        }
124    }
125
126    /// Returns the category of a tool by name, or `None` if not found.
127    pub fn category_of(&self, tool_name: &str) -> Option<ToolCategory> {
128        self.tools
129            .iter()
130            .find(|t| t.name == tool_name)
131            .map(|t| t.category)
132    }
133
134    /// Returns `true` if the tool requires user approval before execution.
135    /// Destructive tools (write, edit, run) and signal tools (switch_mode,
136    /// question, auto_compact) require approval.
137    pub fn needs_approval(&self, tool_name: &str) -> bool {
138        self.category_of(tool_name)
139            .map(|c| c == ToolCategory::Destructive || c == ToolCategory::Signal)
140            .unwrap_or(false)
141    }
142
143    /// Returns `true` if the tool is a signal tool (switch_mode, question, auto_compact).
144    /// Signal tools are handled specially by the agent loop rather than executed generically.
145    pub fn is_signal_tool(&self, tool_name: &str) -> bool {
146        self.category_of(tool_name) == Some(ToolCategory::Signal)
147    }
148
149    /// Parse a signal tool's result string into a structured `SignalEvent`.
150    ///
151    /// Signal tools return plain strings, but the agent loop needs structured
152    /// data to dispatch them correctly. This method interprets the tool call
153    /// arguments (not the result string) to produce the appropriate event.
154    ///
155    /// Returns `None` if the tool is not a signal tool or the arguments are invalid.
156    pub fn parse_signal_event(
157        &self,
158        tool_name: &str,
159        arguments: &serde_json::Value,
160    ) -> Option<SignalEvent> {
161        match tool_name {
162            "switch_mode" => {
163                let mode_str = arguments.get("mode").and_then(|v| v.as_str()).unwrap_or("");
164                mode_str
165                    .parse::<AgentMode>()
166                    .ok()
167                    .map(|mode| SignalEvent::SwitchMode { mode })
168            }
169            "question" => {
170                let question = arguments
171                    .get("question")
172                    .and_then(|v| v.as_str())
173                    .unwrap_or("")
174                    .to_string();
175                let answers: Vec<String> = arguments
176                    .get("answers")
177                    .and_then(|v| v.as_array())
178                    .map(|arr| {
179                        arr.iter()
180                            .filter_map(|item| item.as_str().map(|s| s.to_string()))
181                            .collect()
182                    })
183                    .unwrap_or_default();
184                Some(SignalEvent::Question { question, answers })
185            }
186            "auto_compact" => {
187                let focus = arguments
188                    .get("focus")
189                    .and_then(|v| v.as_str())
190                    .unwrap_or("")
191                    .to_string();
192                Some(SignalEvent::AutoCompact { focus })
193            }
194            "invoke_skill" => {
195                let skill_name = arguments
196                    .get("skill_name")
197                    .and_then(|v| v.as_str())
198                    .unwrap_or("")
199                    .to_string();
200                if skill_name.is_empty() {
201                    None
202                } else {
203                    Some(SignalEvent::InvokeSkill { skill_name })
204                }
205            }
206            _ => None,
207        }
208    }
209
210    pub async fn execute_tool_call(
211        &self,
212        tool_name: &str,
213        arguments: &serde_json::Value,
214    ) -> String {
215        if let Some(tool) = self.tools.iter().find(|t| t.name == tool_name) {
216            tool::execute_tool_call(tool, arguments).await
217        } else {
218            format!("Error: Tool '{}' not found", tool_name)
219        }
220    }
221}