Skip to main content

tinyharness_lib/custom_tools/
mod.rs

1pub mod custom_tool;
2pub mod shell;
3
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8pub use custom_tool::{CustomToolCategory, CustomToolDefinition};
9pub use shell::{ShellCommand, execute_shell_tool};
10
11/// Custom-tool configuration loaded from `custom_tools.json`.
12#[derive(Debug, Clone, Default, Serialize, Deserialize)]
13pub struct CustomToolConfig {
14    #[serde(default)]
15    pub custom_tools: Vec<CustomToolDefinition>,
16}
17
18/// Custom-tool manager — loads and merges global + project custom tools.
19#[derive(Debug, Clone, Default)]
20pub struct CustomToolManager {
21    config: CustomToolConfig,
22}
23
24/// Error type for custom-tool loading.
25#[derive(Debug)]
26pub enum CustomToolError {
27    Io(std::io::Error),
28    Parse(serde_json::Error),
29}
30
31impl std::fmt::Display for CustomToolError {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        match self {
34            CustomToolError::Io(e) => write!(f, "I/O error: {}", e),
35            CustomToolError::Parse(e) => write!(f, "parse error: {}", e),
36        }
37    }
38}
39
40impl std::error::Error for CustomToolError {}
41
42impl From<std::io::Error> for CustomToolError {
43    fn from(e: std::io::Error) -> Self {
44        CustomToolError::Io(e)
45    }
46}
47
48impl From<serde_json::Error> for CustomToolError {
49    fn from(e: serde_json::Error) -> Self {
50        CustomToolError::Parse(e)
51    }
52}
53
54/// Default path for the global custom-tools config file.
55fn global_custom_tools_path() -> PathBuf {
56    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
57    PathBuf::from(home).join(".config/tinyharness/custom_tools.json")
58}
59
60/// Discover `.tinyharness/custom_tools.json` by walking up from the given directory.
61/// Returns `None` if no file is found.
62fn discover_project_custom_tools(start_dir: &std::path::Path) -> Option<PathBuf> {
63    let mut dir = start_dir.to_path_buf();
64    loop {
65        let candidate = dir.join(".tinyharness").join("custom_tools.json");
66        if candidate.is_file() {
67            return Some(candidate);
68        }
69        if let Some(parent) = dir.parent() {
70            if parent == dir {
71                break;
72            }
73            dir = parent.to_path_buf();
74        } else {
75            break;
76        }
77    }
78    None
79}
80
81/// Load a single custom-tools config file. Returns `Ok(None)` if the file doesn't exist.
82fn load_config_file(path: &std::path::Path) -> Result<Option<CustomToolConfig>, CustomToolError> {
83    if !path.is_file() {
84        return Ok(None);
85    }
86    let content = std::fs::read_to_string(path)?;
87    let config: CustomToolConfig = serde_json::from_str(&content)?;
88    Ok(Some(config))
89}
90
91impl CustomToolManager {
92    /// Load and merge global + project custom-tools configs.
93    ///
94    /// Global config is loaded from `~/.config/tinyharness/custom_tools.json`.
95    /// Project config is loaded from `.tinyharness/custom_tools.json` (walking up
96    /// from CWD). Project tools are **appended** to the global list (both run;
97    /// global first, then project).
98    pub fn load() -> Self {
99        Self::load_from_cwd(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
100    }
101
102    /// Load from a specific directory (for testing).
103    pub fn load_from_cwd(cwd: &std::path::Path) -> Self {
104        let mut combined = CustomToolConfig::default();
105
106        // Global config
107        let global_path = global_custom_tools_path();
108        match load_config_file(&global_path) {
109            Ok(Some(cfg)) => combined = cfg,
110            Ok(None) => {}
111            Err(e) => {
112                tracing::warn!(
113                    "Failed to load global custom_tools.json from {}: {e}",
114                    global_path.display()
115                );
116            }
117        }
118
119        // Project config (extends global)
120        if let Some(project_path) = discover_project_custom_tools(cwd) {
121            match load_config_file(&project_path) {
122                Ok(Some(cfg)) => {
123                    combined.custom_tools.extend(cfg.custom_tools);
124                }
125                Ok(None) => {}
126                Err(e) => {
127                    tracing::warn!(
128                        "Failed to load project custom_tools.json from {}: {e}",
129                        project_path.display()
130                    );
131                }
132            }
133        }
134
135        // Validate custom tool names don't collide with built-in tools
136        let builtin = [
137            "ls",
138            "read",
139            "write",
140            "edit",
141            "grep",
142            "glob",
143            "run",
144            "web_search",
145            "web_fetch",
146            "switch_mode",
147            "question",
148            "auto_compact",
149            "invoke_skill",
150            "screenshot",
151        ];
152        for tool in &combined.custom_tools {
153            if builtin.contains(&tool.name.as_str()) {
154                tracing::warn!(
155                    "Custom tool '{}' has the same name as a built-in tool and will be ignored",
156                    tool.name
157                );
158            }
159        }
160
161        CustomToolManager { config: combined }
162    }
163
164    /// Load from an explicit config (for testing).
165    pub fn from_config(config: CustomToolConfig) -> Self {
166        CustomToolManager { config }
167    }
168
169    /// Return the list of custom tool definitions.
170    pub fn custom_tools(&self) -> &[CustomToolDefinition] {
171        &self.config.custom_tools
172    }
173
174    /// Return true if there are no custom tools configured.
175    pub fn is_empty(&self) -> bool {
176        self.config.custom_tools.is_empty()
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn test_empty_config_parses() {
186        let config: CustomToolConfig = serde_json::from_str("{}").unwrap();
187        assert!(config.custom_tools.is_empty());
188    }
189
190    #[test]
191    fn test_full_config_parses() {
192        let json = r#"{
193            "custom_tools": [
194                {
195                    "name": "greet",
196                    "description": "Say hi",
197                    "category": "readonly",
198                    "parameters": {
199                        "type": "object",
200                        "properties": {
201                            "name": { "type": "string", "description": "Who to greet" }
202                        },
203                        "required": ["name"]
204                    },
205                    "command": "echo hello {name}"
206                }
207            ]
208        }"#;
209        let config: CustomToolConfig = serde_json::from_str(json).unwrap();
210        assert_eq!(config.custom_tools.len(), 1);
211        assert_eq!(config.custom_tools[0].name, "greet");
212    }
213
214    #[test]
215    fn test_custom_tool_manager_load_from_config() {
216        let config = CustomToolConfig {
217            custom_tools: vec![],
218        };
219        let mgr = CustomToolManager::from_config(config);
220        assert!(mgr.is_empty());
221    }
222
223    #[test]
224    fn test_load_config_file_missing_returns_none() {
225        let path = std::path::Path::new("/nonexistent/path/custom_tools.json");
226        let result = load_config_file(path).unwrap();
227        assert!(result.is_none());
228    }
229
230    #[test]
231    fn test_load_config_file_valid() {
232        let dir = std::env::temp_dir().join(format!(
233            "tinyharness_custom_tools_test_{}",
234            std::process::id()
235        ));
236        std::fs::create_dir_all(&dir).unwrap();
237        let path = dir.join("custom_tools.json");
238        std::fs::write(&path, r#"{"custom_tools": []}"#).unwrap();
239
240        let config = load_config_file(&path).unwrap().unwrap();
241        assert!(config.custom_tools.is_empty());
242
243        let _ = std::fs::remove_file(&path);
244        let _ = std::fs::remove_dir(&dir);
245    }
246
247    #[test]
248    fn test_load_config_file_invalid_json() {
249        let dir = std::env::temp_dir().join(format!(
250            "tinyharness_custom_tools_test_invalid_{}",
251            std::process::id()
252        ));
253        std::fs::create_dir_all(&dir).unwrap();
254        let path = dir.join("custom_tools.json");
255        std::fs::write(&path, "not json").unwrap();
256
257        let result = load_config_file(&path);
258        assert!(result.is_err());
259
260        let _ = std::fs::remove_file(&path);
261        let _ = std::fs::remove_dir(&dir);
262    }
263
264    #[test]
265    fn test_discover_project_custom_tools_finds_file() {
266        let dir = std::env::temp_dir().join(format!(
267            "tinyharness_custom_tools_discover_{}",
268            std::process::id()
269        ));
270        let project_dir = dir.join("myproject/.tinyharness");
271        std::fs::create_dir_all(&project_dir).unwrap();
272        let tools_path = project_dir.join("custom_tools.json");
273        std::fs::write(&tools_path, "{}").unwrap();
274
275        let found = discover_project_custom_tools(&dir.join("myproject"));
276        assert_eq!(found, Some(tools_path.clone()));
277
278        // Also test from a subdirectory — should walk up and find it
279        let subdir = dir.join("myproject/src/deep");
280        std::fs::create_dir_all(&subdir).unwrap();
281        let found = discover_project_custom_tools(&subdir);
282        assert_eq!(found, Some(tools_path.clone()));
283
284        let _ = std::fs::remove_dir_all(&dir);
285    }
286
287    #[test]
288    fn test_discover_project_custom_tools_not_found() {
289        let dir = std::env::temp_dir().join(format!(
290            "tinyharness_custom_tools_nodiscover_{}",
291            std::process::id()
292        ));
293        std::fs::create_dir_all(&dir).unwrap();
294        let found = discover_project_custom_tools(&dir);
295        assert_eq!(found, None);
296        let _ = std::fs::remove_dir(&dir);
297    }
298}