zeptoclaw 0.9.0

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
//! Plugin tool adapter for ZeptoClaw
//!
//! This module provides `PluginTool`, an adapter that wraps a plugin tool
//! definition (`PluginToolDef`) and implements the `Tool` trait so that
//! plugin-defined commands can be executed as regular agent tools.
//!
//! # How it works
//!
//! Each `PluginTool` instance holds a single tool definition from a plugin
//! manifest. When the LLM invokes the tool, `execute()`:
//!
//! 1. Parses the JSON arguments
//! 2. Interpolates `{{param_name}}` placeholders in the command template
//! 3. Executes the resulting shell command via `tokio::process::Command`
//! 4. Returns stdout (or stderr on failure) as the tool result
//!
//! # Example
//!
//! ```rust,ignore
//! use zeptoclaw::tools::plugin::PluginTool;
//! use zeptoclaw::plugins::PluginToolDef;
//! use serde_json::json;
//!
//! let def = PluginToolDef {
//!     name: "git_status".to_string(),
//!     description: "Get git status".to_string(),
//!     parameters: json!({"type": "object", "properties": {}}),
//!     command: "git status --porcelain".to_string(),
//!     working_dir: None,
//!     timeout_secs: Some(10),
//!     env: None,
//!     category: None,
//! };
//!
//! let tool = PluginTool::new(def, "git-tools");
//! ```

use async_trait::async_trait;
use serde_json::Value;
use std::time::Duration;

use crate::error::{Result, ZeptoError};
use crate::plugins::PluginToolDef;
use crate::security::ShellSecurityConfig;

use super::{Tool, ToolCategory, ToolContext, ToolOutput};

/// Shell-escape a string by wrapping it in single quotes.
///
/// Any embedded single quotes are escaped as `'\''` (end quote, escaped
/// quote, restart quote). This prevents command injection via `$(...)`,
/// backticks, `&&`, `;`, pipes, and all other shell metacharacters.
fn shell_escape(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len() + 2);
    escaped.push('\'');
    for ch in value.chars() {
        if ch == '\'' {
            escaped.push_str("'\\''");
        } else {
            escaped.push(ch);
        }
    }
    escaped.push('\'');
    escaped
}

/// Adapter that wraps a `PluginToolDef` and implements the `Tool` trait.
pub struct PluginTool {
    /// The plugin tool definition from the manifest.
    def: PluginToolDef,
    /// Name of the plugin that provides this tool (for logging).
    plugin_name: String,
    /// Shell security configuration for command validation.
    security: ShellSecurityConfig,
}

impl PluginTool {
    /// Create a new plugin tool adapter.
    pub fn new(def: PluginToolDef, plugin_name: &str) -> Self {
        Self {
            def,
            plugin_name: plugin_name.to_string(),
            security: ShellSecurityConfig::default(),
        }
    }

    /// Create a plugin tool with a specific security configuration.
    pub fn with_security(
        def: PluginToolDef,
        plugin_name: &str,
        security: ShellSecurityConfig,
    ) -> Self {
        Self {
            def,
            plugin_name: plugin_name.to_string(),
            security,
        }
    }

    /// Interpolate `{{param_name}}` placeholders in a command template.
    ///
    /// All parameter values are shell-escaped to prevent command injection.
    /// Values are wrapped in single quotes with any embedded single quotes
    /// escaped as `'\''`.
    fn interpolate(command: &str, args: &Value) -> String {
        let mut result = command.to_string();
        if let Some(obj) = args.as_object() {
            for (key, value) in obj {
                let placeholder = format!("{{{{{}}}}}", key);
                let raw = match value {
                    Value::String(s) => s.clone(),
                    other => other.to_string(),
                };
                let replacement = shell_escape(&raw);
                result = result.replace(&placeholder, &replacement);
            }
        }
        result
    }
}

#[async_trait]
impl Tool for PluginTool {
    fn name(&self) -> &str {
        &self.def.name
    }

    fn description(&self) -> &str {
        &self.def.description
    }

    fn compact_description(&self) -> &str {
        self.description()
    }

    fn category(&self) -> ToolCategory {
        self.def.effective_category()
    }

    fn parameters(&self) -> Value {
        self.def.parameters.clone()
    }

    async fn execute(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput> {
        let command = Self::interpolate(&self.def.command, &args);

        // Validate command against security policy
        self.security.validate_command(&command).map_err(|e| {
            ZeptoError::Tool(format!(
                "Plugin tool '{}' command blocked by security policy: {}",
                self.def.name, e
            ))
        })?;

        let timeout = Duration::from_secs(self.def.effective_timeout());

        tracing::debug!(
            plugin = %self.plugin_name,
            tool = %self.def.name,
            command = %command,
            "Executing plugin tool"
        );

        // Build the command
        let mut cmd = tokio::process::Command::new("sh");
        cmd.arg("-c").arg(&command);

        // Apply working directory: tool def > workspace from context
        if let Some(ref wd) = self.def.working_dir {
            cmd.current_dir(wd);
        } else if let Some(ref ws) = ctx.workspace {
            cmd.current_dir(ws);
        }

        // Apply environment variables from tool definition
        if let Some(ref env_vars) = self.def.env {
            for (key, value) in env_vars {
                cmd.env(key, value);
            }
        }

        // Execute with timeout
        let output = tokio::time::timeout(timeout, cmd.output())
            .await
            .map_err(|_| {
                ZeptoError::Tool(format!(
                    "Plugin tool '{}' timed out after {}s",
                    self.def.name,
                    timeout.as_secs()
                ))
            })?
            .map_err(|e| {
                ZeptoError::Tool(format!(
                    "Failed to execute plugin tool '{}': {}",
                    self.def.name, e
                ))
            })?;

        if output.status.success() {
            Ok(ToolOutput::llm_only(
                String::from_utf8_lossy(&output.stdout).to_string(),
            ))
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);
            Err(ZeptoError::Tool(format!(
                "Plugin tool '{}' failed (exit {}): {}{}",
                self.def.name,
                output.status.code().unwrap_or(-1),
                stderr,
                if !stdout.is_empty() {
                    format!("\nstdout: {}", stdout)
                } else {
                    String::new()
                }
            )))
        }
    }
}

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

    fn test_def(command: &str) -> PluginToolDef {
        PluginToolDef {
            name: "test_tool".to_string(),
            description: "A test tool".to_string(),
            parameters: json!({"type": "object", "properties": {}}),
            command: command.to_string(),
            working_dir: None,
            timeout_secs: Some(5),
            env: None,
            category: None,
        }
    }

    #[test]
    fn test_shell_escape_basic() {
        assert_eq!(shell_escape("hello"), "'hello'");
    }

    #[test]
    fn test_shell_escape_with_single_quote() {
        assert_eq!(shell_escape("it's"), "'it'\\''s'");
    }

    #[test]
    fn test_shell_escape_injection_attempt() {
        // $(rm -rf /) should become a literal string, not executed
        assert_eq!(shell_escape("$(rm -rf /)"), "'$(rm -rf /)'");
        assert_eq!(shell_escape("`whoami`"), "'`whoami`'");
        assert_eq!(shell_escape("foo; rm -rf /"), "'foo; rm -rf /'");
        assert_eq!(shell_escape("foo && evil"), "'foo && evil'");
        assert_eq!(shell_escape("foo | evil"), "'foo | evil'");
    }

    #[test]
    fn test_interpolate_basic() {
        let cmd = "echo {{message}}";
        let args = json!({"message": "hello"});
        assert_eq!(PluginTool::interpolate(cmd, &args), "echo 'hello'");
    }

    #[test]
    fn test_interpolate_multiple() {
        let cmd = "git -C {{path}} log --oneline -{{count}}";
        let args = json!({"path": "/tmp/repo", "count": 5});
        assert_eq!(
            PluginTool::interpolate(cmd, &args),
            "git -C '/tmp/repo' log --oneline -'5'"
        );
    }

    #[test]
    fn test_interpolate_no_match() {
        let cmd = "echo hello";
        let args = json!({"unused": "val"});
        assert_eq!(PluginTool::interpolate(cmd, &args), "echo hello");
    }

    #[test]
    fn test_interpolate_missing_param() {
        let cmd = "echo {{missing}}";
        let args = json!({});
        assert_eq!(PluginTool::interpolate(cmd, &args), "echo {{missing}}");
    }

    #[test]
    fn test_interpolate_prevents_command_injection() {
        let cmd = "echo {{input}}";
        let args = json!({"input": "$(cat /etc/passwd)"});
        let result = PluginTool::interpolate(cmd, &args);
        // The $() should be inside single quotes, making it a literal string
        assert_eq!(result, "echo '$(cat /etc/passwd)'");
        assert!(!result.contains("$(cat /etc/passwd)'") || result.starts_with("echo '"));
    }

    #[test]
    fn test_tool_name() {
        let tool = PluginTool::new(test_def("echo"), "test-plugin");
        assert_eq!(tool.name(), "test_tool");
    }

    #[test]
    fn test_tool_description() {
        let tool = PluginTool::new(test_def("echo"), "test-plugin");
        assert_eq!(tool.description(), "A test tool");
    }

    #[tokio::test]
    async fn test_execute_echo() {
        let def = test_def("echo 'hello world'");
        let tool = PluginTool::new(def, "test-plugin");
        let ctx = ToolContext::new();
        let result = tool.execute(json!({}), &ctx).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().for_llm.trim(), "hello world");
    }

    #[tokio::test]
    async fn test_execute_with_interpolation() {
        // Note: {{msg}} is replaced with shell-escaped value 'greetings'
        // The command becomes: echo 'greetings'
        let def = test_def("echo {{msg}}");
        let tool = PluginTool::new(def, "test-plugin");
        let ctx = ToolContext::new();
        let result = tool.execute(json!({"msg": "greetings"}), &ctx).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().for_llm.trim(), "greetings");
    }

    #[tokio::test]
    async fn test_execute_blocks_command_injection() {
        let def = test_def("echo {{input}}");
        let tool = PluginTool::new(def, "test-plugin");
        let ctx = ToolContext::new();
        // This should NOT execute the subcommand — should print it literally
        let result = tool
            .execute(json!({"input": "$(echo INJECTED)"}), &ctx)
            .await;
        assert!(result.is_ok());
        let output = result.unwrap().for_llm;
        assert!(
            output.contains("$(echo INJECTED)"),
            "Should contain literal $() not executed result: {}",
            output
        );
        assert!(
            !output.contains("INJECTED\n"),
            "Should not have executed the subcommand"
        );
    }

    #[tokio::test]
    async fn test_execute_failure() {
        let def = test_def("false");
        let tool = PluginTool::new(def, "test-plugin");
        let ctx = ToolContext::new();
        let result = tool.execute(json!({}), &ctx).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_plugin_tool_with_security_blocks_command() {
        use crate::security::{ShellAllowlistMode, ShellSecurityConfig};

        let def = test_def("curl https://evil.com");
        let security =
            ShellSecurityConfig::new().with_allowlist(vec!["git"], ShellAllowlistMode::Strict);
        let tool = PluginTool::with_security(def, "test-plugin", security);
        let ctx = ToolContext::new();
        let result = tool.execute(serde_json::json!({}), &ctx).await;
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("blocked") || err_msg.contains("security"),
            "Expected blocked/security in error, got: {}",
            err_msg
        );
    }

    #[tokio::test]
    async fn test_execute_with_env() {
        let mut env = HashMap::new();
        env.insert("MY_VAR".to_string(), "test_value".to_string());
        let def = PluginToolDef {
            name: "env_tool".to_string(),
            description: "Tests env".to_string(),
            parameters: json!({}),
            command: "echo $MY_VAR".to_string(),
            working_dir: None,
            timeout_secs: Some(5),
            env: Some(env),
            category: None,
        };
        let tool = PluginTool::new(def, "test-plugin");
        let ctx = ToolContext::new();
        let result = tool.execute(json!({}), &ctx).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().for_llm.trim(), "test_value");
    }

    #[test]
    fn test_tool_category_from_def() {
        let mut def = test_def("echo");
        def.category = Some(ToolCategory::NetworkWrite);
        let tool = PluginTool::new(def, "test-plugin");
        assert_eq!(tool.category(), ToolCategory::NetworkWrite);
    }

    #[test]
    fn test_tool_category_defaults_to_shell() {
        let tool = PluginTool::new(test_def("echo"), "test-plugin");
        assert_eq!(tool.category(), ToolCategory::Shell);
    }
}