echo_execution 0.1.3

Execution layer for echo-agent framework (sandbox, skills, tools)
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
//! RunSkillScriptTool -- execute scripts bundled with skills (Tier 3).
//!
//! Many real-world skills contain Python/Node/Shell scripts in their `scripts/`
//! directory. This tool lets the LLM execute them directly within the correct
//! working directory (the skill's root), with proper interpreter detection.
//!
//! ## Sandbox integration
//!
//! All script execution goes through [`SandboxManager`], which automatically
//! selects the best isolation level based on security policy:
//!
//! | Command type | Typical isolation |
//! |-------------|-------------------|
//! | `ls`, `cat`, `echo` | None (trusted) |
//! | `python3 script.py` | OS sandbox |
//! | Unknown / dangerous | Docker container |
//!
//! If no `SandboxManager` is configured, falls back to bare process spawning
//! with a minimal environment whitelist (`env_clear()` + PATH / SKILL_DIR / SESSION_ID)
//! and best-effort timeout termination (`kill_on_drop(true)`).
//!
//! ## Cross-platform interpreter detection
//!
//! | Extension | Unix | Windows |
//! |-----------|------|---------|
//! | `.py` | `python3 script.py` | `python script.py` |
//! | `.js` | `node script.js` | `node script.js` |
//! | `.ts` | `bun` / `deno` / `npx tsx` | same detection |
//! | `.sh` | `bash script.sh` | Git Bash -> PowerShell fallback |
//! | `.ps1` | `pwsh script.ps1` | `powershell script.ps1` |
//! | `.rb` | `ruby script.rb` | `ruby script.rb` |
//!
//! ## Security model
//!
//! - Only scripts from **activated** skills can be run
//! - Script paths must be relative and must canonicalize under the activated skill directory
//! - Interpreter is invoked directly (no shell wrapping)
//! - Configurable timeout (default 30 seconds)
//! - Full sandbox integration with policy-based routing
//! - Malformed `args` strings are rejected instead of being silently reinterpreted

use std::path::{Path, PathBuf};
use std::sync::Arc;

use futures::future::BoxFuture;
use serde_json::json;
use tokio::sync::RwLock;

use crate::sandbox::{SandboxCommand, SandboxManager};
use crate::skills::minimal_env;
use crate::skills::registry::SkillRegistry;
use echo_core::error::{Result, ToolError};
use echo_core::tools::{Tool, ToolParameters, ToolResult};

const DEFAULT_TIMEOUT_SECS: u64 = 30;

/// Tool for executing scripts from activated skill directories.
///
/// See the [module-level docs](self) for cross-platform behavior and security model.
pub struct RunSkillScriptTool {
    registry: Arc<RwLock<SkillRegistry>>,
    sandbox: Option<Arc<SandboxManager>>,
    timeout_secs: u64,
}

impl RunSkillScriptTool {
    pub fn new(registry: Arc<RwLock<SkillRegistry>>) -> Self {
        Self {
            registry,
            sandbox: None,
            timeout_secs: DEFAULT_TIMEOUT_SECS,
        }
    }

    pub fn with_sandbox_manager(mut self, manager: Arc<SandboxManager>) -> Self {
        self.sandbox = Some(manager);
        self
    }

    pub fn with_timeout(mut self, secs: u64) -> Self {
        self.timeout_secs = secs;
        self
    }
}

impl Tool for RunSkillScriptTool {
    fn name(&self) -> &str {
        "run_skill_script"
    }

    fn description(&self) -> &str {
        "Execute a script from an activated skill's scripts/ directory. \
         The working directory is set to the skill's root. \
         Supports Python (.py), Node.js (.js/.ts), Bash (.sh), PowerShell (.ps1), \
         Ruby (.rb), Perl (.pl). \
         The skill must be activated first via activate_skill."
    }

    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "skill_name": {
                    "type": "string",
                    "description": "Name of the activated skill"
                },
                "script": {
                    "type": "string",
                    "description": "Relative path to the script (e.g., 'scripts/analyze.py')"
                },
                "args": {
                    "type": "string",
                    "description": "Command-line arguments to pass to the script (optional)",
                    "default": ""
                }
            },
            "required": ["skill_name", "script"]
        })
    }

    fn execute(&self, parameters: ToolParameters) -> BoxFuture<'_, Result<ToolResult>> {
        Box::pin(async move {
            let skill_name = parameters
                .get("skill_name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::MissingParameter("skill_name".to_string()))?
                .to_string();

            let script_path = parameters
                .get("script")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ToolError::MissingParameter("script".to_string()))?
                .to_string();

            let args_str = parameters
                .get("args")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();

            let script_relative_path = Path::new(&script_path);
            if script_relative_path.is_absolute()
                || script_relative_path
                    .components()
                    .any(|component| matches!(component, std::path::Component::ParentDir))
            {
                return Ok(ToolResult::error(
                    "Script path must be a relative path inside the activated skill directory",
                ));
            }

            let registry = self.registry.read().await;

            if !registry.is_activated(&skill_name) {
                return Ok(ToolResult::error(format!(
                    "Skill '{}' has not been activated. Call activate_skill first.",
                    skill_name
                )));
            }

            let descriptor = match registry.get_descriptor(&skill_name) {
                Some(d) => d,
                None => {
                    return Ok(ToolResult::error(format!(
                        "Skill '{}' not found in catalog",
                        skill_name
                    )));
                }
            };

            if !descriptor.permits_tool(self.name()) {
                return Ok(ToolResult::error(format!(
                    "Skill '{}' does not permit tool '{}'; allowed-tools: {}",
                    skill_name,
                    self.name(),
                    descriptor.allowed_tools.join(", ")
                )));
            }

            let skill_dir = match descriptor.location.parent() {
                Some(d) => d.to_path_buf(),
                None => {
                    return Ok(ToolResult::error(format!(
                        "Cannot determine skill directory for '{}'",
                        skill_name
                    )));
                }
            };

            let canonical_skill_dir = match skill_dir.canonicalize() {
                Ok(path) => path,
                Err(e) => {
                    return Ok(ToolResult::error(format!(
                        "Cannot canonicalize skill directory for '{}': {}",
                        skill_name, e
                    )));
                }
            };
            let full_script_path = canonical_skill_dir.join(script_relative_path);
            let canonical_script_path = match full_script_path.canonicalize() {
                Ok(path) => path,
                Err(e) => {
                    return Ok(ToolResult::error(format!(
                        "Cannot canonicalize script '{}': {}",
                        script_path, e
                    )));
                }
            };

            if !canonical_script_path.starts_with(&canonical_skill_dir) {
                return Ok(ToolResult::error(
                    "Resolved script path escapes the skill directory",
                ));
            }

            if !canonical_script_path.exists() {
                return Ok(ToolResult::error(format!(
                    "Script not found: {} (in skill '{}')",
                    script_path, skill_name
                )));
            }

            // Resolve interpreter from script extension
            let invocation = resolve_interpreter(&script_path);

            // Build argument list: [prefix_args...] <script_path> [user_args...]
            let mut all_args: Vec<String> = invocation.prefix_args.to_vec();
            all_args.push(canonical_script_path.display().to_string());
            if !args_str.is_empty() {
                let parsed =
                    shlex::split(&args_str).ok_or_else(|| ToolError::InvalidParameter {
                        name: "args".to_string(),
                        message: "Malformed script arguments: unmatched quotes or escapes"
                            .to_string(),
                    })?;
                all_args.extend(parsed);
            }

            let timeout = std::time::Duration::from_secs(self.timeout_secs);

            // -- Sandbox execution path --
            if let Some(ref manager) = self.sandbox {
                let sandbox_cmd = SandboxCommand::program(&invocation.program, all_args)
                    .with_working_dir(&canonical_skill_dir)
                    .with_timeout(timeout);

                return match manager.execute(sandbox_cmd).await {
                    Ok(result) => format_execution_result(
                        &skill_name,
                        &script_path,
                        result.exit_code,
                        &result.stdout,
                        &result.stderr,
                        &result.sandbox_type,
                    ),
                    Err(e) => Ok(ToolResult::error(format!(
                        "Sandbox execution failed for '{}' in skill '{}': {}",
                        script_path, skill_name, e
                    ))),
                };
            }

            // -- Fallback: direct process execution (no sandbox) --
            let mut cmd = tokio::process::Command::new(&invocation.program);
            for arg in &all_args {
                cmd.arg(arg);
            }
            cmd.current_dir(&canonical_skill_dir);
            cmd.kill_on_drop(true);

            // Use minimal environment to avoid leaking sensitive variables
            let env = minimal_env(
                &canonical_skill_dir.display().to_string(),
                "", // no session_id needed for script execution
                std::collections::HashMap::new(),
            );
            cmd.env_clear();
            for (k, v) in env {
                cmd.env(k, v);
            }

            match tokio::time::timeout(timeout, cmd.output()).await {
                Ok(Ok(output)) => {
                    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
                    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
                    format_execution_result(
                        &skill_name,
                        &script_path,
                        output.status.code().unwrap_or(-1),
                        &stdout,
                        &stderr,
                        "direct",
                    )
                }
                Ok(Err(e)) => Ok(ToolResult::error(format!(
                    "Failed to execute '{}' in skill '{}': {}. \
                     Ensure the interpreter is installed and on PATH.",
                    script_path, skill_name, e
                ))),
                Err(_) => Ok(ToolResult::error(format!(
                    "Script '{}' in skill '{}' timed out after {}s",
                    script_path, skill_name, self.timeout_secs
                ))),
            }
        })
    }
}

// -- Interpreter Resolution --

/// Resolved invocation: how to run a script file.
struct Invocation {
    /// The executable to call (e.g. `python3`, `node`, `bash`).
    program: String,
    /// Arguments inserted between the program and the script path.
    prefix_args: Vec<String>,
}

/// Resolve the interpreter invocation for a script path, with cross-platform awareness.
fn resolve_interpreter(script_path: &str) -> Invocation {
    let ext = script_path
        .rsplit('.')
        .next()
        .unwrap_or("")
        .to_ascii_lowercase();

    match ext.as_str() {
        "py" => resolve_python(),
        "js" | "mjs" | "cjs" => Invocation::simple("node"),
        "ts" | "mts" | "tsx" => resolve_typescript(),
        "sh" | "bash" => resolve_shell(),
        "ps1" => resolve_powershell(),
        "rb" => Invocation::simple("ruby"),
        "pl" => Invocation::simple("perl"),
        "php" => Invocation::simple("php"),
        "r" | "R" => Invocation::new("Rscript", vec![]),
        _ => resolve_shell(), // unknown extension -> try shell
    }
}

impl Invocation {
    fn simple(program: &str) -> Self {
        Self {
            program: program.into(),
            prefix_args: vec![],
        }
    }

    fn new(program: &str, prefix_args: Vec<&str>) -> Self {
        Self {
            program: program.into(),
            prefix_args: prefix_args.into_iter().map(String::from).collect(),
        }
    }
}

/// Python: `python3` on Unix, `python` on Windows.
fn resolve_python() -> Invocation {
    if cfg!(target_os = "windows") {
        if which_exists("python") {
            Invocation::simple("python")
        } else {
            Invocation::new("py", vec!["-3"])
        }
    } else {
        if which_exists("python3") {
            Invocation::simple("python3")
        } else {
            Invocation::simple("python")
        }
    }
}

/// TypeScript: `bun` -> `deno run` -> `npx tsx`.
fn resolve_typescript() -> Invocation {
    if which_exists("bun") {
        return Invocation::simple("bun");
    }
    if which_exists("deno") {
        return Invocation::new("deno", vec!["run", "--allow-read", "--allow-env"]);
    }
    Invocation::new("npx", vec!["tsx"])
}

/// Shell scripts (.sh/.bash): bash on Unix, Git Bash -> PowerShell on Windows.
fn resolve_shell() -> Invocation {
    if cfg!(target_os = "windows") {
        if let Some(git_bash) = find_git_bash() {
            return Invocation::simple(git_bash.to_str().unwrap_or("bash"));
        }
        if which_exists("wsl") {
            return Invocation::new("wsl", vec!["bash"]);
        }
        resolve_powershell()
    } else {
        Invocation::simple("bash")
    }
}

/// PowerShell: `pwsh` (cross-platform PS 7+) -> `powershell` (Windows built-in).
fn resolve_powershell() -> Invocation {
    if which_exists("pwsh") {
        Invocation::new("pwsh", vec!["-NoProfile", "-NonInteractive", "-File"])
    } else if cfg!(target_os = "windows") {
        Invocation::new(
            "powershell",
            vec![
                "-NoProfile",
                "-NonInteractive",
                "-ExecutionPolicy",
                "Bypass",
                "-File",
            ],
        )
    } else {
        Invocation::simple("sh")
    }
}

/// Find Git Bash on Windows.
#[cfg(target_os = "windows")]
fn find_git_bash() -> Option<PathBuf> {
    let candidates = [
        std::env::var("ProgramFiles")
            .ok()
            .map(|p| PathBuf::from(p).join("Git").join("bin").join("bash.exe")),
        std::env::var("ProgramFiles(x86)")
            .ok()
            .map(|p| PathBuf::from(p).join("Git").join("bin").join("bash.exe")),
        Some(PathBuf::from(r"C:\Program Files\Git\bin\bash.exe")),
        Some(PathBuf::from(r"C:\Program Files (x86)\Git\bin\bash.exe")),
    ];

    for candidate in candidates.into_iter().flatten() {
        if candidate.exists() {
            return Some(candidate);
        }
    }

    if which_exists("bash") {
        return Some(PathBuf::from("bash"));
    }

    None
}

#[cfg(not(target_os = "windows"))]
fn find_git_bash() -> Option<PathBuf> {
    None
}

// -- Utilities --

/// Check if a command exists on PATH.
fn which_exists(cmd: &str) -> bool {
    std::process::Command::new(cmd)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

/// Format execution output into a structured result.
fn format_execution_result(
    skill_name: &str,
    script_path: &str,
    exit_code: i32,
    stdout: &str,
    stderr: &str,
    sandbox_type: &str,
) -> Result<ToolResult> {
    let mut output = format!(
        "<script_output skill=\"{}\" script=\"{}\" exit_code=\"{}\" sandbox=\"{}\">\n",
        skill_name, script_path, exit_code, sandbox_type,
    );

    if !stdout.is_empty() {
        output.push_str(stdout);
        if !stdout.ends_with('\n') {
            output.push('\n');
        }
    }

    if !stderr.is_empty() {
        output.push_str(&format!("\n<stderr>\n{}</stderr>\n", stderr.trim()));
    }

    output.push_str("</script_output>");

    if exit_code == 0 {
        Ok(ToolResult::success(output))
    } else {
        Ok(ToolResult {
            success: false,
            output,
            error: Some(format!(
                "Script '{}' exited with code {}",
                script_path, exit_code
            )),
            bytes: None,
            data: None,
        })
    }
}

// -- Tests --

#[cfg(test)]
mod tests {
    use super::*;
    use crate::skills::external::types::SkillDescriptor;
    use crate::skills::registry::SkillRegistry;
    use std::collections::HashMap;

    #[test]
    fn test_resolve_python() {
        let inv = resolve_python();
        assert!(
            inv.program == "python3" || inv.program == "python" || inv.program == "py",
            "unexpected python program: {}",
            inv.program
        );
    }

    #[test]
    fn test_resolve_typescript() {
        let inv = resolve_typescript();
        assert!(
            inv.program == "bun" || inv.program == "deno" || inv.program == "npx",
            "unexpected ts program: {}",
            inv.program
        );
    }

    #[test]
    fn test_resolve_shell() {
        let inv = resolve_shell();
        if cfg!(target_os = "windows") {
            assert!(
                inv.program.contains("bash")
                    || inv.program == "wsl"
                    || inv.program == "pwsh"
                    || inv.program == "powershell",
                "unexpected shell program: {}",
                inv.program
            );
        } else {
            assert_eq!(inv.program, "bash");
        }
    }

    #[test]
    fn test_resolve_powershell() {
        let inv = resolve_powershell();
        assert!(
            inv.program == "pwsh" || inv.program == "powershell" || inv.program == "sh",
            "unexpected ps program: {}",
            inv.program
        );
    }

    #[test]
    fn test_resolve_interpreter_extensions() {
        assert_eq!(resolve_interpreter("test.js").program, "node");
        assert_eq!(resolve_interpreter("test.rb").program, "ruby");
        assert_eq!(resolve_interpreter("test.pl").program, "perl");
        assert_eq!(resolve_interpreter("test.php").program, "php");
        assert_eq!(resolve_interpreter("test.R").program, "Rscript");
    }

    #[test]
    fn test_shlex_split_simple() {
        let result = shlex::split("--input data.csv --output result.json");
        assert_eq!(
            result,
            Some(vec![
                "--input".to_string(),
                "data.csv".to_string(),
                "--output".to_string(),
                "result.json".to_string(),
            ])
        );
    }

    #[test]
    fn test_shlex_split_quotes() {
        let result = shlex::split(r#"--name "hello world" --verbose"#);
        assert_eq!(
            result,
            Some(vec![
                "--name".to_string(),
                "hello world".to_string(),
                "--verbose".to_string(),
            ])
        );
    }

    #[test]
    fn test_shlex_split_empty() {
        assert!(shlex::split("").unwrap_or_default().is_empty());
        assert!(shlex::split("   ").unwrap_or_default().is_empty());
    }

    #[test]
    fn test_shlex_split_malformed() {
        assert!(shlex::split(r#"--name "unterminated"#).is_none());
    }

    #[test]
    fn test_invocation_no_longer_has_shell_prefix() {
        let inv = Invocation::simple("python3");
        assert_eq!(inv.program, "python3");
        assert!(inv.prefix_args.is_empty());
    }

    #[tokio::test]
    async fn run_skill_script_enforces_allowed_tools() {
        let root =
            std::env::temp_dir().join(format!("echo-skill-script-test-{}", std::process::id()));
        let skill_dir = root.join("locked-skill");
        tokio::fs::create_dir_all(skill_dir.join("scripts"))
            .await
            .unwrap();
        tokio::fs::write(skill_dir.join("SKILL.md"), "body")
            .await
            .unwrap();
        tokio::fs::write(skill_dir.join("scripts/test.py"), "print('hi')\n")
            .await
            .unwrap();

        let mut registry = SkillRegistry::new();
        registry.register_descriptor(SkillDescriptor {
            name: "locked-skill".into(),
            description: "desc".into(),
            location: skill_dir.join("SKILL.md"),
            license: None,
            compatibility: None,
            metadata: HashMap::new(),
            allowed_tools: vec!["read_skill_resource".into()],
            shell: None,
            paths: vec![],
            hooks: None,
        });
        registry.mark_activated("locked-skill");

        let tool = RunSkillScriptTool::new(Arc::new(RwLock::new(registry)));
        let result = tool
            .execute(
                [
                    ("skill_name".to_string(), json!("locked-skill")),
                    ("script".to_string(), json!("scripts/test.py")),
                ]
                .into(),
            )
            .await
            .unwrap();

        assert!(!result.success);
        assert!(
            result
                .error
                .unwrap_or_default()
                .contains("does not permit tool 'run_skill_script'")
        );

        let _ = tokio::fs::remove_dir_all(root).await;
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn test_find_git_bash_returns_something_or_none() {
        let _ = find_git_bash();
    }
}