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        CommandSpec {
25            program: unix_shell().to_string(),
26            args: vec!["-c".to_string(), command.to_string()],
27            landlock: None,
28        }
29    }
30}
31
32/// The shell that runs commands on Unix.
33///
34/// The tool promises bash and models write bash, so bash is used whenever it
35/// is installed. The user's `$SHELL` is not used unless it is bash: zsh (the
36/// macOS default) aborts on an unmatched glob such as `--include=*.rs` and
37/// splits words differently. Without bash, `$SHELL` or `/bin/sh` is used.
38fn unix_shell() -> &'static str {
39    static SHELL: std::sync::OnceLock<String> = std::sync::OnceLock::new();
40    SHELL.get_or_init(|| {
41        let user_shell = std::env::var("SHELL").ok().filter(|s| !s.trim().is_empty());
42        pick_unix_shell(
43            user_shell.as_deref(),
44            std::env::var_os("PATH").as_deref(),
45            |p| p.is_file(),
46        )
47    })
48}
49
50fn pick_unix_shell(
51    user_shell: Option<&str>,
52    path: Option<&std::ffi::OsStr>,
53    exists: impl Fn(&Path) -> bool,
54) -> String {
55    let user_bash = user_shell.filter(|shell| {
56        Path::new(shell).file_name().and_then(|n| n.to_str()) == Some("bash")
57            && exists(Path::new(shell))
58    });
59    if let Some(shell) = user_bash {
60        return shell.to_string();
61    }
62    for candidate in ["/bin/bash", "/usr/bin/bash"] {
63        if exists(Path::new(candidate)) {
64            return candidate.to_string();
65        }
66    }
67    if let Some(path) = path {
68        for dir in std::env::split_paths(path) {
69            let candidate = dir.join("bash");
70            if exists(&candidate) {
71                return candidate.to_string_lossy().into_owned();
72            }
73        }
74    }
75    user_shell.unwrap_or("/bin/sh").to_string()
76}
77
78pub fn agent_browser_program() -> String {
79    if cfg!(target_os = "windows") {
80        "agent-browser.cmd".to_string()
81    } else {
82        "agent-browser".to_string()
83    }
84}
85
86pub fn build_command(spec: &CommandSpec, working_dir: Option<&Path>) -> tokio::process::Command {
87    let mut cmd = tokio::process::Command::new(&spec.program);
88    cmd.args(&spec.args);
89    if let Some(dir) = working_dir {
90        cmd.current_dir(dir);
91    }
92    #[cfg(target_os = "linux")]
93    if let Some(rules) = spec.landlock.clone() {
94        // SAFETY: restrict_self only issues prctl/landlock system calls,
95        // which are async-signal-safe between fork and exec.
96        unsafe {
97            cmd.pre_exec(move || rules.restrict_self());
98        }
99    }
100    cmd
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn test_shell_command_shape() {
109        let spec = shell_command("echo hello");
110        assert!(!spec.program.is_empty());
111        assert!(!spec.args.is_empty());
112    }
113
114    #[test]
115    fn test_pick_unix_shell_prefers_bash() {
116        let only = |paths: &'static [&'static str]| {
117            move |p: &Path| paths.iter().any(|x| Path::new(x) == p)
118        };
119        // zsh as the login shell still runs commands in bash.
120        assert_eq!(
121            pick_unix_shell(Some("/bin/zsh"), None, only(&["/bin/zsh", "/bin/bash"])),
122            "/bin/bash"
123        );
124        // A bash login shell (e.g. a newer Homebrew bash) is kept.
125        assert_eq!(
126            pick_unix_shell(
127                Some("/opt/homebrew/bin/bash"),
128                None,
129                only(&["/opt/homebrew/bin/bash", "/bin/bash"])
130            ),
131            "/opt/homebrew/bin/bash"
132        );
133        // NixOS-style: no /bin/bash, bash on PATH.
134        let path = std::ffi::OsString::from("/run/current-system/sw/bin:/usr/bin");
135        assert_eq!(
136            pick_unix_shell(
137                Some("/bin/zsh"),
138                Some(&path),
139                only(&["/run/current-system/sw/bin/bash"])
140            ),
141            "/run/current-system/sw/bin/bash"
142        );
143        // No bash at all: the login shell, then /bin/sh.
144        assert_eq!(
145            pick_unix_shell(Some("/bin/zsh"), None, only(&[])),
146            "/bin/zsh"
147        );
148        assert_eq!(pick_unix_shell(None, None, only(&[])), "/bin/sh");
149    }
150
151    #[test]
152    fn test_agent_browser_program_not_empty() {
153        let p = agent_browser_program();
154        assert!(!p.trim().is_empty());
155    }
156}