opencrabs 0.3.13

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Tool Manage — meta-tool for runtime tool management.
//!
//! Allows the agent to list, add, remove, enable, disable, and reload
//! dynamic tools defined in `~/.opencrabs/tools.toml`.

use super::ToolRegistry;
use super::dynamic::{DynamicToolDef, DynamicToolLoader, ExecutorType, ParamDef};
use super::error::Result;
use super::r#trait::{Tool, ToolCapability, ToolExecutionContext, ToolResult};
use async_trait::async_trait;
use serde_json::Value;
use std::path::PathBuf;
use std::sync::Arc;

/// Meta-tool the agent uses to manage dynamic tools at runtime.
pub struct ToolManageTool {
    registry: Arc<ToolRegistry>,
    tools_path: PathBuf,
}

impl ToolManageTool {
    pub fn new(registry: Arc<ToolRegistry>, tools_path: PathBuf) -> Self {
        Self {
            registry,
            tools_path,
        }
    }
}

#[async_trait]
impl Tool for ToolManageTool {
    fn name(&self) -> &str {
        "tool_manage"
    }

    fn description(&self) -> &str {
        "Manage dynamic tools at runtime. Add new HTTP or shell tools, list/remove/enable/disable \
         existing ones, or reload from disk. Dynamic tools appear in the tool list immediately \
         without restart. Use this to extend your own capabilities on the fly."
    }

    fn input_schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["list", "add", "remove", "enable", "disable", "reload"],
                    "description": "Action to perform"
                },
                "name": {
                    "type": "string",
                    "description": "Tool name (required for add/remove/enable/disable)"
                },
                "description": {
                    "type": "string",
                    "description": "Tool description shown to the LLM (required for add)"
                },
                "executor": {
                    "type": "string",
                    "enum": ["http", "shell"],
                    "description": "Executor type (required for add)"
                },
                "method": {
                    "type": "string",
                    "description": "HTTP method (for http executor)"
                },
                "url": {
                    "type": "string",
                    "description": "URL with optional {{param}} placeholders (for http executor)"
                },
                "headers": {
                    "type": "object",
                    "description": "Static headers (for http executor)",
                    "additionalProperties": { "type": "string" }
                },
                "command": {
                    "type": "string",
                    "description": "Shell command with optional {{param}} placeholders (for shell executor)"
                },
                "params": {
                    "type": "array",
                    "description": "Parameter definitions",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": { "type": "string" },
                            "type": { "type": "string", "default": "string" },
                            "description": { "type": "string" },
                            "required": { "type": "boolean", "default": true },
                            "default": { "type": "string" }
                        },
                        "required": ["name"]
                    }
                },
                "requires_approval": {
                    "type": "boolean",
                    "description": "Whether tool requires approval (default: true)"
                },
                "timeout_secs": {
                    "type": "integer",
                    "description": "Timeout in seconds for http executor (default: 30)"
                }
            },
            "required": ["action"]
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::SystemModification]
    }

    fn requires_approval(&self) -> bool {
        true
    }

    async fn execute(&self, input: Value, _context: &ToolExecutionContext) -> Result<ToolResult> {
        let action = input["action"].as_str().unwrap_or("").to_string();

        match action.as_str() {
            "list" => self.handle_list(),
            "add" => self.handle_add(&input),
            "remove" => self.handle_remove(&input),
            "enable" => self.handle_set_enabled(&input, true),
            "disable" => self.handle_set_enabled(&input, false),
            "reload" => self.handle_reload(),
            _ => Ok(ToolResult::error(format!(
                "Unknown action: '{action}'. Use: list, add, remove, enable, disable, reload"
            ))),
        }
    }
}

impl ToolManageTool {
    fn handle_list(&self) -> Result<ToolResult> {
        let defs = DynamicToolLoader::list_tools_detailed(&self.tools_path);
        if defs.is_empty() {
            return Ok(ToolResult::success(
                "No dynamic tools defined. Use 'add' to create one.".to_string(),
            ));
        }

        let mut output = format!("Dynamic tools ({}):\n\n", defs.len());
        for def in &defs {
            let status = if def.enabled { "enabled" } else { "disabled" };
            let executor = match def.executor {
                ExecutorType::Http => "http",
                ExecutorType::Shell => "shell",
            };
            output.push_str(&format!(
                "  {} [{}] ({})\n    {}\n",
                def.name, status, executor, def.description
            ));
            if !def.params.is_empty() {
                output.push_str("    params: ");
                let param_strs: Vec<String> = def
                    .params
                    .iter()
                    .map(|p| {
                        if p.required {
                            format!("{}*", p.name)
                        } else {
                            p.name.clone()
                        }
                    })
                    .collect();
                output.push_str(&param_strs.join(", "));
                output.push('\n');
            }
        }
        Ok(ToolResult::success(output))
    }

    fn handle_add(&self, input: &Value) -> Result<ToolResult> {
        let name = match input["name"].as_str() {
            Some(n) if !n.is_empty() => n,
            _ => return Ok(ToolResult::error("'name' is required for add".to_string())),
        };
        let description = match input["description"].as_str() {
            Some(d) if !d.is_empty() => d,
            _ => {
                return Ok(ToolResult::error(
                    "'description' is required for add".to_string(),
                ));
            }
        };
        let executor = match input["executor"].as_str() {
            Some("http") => ExecutorType::Http,
            Some("shell") => ExecutorType::Shell,
            _ => {
                return Ok(ToolResult::error(
                    "'executor' is required: http or shell".to_string(),
                ));
            }
        };

        // Parse params
        let params = if let Some(arr) = input["params"].as_array() {
            arr.iter()
                .filter_map(|p| {
                    let pname = p["name"].as_str()?;
                    Some(ParamDef {
                        name: pname.to_string(),
                        param_type: p["type"].as_str().unwrap_or("string").to_string(),
                        description: p["description"].as_str().unwrap_or("").to_string(),
                        required: p["required"].as_bool().unwrap_or(true),
                        default: if p["default"].is_null() {
                            None
                        } else {
                            Some(p["default"].clone())
                        },
                    })
                })
                .collect()
        } else {
            Vec::new()
        };

        let def = DynamicToolDef {
            name: name.to_string(),
            description: description.to_string(),
            executor,
            method: input["method"].as_str().map(|s| s.to_string()),
            url: input["url"].as_str().map(|s| s.to_string()),
            headers: input["headers"]
                .as_object()
                .map(|obj| {
                    obj.iter()
                        .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string())))
                        .collect()
                })
                .unwrap_or_default(),
            command: input["command"].as_str().map(|s| s.to_string()),
            params,
            timeout_secs: input["timeout_secs"].as_u64().unwrap_or(30),
            requires_approval: input["requires_approval"].as_bool().unwrap_or(true),
            enabled: true,
        };

        match DynamicToolLoader::add_tool(&self.tools_path, def, &self.registry) {
            Ok(()) => Ok(ToolResult::success(format!(
                "Dynamic tool '{name}' added and registered. It's now available in your tool list."
            ))),
            Err(e) => Ok(ToolResult::error(format!("Failed to add tool: {e}"))),
        }
    }

    fn handle_remove(&self, input: &Value) -> Result<ToolResult> {
        let name = match input["name"].as_str() {
            Some(n) if !n.is_empty() => n,
            _ => {
                return Ok(ToolResult::error(
                    "'name' is required for remove".to_string(),
                ));
            }
        };

        match DynamicToolLoader::remove_tool(&self.tools_path, name, &self.registry) {
            Ok(true) => Ok(ToolResult::success(format!(
                "Dynamic tool '{name}' removed and unregistered."
            ))),
            Ok(false) => Ok(ToolResult::error(format!(
                "Tool '{name}' not found in dynamic tools."
            ))),
            Err(e) => Ok(ToolResult::error(format!("Failed to remove tool: {e}"))),
        }
    }

    fn handle_set_enabled(&self, input: &Value, enabled: bool) -> Result<ToolResult> {
        let name = match input["name"].as_str() {
            Some(n) if !n.is_empty() => n,
            _ => {
                return Ok(ToolResult::error(
                    "'name' is required for enable/disable".to_string(),
                ));
            }
        };
        let action_word = if enabled { "enabled" } else { "disabled" };

        match DynamicToolLoader::set_enabled(&self.tools_path, name, enabled, &self.registry) {
            Ok(true) => Ok(ToolResult::success(format!(
                "Dynamic tool '{name}' {action_word}."
            ))),
            Ok(false) => Ok(ToolResult::error(format!(
                "Tool '{name}' not found in dynamic tools."
            ))),
            Err(e) => Ok(ToolResult::error(format!(
                "Failed to {action_word} tool: {e}"
            ))),
        }
    }

    fn handle_reload(&self) -> Result<ToolResult> {
        let count = DynamicToolLoader::reload(&self.tools_path, &self.registry);
        Ok(ToolResult::success(format!(
            "Reloaded {count} dynamic tool(s) from {}",
            self.tools_path.display()
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write as IoWrite;
    use tempfile::TempDir;
    use uuid::Uuid;

    fn setup() -> (Arc<ToolRegistry>, PathBuf, ToolManageTool) {
        let dir = TempDir::new().unwrap();
        let tools_path = dir.keep().join("tools.toml");
        let registry = Arc::new(ToolRegistry::new());
        let tool = ToolManageTool::new(registry.clone(), tools_path.clone());
        (registry, tools_path, tool)
    }

    fn ctx() -> ToolExecutionContext {
        ToolExecutionContext::new(Uuid::new_v4()).with_auto_approve(true)
    }

    #[tokio::test]
    async fn test_list_empty() {
        let (_reg, _path, tool) = setup();
        let result = tool
            .execute(serde_json::json!({"action": "list"}), &ctx())
            .await
            .unwrap();
        assert!(result.success);
        assert!(result.output.contains("No dynamic tools"));
    }

    #[tokio::test]
    async fn test_add_shell_tool() {
        let (reg, _path, tool) = setup();
        let result = tool
            .execute(
                serde_json::json!({
                    "action": "add",
                    "name": "my_echo",
                    "description": "Echo a message",
                    "executor": "shell",
                    "command": "echo {{msg}}",
                    "requires_approval": false,
                    "params": [{"name": "msg", "type": "string", "required": true}]
                }),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(result.success, "add failed: {:?}", result.error);
        assert!(reg.has_tool("my_echo"));
    }

    #[tokio::test]
    async fn test_add_then_list() {
        let (_reg, _path, tool) = setup();
        tool.execute(
            serde_json::json!({
                "action": "add",
                "name": "test_tool",
                "description": "A test tool",
                "executor": "shell",
                "command": "echo test"
            }),
            &ctx(),
        )
        .await
        .unwrap();

        let result = tool
            .execute(serde_json::json!({"action": "list"}), &ctx())
            .await
            .unwrap();
        assert!(result.output.contains("test_tool"));
        assert!(result.output.contains("enabled"));
    }

    #[tokio::test]
    async fn test_remove_tool() {
        let (reg, _path, tool) = setup();
        // Add first
        tool.execute(
            serde_json::json!({
                "action": "add",
                "name": "removable",
                "description": "Will be removed",
                "executor": "shell",
                "command": "echo bye"
            }),
            &ctx(),
        )
        .await
        .unwrap();
        assert!(reg.has_tool("removable"));

        // Remove
        let result = tool
            .execute(
                serde_json::json!({"action": "remove", "name": "removable"}),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(result.success);
        assert!(!reg.has_tool("removable"));
    }

    #[tokio::test]
    async fn test_disable_enable() {
        let (reg, _path, tool) = setup();
        tool.execute(
            serde_json::json!({
                "action": "add",
                "name": "toggleable",
                "description": "Can be toggled",
                "executor": "shell",
                "command": "echo hi"
            }),
            &ctx(),
        )
        .await
        .unwrap();
        assert!(reg.has_tool("toggleable"));

        // Disable
        let result = tool
            .execute(
                serde_json::json!({"action": "disable", "name": "toggleable"}),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(result.success);
        assert!(!reg.has_tool("toggleable"));

        // Enable
        let result = tool
            .execute(
                serde_json::json!({"action": "enable", "name": "toggleable"}),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(result.success);
        assert!(reg.has_tool("toggleable"));
    }

    #[tokio::test]
    async fn test_reload() {
        let (reg, path, tool) = setup();
        // Write a tools.toml directly
        let mut f = std::fs::File::create(&path).unwrap();
        writeln!(
            f,
            r#"
[[tools]]
name = "from_disk"
description = "Loaded from disk"
executor = "shell"
command = "echo disk"
"#
        )
        .unwrap();

        let result = tool
            .execute(serde_json::json!({"action": "reload"}), &ctx())
            .await
            .unwrap();
        assert!(result.success);
        assert!(reg.has_tool("from_disk"));
    }

    #[tokio::test]
    async fn test_add_missing_name() {
        let (_reg, _path, tool) = setup();
        let result = tool
            .execute(
                serde_json::json!({"action": "add", "executor": "shell"}),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(!result.success);
    }

    #[tokio::test]
    async fn test_add_missing_executor() {
        let (_reg, _path, tool) = setup();
        let result = tool
            .execute(
                serde_json::json!({
                    "action": "add",
                    "name": "no_exec",
                    "description": "Missing executor"
                }),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(!result.success);
    }

    #[tokio::test]
    async fn test_unknown_action() {
        let (_reg, _path, tool) = setup();
        let result = tool
            .execute(serde_json::json!({"action": "destroy"}), &ctx())
            .await
            .unwrap();
        assert!(!result.success);
        assert!(result.error.unwrap().contains("Unknown action"));
    }

    #[tokio::test]
    async fn test_add_http_tool() {
        let (reg, _path, tool) = setup();
        let result = tool
            .execute(
                serde_json::json!({
                    "action": "add",
                    "name": "health_check",
                    "description": "Check server health",
                    "executor": "http",
                    "method": "GET",
                    "url": "https://example.com/health",
                    "timeout_secs": 10,
                    "headers": {"Authorization": "Bearer {{token}}"},
                    "params": [{"name": "token", "type": "string", "required": true}]
                }),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(result.success, "add http failed: {:?}", result.error);
        assert!(reg.has_tool("health_check"));

        // Verify it shows up in tool definitions
        let defs = reg.get_tool_definitions();
        let hc = defs.iter().find(|t| t.name == "health_check").unwrap();
        assert!(hc.description.contains("health"));
    }

    #[tokio::test]
    async fn test_remove_nonexistent() {
        let (_reg, _path, tool) = setup();
        let result = tool
            .execute(
                serde_json::json!({"action": "remove", "name": "ghost"}),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(!result.success);
    }
}