brainwires-tools 0.9.0

Built-in tool implementations for the Brainwires Agent Framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Tool Registry - Composable container for tool definitions
//!
//! Provides a `ToolRegistry` that stores tool definitions and supports
//! deferred loading, category filtering, and search.

use brainwires_core::Tool;

/// Tool categories for filtering tools by purpose
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolCategory {
    /// File operation tools.
    FileOps,
    /// Code search tools.
    Search,
    /// Semantic/RAG search tools.
    SemanticSearch,
    /// Git version control tools.
    Git,
    /// Task management tools.
    TaskManager,
    /// Agent pool management tools.
    AgentPool,
    /// Web fetching tools.
    Web,
    /// Web search tools.
    WebSearch,
    /// Shell command execution tools.
    Bash,
    /// Planning tools.
    Planning,
    /// Context recall tools.
    Context,
    /// Script orchestrator tools.
    Orchestrator,
    /// Code execution/interpreter tools.
    CodeExecution,
    /// Session task tools.
    SessionTask,
    /// Validation tools.
    Validation,
}

/// Composable tool registry - stores and queries tool definitions.
///
/// Unlike the CLI's registry which auto-registers all tools, this registry
/// is empty by default. Callers compose it by registering tools from
/// whichever modules they need.
///
/// # Example
/// ```ignore
/// use brainwires_tools::{ToolRegistry, BashTool, FileOpsTool, GitTool};
///
/// let mut registry = ToolRegistry::new();
/// registry.register_tools(BashTool::get_tools());
/// registry.register_tools(FileOpsTool::get_tools());
/// registry.register_tools(GitTool::get_tools());
/// ```
pub struct ToolRegistry {
    tools: Vec<Tool>,
}

impl ToolRegistry {
    /// Create an empty registry
    pub fn new() -> Self {
        Self { tools: vec![] }
    }

    /// Create a registry pre-populated with all built-in tools
    pub fn with_builtins() -> Self {
        let mut registry = Self::new();

        // Always-available tools
        registry.register_tools(crate::ToolSearchTool::get_tools());

        // Native-only tools
        #[cfg(feature = "native")]
        {
            registry.register_tools(crate::FileOpsTool::get_tools());
            registry.register_tools(crate::BashTool::get_tools());
            registry.register_tools(crate::GitTool::get_tools());
            registry.register_tools(crate::WebTool::get_tools());
            registry.register_tools(crate::SearchTool::get_tools());
            registry.register_tools(crate::get_validation_tools());
        }

        // Feature-gated tools
        #[cfg(feature = "orchestrator")]
        registry.register_tools(crate::OrchestratorTool::get_tools());

        #[cfg(feature = "interpreters")]
        registry.register_tools(crate::CodeExecTool::get_tools());

        #[cfg(feature = "rag")]
        registry.register_tools(crate::SemanticSearchTool::get_tools());

        registry
    }

    /// Register a single tool
    pub fn register(&mut self, tool: Tool) {
        self.tools.push(tool);
    }

    /// Register multiple tools at once
    pub fn register_tools(&mut self, tools: Vec<Tool>) {
        self.tools.extend(tools);
    }

    /// Get all registered tools
    pub fn get_all(&self) -> &[Tool] {
        &self.tools
    }

    /// Get all tools including additional external tools (e.g., MCP tools)
    pub fn get_all_with_extra(&self, extra: &[Tool]) -> Vec<Tool> {
        let mut all = self.tools.clone();
        all.extend(extra.iter().cloned());
        all
    }

    /// Look up a tool by name
    pub fn get(&self, name: &str) -> Option<&Tool> {
        self.tools.iter().find(|t| t.name == name)
    }

    /// Get tools that should be loaded initially (defer_loading = false)
    pub fn get_initial_tools(&self) -> Vec<&Tool> {
        self.tools.iter().filter(|t| !t.defer_loading).collect()
    }

    /// Get only deferred tools (defer_loading = true)
    pub fn get_deferred_tools(&self) -> Vec<&Tool> {
        self.tools.iter().filter(|t| t.defer_loading).collect()
    }

    /// Search tools by query string matching name and description
    pub fn search_tools(&self, query: &str) -> Vec<&Tool> {
        let query_lower = query.to_lowercase();
        let query_terms: Vec<&str> = query_lower.split_whitespace().collect();

        self.tools
            .iter()
            .filter(|tool| {
                let name_lower = tool.name.to_lowercase();
                let desc_lower = tool.description.to_lowercase();
                query_terms
                    .iter()
                    .any(|term| name_lower.contains(term) || desc_lower.contains(term))
            })
            .collect()
    }

    /// Get tools by category
    pub fn get_by_category(&self, category: ToolCategory) -> Vec<&Tool> {
        let names: &[&str] = match category {
            ToolCategory::FileOps => &[
                "read_file",
                "write_file",
                "edit_file",
                "patch_file",
                "list_directory",
                "search_files",
                "delete_file",
                "create_directory",
            ],
            ToolCategory::Search => &["search_code", "search_files"],
            ToolCategory::SemanticSearch => &[
                "index_codebase",
                "query_codebase",
                "search_with_filters",
                "get_rag_statistics",
                "clear_rag_index",
                "search_git_history",
            ],
            ToolCategory::Git => &[
                "git_status",
                "git_diff",
                "git_log",
                "git_stage",
                "git_unstage",
                "git_commit",
                "git_push",
                "git_pull",
                "git_fetch",
                "git_discard",
                "git_branch",
            ],
            ToolCategory::TaskManager => &[
                "task_create",
                "task_start",
                "task_complete",
                "task_list",
                "task_skip",
                "task_add",
                "task_block",
                "task_depends",
                "task_ready",
                "task_time",
            ],
            ToolCategory::AgentPool => &[
                "agent_spawn",
                "agent_status",
                "agent_list",
                "agent_stop",
                "agent_await",
            ],
            ToolCategory::Web => &["fetch_url"],
            ToolCategory::WebSearch => &["web_search", "web_browse", "web_scrape"],
            ToolCategory::Bash => &["execute_command"],
            ToolCategory::Planning => &["plan_task"],
            ToolCategory::Context => &["recall_context"],
            ToolCategory::Orchestrator => &["execute_script"],
            ToolCategory::CodeExecution => &["execute_code"],
            ToolCategory::SessionTask => &["task_list_write"],
            ToolCategory::Validation => &["check_duplicates", "verify_build", "check_syntax"],
        };

        self.tools
            .iter()
            .filter(|t| names.contains(&t.name.as_str()))
            .collect()
    }

    /// Get all tools including MCP tools
    pub fn get_all_with_mcp(&self, mcp_tools: &[Tool]) -> Vec<Tool> {
        self.get_all_with_extra(mcp_tools)
    }

    /// Get core tools for basic project exploration
    pub fn get_core(&self) -> Vec<&Tool> {
        let core_names = [
            "read_file",
            "write_file",
            "edit_file",
            "list_directory",
            "search_code",
            "execute_command",
            "git_status",
            "git_diff",
            "git_log",
            "git_stage",
            "git_commit",
            "search_tools",
            "index_codebase",
            "query_codebase",
        ];
        self.tools
            .iter()
            .filter(|t| core_names.contains(&t.name.as_str()))
            .collect()
    }

    /// Get primary meta-tools (always available)
    pub fn get_primary(&self) -> Vec<&Tool> {
        let primary_names = ["execute_script", "search_tools"];
        self.tools
            .iter()
            .filter(|t| primary_names.contains(&t.name.as_str()))
            .collect()
    }

    /// Search tools by semantic similarity using embeddings.
    ///
    /// Returns tools with their similarity scores, sorted by relevance.
    /// Requires the `rag` feature to be enabled.
    #[cfg(feature = "rag")]
    pub fn semantic_search_tools(
        &self,
        query: &str,
        limit: usize,
        min_score: f32,
    ) -> anyhow::Result<Vec<(&Tool, f32)>> {
        let tool_pairs: Vec<(String, String)> = self
            .tools
            .iter()
            .map(|t| (t.name.clone(), t.description.clone()))
            .collect();

        let index = crate::tool_embedding::ToolEmbeddingIndex::build(&tool_pairs)?;
        let results = index.search(query, limit, min_score)?;

        Ok(results
            .into_iter()
            .filter_map(|(name, score)| self.get(&name).map(|tool| (tool, score)))
            .collect())
    }

    /// Return a filtered view containing only the named tools.
    ///
    /// Useful when constructing a provider call for a constrained agent role —
    /// the caller supplies the allow-list (e.g. from `AgentRole::allowed_tools`)
    /// and receives only the matching `Tool` definitions.
    ///
    /// Tools not present in the registry are silently skipped, so the list may
    /// be shorter than `allow` if some tools are not registered.
    pub fn filtered_view(&self, allow: &[&str]) -> Vec<Tool> {
        self.tools
            .iter()
            .filter(|t| allow.contains(&t.name.as_str()))
            .cloned()
            .collect()
    }

    /// Total number of registered tools
    pub fn len(&self) -> usize {
        self.tools.len()
    }

    /// Whether the registry is empty
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }
}

impl Default for ToolRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use brainwires_core::ToolInputSchema;
    use std::collections::HashMap;

    fn make_tool(name: &str, defer: bool) -> Tool {
        Tool {
            name: name.to_string(),
            description: format!("A {} tool", name),
            input_schema: ToolInputSchema::object(HashMap::new(), vec![]),
            requires_approval: false,
            defer_loading: defer,
            ..Default::default()
        }
    }

    #[test]
    fn test_new_is_empty() {
        let registry = ToolRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
    }

    #[test]
    fn test_register_single() {
        let mut registry = ToolRegistry::new();
        registry.register(make_tool("test_tool", false));
        assert_eq!(registry.len(), 1);
        assert!(registry.get("test_tool").is_some());
    }

    #[test]
    fn test_register_multiple() {
        let mut registry = ToolRegistry::new();
        registry.register_tools(vec![make_tool("tool1", false), make_tool("tool2", false)]);
        assert_eq!(registry.len(), 2);
    }

    #[test]
    fn test_get_by_name() {
        let mut registry = ToolRegistry::new();
        registry.register(make_tool("my_tool", false));

        assert!(registry.get("my_tool").is_some());
        assert!(registry.get("nonexistent").is_none());
    }

    #[test]
    fn test_initial_vs_deferred() {
        let mut registry = ToolRegistry::new();
        registry.register(make_tool("initial", false));
        registry.register(make_tool("deferred", true));

        assert_eq!(registry.get_initial_tools().len(), 1);
        assert_eq!(registry.get_initial_tools()[0].name, "initial");

        assert_eq!(registry.get_deferred_tools().len(), 1);
        assert_eq!(registry.get_deferred_tools()[0].name, "deferred");
    }

    #[test]
    fn test_search_tools() {
        let mut registry = ToolRegistry::new();
        registry.register(Tool {
            name: "read_file".to_string(),
            description: "Read a file from disk".to_string(),
            input_schema: ToolInputSchema::object(HashMap::new(), vec![]),
            ..Default::default()
        });
        registry.register(Tool {
            name: "write_file".to_string(),
            description: "Write content to a file".to_string(),
            input_schema: ToolInputSchema::object(HashMap::new(), vec![]),
            ..Default::default()
        });
        registry.register(Tool {
            name: "execute_command".to_string(),
            description: "Execute a bash command".to_string(),
            input_schema: ToolInputSchema::object(HashMap::new(), vec![]),
            ..Default::default()
        });

        let results = registry.search_tools("file");
        assert_eq!(results.len(), 2);

        let results = registry.search_tools("bash");
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_get_all_with_extra() {
        let mut registry = ToolRegistry::new();
        registry.register(make_tool("builtin", false));

        let extra = vec![make_tool("mcp_tool", false)];
        let all = registry.get_all_with_extra(&extra);
        assert_eq!(all.len(), 2);
    }

    #[test]
    fn test_no_duplicate_names_in_builtins() {
        let registry = ToolRegistry::with_builtins();
        let mut seen = std::collections::HashSet::new();
        for tool in registry.get_all() {
            assert!(
                seen.insert(tool.name.clone()),
                "Duplicate tool name: {}",
                tool.name
            );
        }
    }

    #[test]
    fn filtered_view_returns_only_named_tools() {
        let mut registry = ToolRegistry::new();
        registry.register(make_tool("read_file", false));
        registry.register(make_tool("write_file", false));
        registry.register(make_tool("execute_command", false));

        let view = registry.filtered_view(&["read_file", "execute_command"]);
        assert_eq!(view.len(), 2);
        let names: Vec<&str> = view.iter().map(|t| t.name.as_str()).collect();
        assert!(names.contains(&"read_file"));
        assert!(names.contains(&"execute_command"));
        assert!(!names.contains(&"write_file"));
    }

    #[test]
    fn filtered_view_unknown_names_are_silently_skipped() {
        let mut registry = ToolRegistry::new();
        registry.register(make_tool("read_file", false));

        // "nonexistent" is not in the registry — must not panic, just ignored
        let view = registry.filtered_view(&["read_file", "nonexistent"]);
        assert_eq!(view.len(), 1);
        assert_eq!(view[0].name, "read_file");
    }

    #[test]
    fn filtered_view_empty_allow_list_returns_empty() {
        let mut registry = ToolRegistry::new();
        registry.register(make_tool("read_file", false));

        let view = registry.filtered_view(&[]);
        assert!(view.is_empty());
    }
}