Skip to main content

microclaw_engine/internal/tool_runtime/
command_runner.rs

1use std::path::Path;
2
3pub struct CommandSpec {
4    pub program: String,
5    pub args: Vec<String>,
6    /// Landlock rules applied to the child before `exec` (local sandbox
7    /// fallback on Linux without bubblewrap).
8    pub landlock: Option<std::sync::Arc<crate::internal::tool_runtime::landlock::Ruleset>>,
9}
10
11pub fn shell_command(command: &str) -> CommandSpec {
12    if cfg!(target_os = "windows") {
13        CommandSpec {
14            program: "powershell".to_string(),
15            args: vec![
16                "-NoProfile".to_string(),
17                "-NonInteractive".to_string(),
18                "-Command".to_string(),
19                command.to_string(),
20            ],
21            landlock: None,
22        }
23    } else {
24        let shell = std::env::var("SHELL")
25            .ok()
26            .filter(|s| !s.trim().is_empty())
27            .unwrap_or_else(|| "/bin/sh".to_string());
28        CommandSpec {
29            program: shell,
30            args: vec!["-c".to_string(), command.to_string()],
31            landlock: None,
32        }
33    }
34}
35
36pub fn agent_browser_program() -> String {
37    if cfg!(target_os = "windows") {
38        "agent-browser.cmd".to_string()
39    } else {
40        "agent-browser".to_string()
41    }
42}
43
44pub fn build_command(spec: &CommandSpec, working_dir: Option<&Path>) -> tokio::process::Command {
45    let mut cmd = tokio::process::Command::new(&spec.program);
46    cmd.args(&spec.args);
47    if let Some(dir) = working_dir {
48        cmd.current_dir(dir);
49    }
50    #[cfg(target_os = "linux")]
51    if let Some(rules) = spec.landlock.clone() {
52        // SAFETY: restrict_self only issues prctl/landlock system calls,
53        // which are async-signal-safe between fork and exec.
54        unsafe {
55            cmd.pre_exec(move || rules.restrict_self());
56        }
57    }
58    cmd
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_shell_command_shape() {
67        let spec = shell_command("echo hello");
68        assert!(!spec.program.is_empty());
69        assert!(!spec.args.is_empty());
70    }
71
72    #[test]
73    fn test_agent_browser_program_not_empty() {
74        let p = agent_browser_program();
75        assert!(!p.trim().is_empty());
76    }
77}