zeptoclaw 0.8.2

Ultra-lightweight personal AI assistant
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! Plugin types for ZeptoClaw
//!
//! This module defines all types used by the plugin system, including
//! manifest structures for parsing `plugin.json` files, plugin configuration,
//! and the runtime plugin representation.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::path::PathBuf;

use crate::tools::ToolCategory;

/// Default execution mode for plugins.
fn default_execution() -> String {
    "command".to_string()
}

/// Default protocol for binary plugins.
fn default_protocol() -> String {
    "jsonrpc".to_string()
}

/// The manifest loaded from a plugin's `plugin.json` file.
///
/// Each plugin directory must contain a `plugin.json` file that conforms
/// to this structure. The manifest declares the plugin's identity and the
/// tools it provides.
///
/// # Example
///
/// ```json
/// {
///   "name": "git-tools",
///   "version": "1.0.0",
///   "description": "Git integration tools",
///   "author": "ZeptoClaw",
///   "tools": [
///     {
///       "name": "git_status",
///       "description": "Get the git status of the workspace",
///       "parameters": {
///         "type": "object",
///         "properties": {
///           "path": { "type": "string", "description": "Repository path" }
///         },
///         "required": ["path"]
///       },
///       "command": "git -C {{path}} status --porcelain",
///       "timeout_secs": 10
///     }
///   ]
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginManifest {
    /// Plugin name. Must be unique, alphanumeric characters and hyphens only,
    /// between 1 and 64 characters.
    pub name: String,

    /// Semantic version string (e.g., "1.0.0").
    pub version: String,

    /// Human-readable description of what the plugin provides.
    pub description: String,

    /// Optional author name or identifier.
    #[serde(default)]
    pub author: Option<String>,

    /// List of tool definitions provided by this plugin.
    pub tools: Vec<PluginToolDef>,

    /// Execution mode: "command" (default) or "binary" (JSON-RPC stdin/stdout).
    #[serde(default = "default_execution")]
    pub execution: String,

    /// Binary plugin configuration. Required when execution is "binary".
    #[serde(default)]
    pub binary: Option<BinaryPluginConfig>,
}

/// Configuration for binary plugin execution.
///
/// Binary plugins are standalone executables that communicate via JSON-RPC 2.0
/// over stdin/stdout. They are spawned on-demand per tool call.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinaryPluginConfig {
    /// Relative path to binary within plugin directory.
    pub path: String,

    /// Protocol: only "jsonrpc" supported.
    #[serde(default = "default_protocol")]
    pub protocol: String,

    /// Optional timeout override in seconds (default: 30).
    #[serde(default)]
    pub timeout_secs: Option<u64>,

    /// Optional SHA-256 hex digest for binary integrity verification.
    /// When set, the binary's hash is checked before execution.
    #[serde(default)]
    pub sha256: Option<String>,
}

/// A tool definition within a plugin manifest.
///
/// Each tool wraps a shell command template that is executed when the LLM
/// invokes the tool. Parameter interpolation uses `{{param_name}}` syntax
/// within the command string.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginToolDef {
    /// Tool name as registered with the agent. Must be alphanumeric
    /// characters and underscores only.
    pub name: String,

    /// Tool description sent to the LLM to help it understand
    /// when and how to use the tool.
    pub description: String,

    /// JSON Schema describing the tool's parameters.
    pub parameters: Value,

    /// Shell command template. Uses `{{param_name}}` for parameter interpolation.
    /// Must not contain dangerous shell operators (&&, ||, ;, |, backticks).
    /// Empty for binary plugins.
    #[serde(default)]
    pub command: String,

    /// Optional working directory for command execution.
    #[serde(default)]
    pub working_dir: Option<String>,

    /// Optional timeout in seconds. Defaults to 30 if not specified.
    #[serde(default)]
    pub timeout_secs: Option<u64>,

    /// Optional environment variables to set during command execution.
    #[serde(default)]
    pub env: Option<HashMap<String, String>>,

    /// Optional tool category for agent mode enforcement.
    /// Defaults to `Shell` (fail-closed) if not specified.
    #[serde(default)]
    pub category: Option<ToolCategory>,
}

impl PluginManifest {
    /// Returns true if this plugin uses binary execution mode.
    pub fn is_binary(&self) -> bool {
        self.execution == "binary"
    }
}

impl PluginToolDef {
    /// Returns the effective timeout in seconds, defaulting to 30.
    pub fn effective_timeout(&self) -> u64 {
        self.timeout_secs.unwrap_or(30)
    }

    /// Returns the effective tool category, defaulting to Shell (fail-closed).
    pub fn effective_category(&self) -> ToolCategory {
        self.category.unwrap_or(ToolCategory::Shell)
    }
}

/// A loaded plugin with its manifest, filesystem path, and enabled state.
#[derive(Debug, Clone)]
pub struct Plugin {
    /// The parsed plugin manifest.
    pub manifest: PluginManifest,

    /// The directory path where the plugin was loaded from.
    pub path: PathBuf,

    /// Whether this plugin is currently enabled.
    pub enabled: bool,
}

impl Plugin {
    /// Create a new plugin from a manifest and path, enabled by default.
    pub fn new(manifest: PluginManifest, path: PathBuf) -> Self {
        Self {
            manifest,
            path,
            enabled: true,
        }
    }

    /// Get the plugin name from its manifest.
    pub fn name(&self) -> &str {
        &self.manifest.name
    }

    /// Get the number of tools defined by this plugin.
    pub fn tool_count(&self) -> usize {
        self.manifest.tools.len()
    }
}

/// Plugin system configuration, typically stored within the main config.json.
///
/// Controls whether the plugin system is active, which directories are
/// scanned for plugins, and which plugins are allowed or blocked.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginConfig {
    /// Whether the plugin system is enabled. Defaults to false.
    #[serde(default)]
    pub enabled: bool,

    /// Directories to scan for plugin subdirectories.
    /// Defaults to `["~/.zeptoclaw/plugins"]`.
    #[serde(default = "default_plugin_dirs")]
    pub plugin_dirs: Vec<String>,

    /// Allowlist of plugin names. If empty, all discovered plugins are allowed.
    #[serde(default)]
    pub allowed_plugins: Vec<String>,

    /// Blocklist of plugin names. If empty, no plugins are blocked.
    /// Blocklist takes precedence over allowlist.
    #[serde(default)]
    pub blocked_plugins: Vec<String>,
}

impl Default for PluginConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            plugin_dirs: default_plugin_dirs(),
            allowed_plugins: Vec::new(),
            blocked_plugins: Vec::new(),
        }
    }
}

impl PluginConfig {
    /// Check whether a plugin name is permitted by the allow/block lists.
    ///
    /// A plugin is permitted if:
    /// - It is not in the blocked list, AND
    /// - The allowed list is empty (all plugins allowed) OR the plugin is in the allowed list.
    pub fn is_plugin_permitted(&self, name: &str) -> bool {
        if self.blocked_plugins.contains(&name.to_string()) {
            return false;
        }
        if self.allowed_plugins.is_empty() {
            return true;
        }
        self.allowed_plugins.contains(&name.to_string())
    }
}

/// Returns the default plugin directories.
fn default_plugin_dirs() -> Vec<String> {
    vec!["~/.zeptoclaw/plugins".to_string()]
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_plugin_manifest_serialization_roundtrip() {
        let manifest = PluginManifest {
            name: "test-plugin".to_string(),
            version: "1.0.0".to_string(),
            description: "A test plugin".to_string(),
            author: Some("Tester".to_string()),
            tools: vec![PluginToolDef {
                name: "test_tool".to_string(),
                description: "A test tool".to_string(),
                parameters: json!({
                    "type": "object",
                    "properties": {
                        "input": { "type": "string" }
                    },
                    "required": ["input"]
                }),
                command: "echo {{input}}".to_string(),
                working_dir: None,
                timeout_secs: Some(15),
                env: None,
                category: None,
            }],
            execution: "command".to_string(),
            binary: None,
        };

        let json_str = serde_json::to_string(&manifest).unwrap();
        let deserialized: PluginManifest = serde_json::from_str(&json_str).unwrap();

        assert_eq!(deserialized.name, "test-plugin");
        assert_eq!(deserialized.version, "1.0.0");
        assert_eq!(deserialized.description, "A test plugin");
        assert_eq!(deserialized.author, Some("Tester".to_string()));
        assert_eq!(deserialized.tools.len(), 1);
        assert_eq!(deserialized.tools[0].name, "test_tool");
        assert_eq!(deserialized.tools[0].timeout_secs, Some(15));
    }

    #[test]
    fn test_plugin_manifest_deserialization_from_json() {
        let json_str = r#"{
            "name": "git-tools",
            "version": "1.0.0",
            "description": "Git integration tools",
            "author": "ZeptoClaw",
            "tools": [
                {
                    "name": "git_status",
                    "description": "Get git status",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "path": { "type": "string" }
                        },
                        "required": ["path"]
                    },
                    "command": "git -C {{path}} status --porcelain",
                    "timeout_secs": 10
                }
            ]
        }"#;

        let manifest: PluginManifest = serde_json::from_str(json_str).unwrap();
        assert_eq!(manifest.name, "git-tools");
        assert_eq!(
            manifest.tools[0].command,
            "git -C {{path}} status --porcelain"
        );
    }

    #[test]
    fn test_plugin_tool_def_defaults() {
        let json_str = r#"{
            "name": "simple_tool",
            "description": "A simple tool",
            "parameters": { "type": "object", "properties": {} },
            "command": "echo hello"
        }"#;

        let tool_def: PluginToolDef = serde_json::from_str(json_str).unwrap();
        assert_eq!(tool_def.name, "simple_tool");
        assert!(tool_def.working_dir.is_none());
        assert!(tool_def.timeout_secs.is_none());
        assert!(tool_def.env.is_none());
        assert_eq!(tool_def.effective_timeout(), 30);
    }

    #[test]
    fn test_plugin_tool_def_effective_timeout() {
        let tool = PluginToolDef {
            name: "t".to_string(),
            description: "d".to_string(),
            parameters: json!({}),
            command: "echo".to_string(),
            working_dir: None,
            timeout_secs: Some(60),
            env: None,
            category: None,
        };
        assert_eq!(tool.effective_timeout(), 60);

        let tool_default = PluginToolDef {
            name: "t".to_string(),
            description: "d".to_string(),
            parameters: json!({}),
            command: "echo".to_string(),
            working_dir: None,
            timeout_secs: None,
            env: None,
            category: None,
        };
        assert_eq!(tool_default.effective_timeout(), 30);
    }

    #[test]
    fn test_plugin_tool_def_with_env() {
        let mut env = HashMap::new();
        env.insert("FOO".to_string(), "bar".to_string());
        env.insert("BAZ".to_string(), "qux".to_string());

        let tool = PluginToolDef {
            name: "env_tool".to_string(),
            description: "Tool with env".to_string(),
            parameters: json!({}),
            command: "printenv FOO".to_string(),
            working_dir: Some("/tmp".to_string()),
            timeout_secs: Some(5),
            env: Some(env),
            category: None,
        };

        assert_eq!(tool.env.as_ref().unwrap().get("FOO").unwrap(), "bar");
        assert_eq!(tool.working_dir.as_deref(), Some("/tmp"));
    }

    #[test]
    fn test_plugin_config_defaults() {
        let config = PluginConfig::default();
        assert!(!config.enabled);
        assert_eq!(config.plugin_dirs, vec!["~/.zeptoclaw/plugins"]);
        assert!(config.allowed_plugins.is_empty());
        assert!(config.blocked_plugins.is_empty());
    }

    #[test]
    fn test_plugin_config_deserialization_defaults() {
        let json_str = r#"{}"#;
        let config: PluginConfig = serde_json::from_str(json_str).unwrap();
        assert!(!config.enabled);
        assert_eq!(config.plugin_dirs, vec!["~/.zeptoclaw/plugins"]);
        assert!(config.allowed_plugins.is_empty());
        assert!(config.blocked_plugins.is_empty());
    }

    #[test]
    fn test_plugin_config_is_plugin_permitted_all_allowed() {
        let config = PluginConfig::default();
        assert!(config.is_plugin_permitted("any-plugin"));
        assert!(config.is_plugin_permitted("another-plugin"));
    }

    #[test]
    fn test_plugin_config_is_plugin_permitted_allowlist() {
        let config = PluginConfig {
            enabled: true,
            plugin_dirs: vec![],
            allowed_plugins: vec!["good-plugin".to_string()],
            blocked_plugins: vec![],
        };
        assert!(config.is_plugin_permitted("good-plugin"));
        assert!(!config.is_plugin_permitted("other-plugin"));
    }

    #[test]
    fn test_plugin_config_is_plugin_permitted_blocklist() {
        let config = PluginConfig {
            enabled: true,
            plugin_dirs: vec![],
            allowed_plugins: vec![],
            blocked_plugins: vec!["bad-plugin".to_string()],
        };
        assert!(!config.is_plugin_permitted("bad-plugin"));
        assert!(config.is_plugin_permitted("good-plugin"));
    }

    #[test]
    fn test_plugin_config_blocklist_overrides_allowlist() {
        let config = PluginConfig {
            enabled: true,
            plugin_dirs: vec![],
            allowed_plugins: vec!["my-plugin".to_string()],
            blocked_plugins: vec!["my-plugin".to_string()],
        };
        // Blocklist takes precedence
        assert!(!config.is_plugin_permitted("my-plugin"));
    }

    #[test]
    fn test_plugin_struct_construction() {
        let manifest = PluginManifest {
            name: "test-plugin".to_string(),
            version: "0.1.0".to_string(),
            description: "Test".to_string(),
            author: None,
            tools: vec![PluginToolDef {
                name: "t".to_string(),
                description: "d".to_string(),
                parameters: json!({}),
                command: "echo".to_string(),
                working_dir: None,
                timeout_secs: None,
                env: None,
                category: None,
            }],
            execution: "command".to_string(),
            binary: None,
        };

        let plugin = Plugin::new(manifest, PathBuf::from("/tmp/test-plugin"));
        assert_eq!(plugin.name(), "test-plugin");
        assert!(plugin.enabled);
        assert_eq!(plugin.path, PathBuf::from("/tmp/test-plugin"));
        assert_eq!(plugin.tool_count(), 1);
    }

    #[test]
    fn test_plugin_manifest_without_author() {
        let json_str = r#"{
            "name": "minimal",
            "version": "1.0.0",
            "description": "Minimal plugin",
            "tools": [
                {
                    "name": "noop",
                    "description": "Does nothing",
                    "parameters": { "type": "object", "properties": {} },
                    "command": "true"
                }
            ]
        }"#;

        let manifest: PluginManifest = serde_json::from_str(json_str).unwrap();
        assert!(manifest.author.is_none());
        assert_eq!(manifest.tools.len(), 1);
    }

    #[test]
    fn test_plugin_tool_parameter_schema() {
        let tool = PluginToolDef {
            name: "search".to_string(),
            description: "Search files".to_string(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Search query"
                    },
                    "max_results": {
                        "type": "integer",
                        "description": "Maximum results",
                        "default": 10
                    }
                },
                "required": ["query"]
            }),
            command: "grep -r {{query}}".to_string(),
            working_dir: None,
            timeout_secs: None,
            env: None,
            category: None,
        };

        let params = &tool.parameters;
        assert_eq!(params["type"], "object");
        assert!(params["properties"]["query"].is_object());
        assert!(params["properties"]["max_results"].is_object());
        assert_eq!(params["required"][0], "query");
    }

    // ---- Binary plugin types tests ----

    #[test]
    fn test_manifest_default_execution_is_command() {
        let json_str = r#"{
            "name": "basic-plugin",
            "version": "1.0.0",
            "description": "Basic",
            "tools": [{
                "name": "t",
                "description": "d",
                "parameters": {},
                "command": "echo"
            }]
        }"#;
        let manifest: PluginManifest = serde_json::from_str(json_str).unwrap();
        assert_eq!(manifest.execution, "command");
        assert!(manifest.binary.is_none());
        assert!(!manifest.is_binary());
    }

    #[test]
    fn test_manifest_binary_deserialization() {
        let json_str = r#"{
            "name": "bin-plugin",
            "version": "1.0.0",
            "description": "Binary plugin",
            "execution": "binary",
            "binary": {
                "path": "bin/my-plugin",
                "protocol": "jsonrpc",
                "timeout_secs": 60
            },
            "tools": [{
                "name": "my_tool",
                "description": "Does stuff",
                "parameters": {"type": "object", "properties": {}}
            }]
        }"#;
        let manifest: PluginManifest = serde_json::from_str(json_str).unwrap();
        assert_eq!(manifest.execution, "binary");
        assert!(manifest.is_binary());
        let bin = manifest.binary.unwrap();
        assert_eq!(bin.path, "bin/my-plugin");
        assert_eq!(bin.protocol, "jsonrpc");
        assert_eq!(bin.timeout_secs, Some(60));
        // command defaults to empty for binary plugins
        assert_eq!(manifest.tools[0].command, "");
    }

    #[test]
    fn test_manifest_binary_config_defaults() {
        let json_str = r#"{
            "name": "bin-plugin",
            "version": "1.0.0",
            "description": "Minimal binary",
            "execution": "binary",
            "binary": { "path": "plugin" },
            "tools": [{
                "name": "t",
                "description": "d",
                "parameters": {}
            }]
        }"#;
        let manifest: PluginManifest = serde_json::from_str(json_str).unwrap();
        let bin = manifest.binary.unwrap();
        assert_eq!(bin.protocol, "jsonrpc");
        assert!(bin.timeout_secs.is_none());
    }

    #[test]
    fn test_manifest_is_binary() {
        let command_manifest = PluginManifest {
            name: "cmd".to_string(),
            version: "1.0.0".to_string(),
            description: "Command".to_string(),
            author: None,
            tools: vec![],
            execution: "command".to_string(),
            binary: None,
        };
        assert!(!command_manifest.is_binary());

        let binary_manifest = PluginManifest {
            name: "bin".to_string(),
            version: "1.0.0".to_string(),
            description: "Binary".to_string(),
            author: None,
            tools: vec![],
            execution: "binary".to_string(),
            binary: Some(BinaryPluginConfig {
                path: "plugin".to_string(),
                protocol: "jsonrpc".to_string(),
                timeout_secs: None,
                sha256: None,
            }),
        };
        assert!(binary_manifest.is_binary());
    }

    #[test]
    fn test_manifest_backward_compat_no_execution_field() {
        // Old-style manifests without execution/binary fields should still work
        let json_str = r#"{
            "name": "old-plugin",
            "version": "1.0.0",
            "description": "Old style",
            "tools": [{
                "name": "old_tool",
                "description": "Old tool",
                "parameters": {},
                "command": "echo hello"
            }]
        }"#;
        let manifest: PluginManifest = serde_json::from_str(json_str).unwrap();
        assert_eq!(manifest.execution, "command");
        assert!(manifest.binary.is_none());
        assert!(!manifest.is_binary());
        assert_eq!(manifest.tools[0].command, "echo hello");
    }

    #[test]
    fn test_plugin_tool_def_with_category() {
        let json_str = r#"{
            "name": "gcal",
            "description": "Google Calendar",
            "parameters": {},
            "category": "network_write"
        }"#;
        let def: PluginToolDef = serde_json::from_str(json_str).unwrap();
        assert_eq!(def.category, Some(ToolCategory::NetworkWrite));
        assert_eq!(def.effective_category(), ToolCategory::NetworkWrite);
    }

    #[test]
    fn test_plugin_tool_def_category_defaults_to_shell() {
        let json_str = r#"{
            "name": "tool",
            "description": "desc",
            "parameters": {},
            "command": "echo"
        }"#;
        let def: PluginToolDef = serde_json::from_str(json_str).unwrap();
        assert!(def.category.is_none());
        assert_eq!(def.effective_category(), ToolCategory::Shell);
    }
}