Skip to main content

lean_ctx/core/
sandbox.rs

1use std::collections::HashMap;
2#[cfg(unix)]
3use std::os::unix::process::CommandExt;
4use std::process::Command;
5
6#[derive(Debug, Clone)]
7pub struct SandboxResult {
8    pub stdout: String,
9    pub stderr: String,
10    pub exit_code: i32,
11    pub language: String,
12    pub duration_ms: u64,
13}
14
15const TIMEOUT_SECS: u64 = 30;
16const MAX_OUTPUT_BYTES: usize = 32_768;
17/// Upper bound on the `code` payload. Generous for real scripts while preventing an
18/// agent from forcing a multi-megabyte temp-file write / interpreter argv → memory abuse.
19const MAX_CODE_BYTES: usize = 256 * 1024;
20
21pub fn execute(language: &str, code: &str, timeout_secs: Option<u64>) -> SandboxResult {
22    execute_in(language, code, timeout_secs, None)
23}
24
25/// Same as [`execute`], but runs the snippet in `cwd` (GH #1666).
26///
27/// A caller that already resolved a working directory — `ctx_shell` rerouting
28/// an interpreter heredoc, for one — must be able to hand it over. Without
29/// this, the snippet inherited the server process's directory while the rest
30/// of the same tool call ran in `cwd`, so relative paths in the snippet
31/// resolved against a different tree and quietly hit the wrong files.
32pub fn execute_in(
33    language: &str,
34    code: &str,
35    timeout_secs: Option<u64>,
36    cwd: Option<&std::path::Path>,
37) -> SandboxResult {
38    if code.len() > MAX_CODE_BYTES {
39        return SandboxResult {
40            stdout: String::new(),
41            stderr: format!(
42                "Code exceeds the {MAX_CODE_BYTES}-byte limit ({} bytes). Split it into smaller scripts.",
43                code.len()
44            ),
45            exit_code: 1,
46            language: language.to_string(),
47            duration_ms: 0,
48        };
49    }
50
51    let timeout = timeout_secs.unwrap_or(TIMEOUT_SECS);
52    let start = std::time::Instant::now();
53
54    let Some(runtime) = resolve_runtime(language) else {
55        return SandboxResult {
56            stdout: String::new(),
57            stderr: format!(
58                "Unsupported language: {language}. Supported: javascript, typescript, python, shell, ruby, go, rust, php, perl, r, elixir"
59            ),
60            exit_code: 1,
61            language: language.to_string(),
62            duration_ms: 0,
63        };
64    };
65
66    let sandbox_level = std::env::var("LEAN_CTX_SANDBOX_LEVEL")
67        .ok()
68        .and_then(|v| v.parse::<u8>().ok())
69        .unwrap_or_else(|| crate::core::config::Config::load().sandbox_level);
70
71    if sandbox_level >= 1 && cfg!(target_os = "macos") {
72        let result = seatbelt_execute(&runtime, code, timeout, cwd);
73        let duration_ms = start.elapsed().as_millis() as u64;
74        return match result {
75            Ok((stdout, stderr, exit_code)) => SandboxResult {
76                stdout: truncate_output(&stdout),
77                stderr: truncate_smart(&stderr, 2048),
78                exit_code,
79                language: language.to_string(),
80                duration_ms,
81            },
82            Err(e) => SandboxResult {
83                stdout: String::new(),
84                stderr: format!("Seatbelt execution error: {e}"),
85                exit_code: 1,
86                language: language.to_string(),
87                duration_ms,
88            },
89        };
90    } else if sandbox_level >= 1 {
91        #[cfg(target_os = "linux")]
92        {
93            let result = landlock_execute(&runtime, code, timeout, cwd);
94            let duration_ms = start.elapsed().as_millis() as u64;
95            return match result {
96                Ok((stdout, stderr, exit_code)) => SandboxResult {
97                    stdout: truncate_output(&stdout),
98                    stderr: truncate_smart(&stderr, 2048),
99                    exit_code,
100                    language: language.to_string(),
101                    duration_ms,
102                },
103                Err(e) => SandboxResult {
104                    stdout: String::new(),
105                    stderr: format!("Landlock execution error: {e}"),
106                    exit_code: 1,
107                    language: language.to_string(),
108                    duration_ms,
109                },
110            };
111        }
112
113        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
114        eprintln!(
115            "[lean-ctx] sandbox_level=1 requested but sandboxing not available on this platform; falling back to Level 0"
116        );
117    }
118
119    let result = if runtime.needs_temp_file {
120        execute_with_file(&runtime, code, timeout, cwd)
121    } else {
122        execute_with_stdin(&runtime, code, timeout, cwd)
123    };
124
125    let duration_ms = start.elapsed().as_millis() as u64;
126
127    match result {
128        Ok((stdout, stderr, code)) => SandboxResult {
129            stdout: truncate_output(&stdout),
130            stderr: truncate_smart(&stderr, 2048),
131            exit_code: code,
132            language: language.to_string(),
133            duration_ms,
134        },
135        Err(e) => SandboxResult {
136            stdout: String::new(),
137            stderr: format!("Execution error: {e}"),
138            exit_code: 1,
139            language: language.to_string(),
140            duration_ms,
141        },
142    }
143}
144
145pub fn batch_execute(items: &[(String, String)]) -> Vec<SandboxResult> {
146    items
147        .iter()
148        .map(|(lang, code)| execute(lang, code, None))
149        .collect()
150}
151
152struct RuntimeConfig {
153    command: String,
154    args: Vec<String>,
155    needs_temp_file: bool,
156    file_extension: String,
157    env: HashMap<String, String>,
158}
159
160fn resolve_runtime(language: &str) -> Option<RuntimeConfig> {
161    let lang = language.to_lowercase();
162    let lang = lang.as_str();
163
164    match lang {
165        "javascript" | "js" | "node" => Some(RuntimeConfig {
166            command: find_binary(&["bun", "node"])?,
167            args: vec!["-e".to_string()],
168            needs_temp_file: false,
169            file_extension: "js".to_string(),
170            env: HashMap::new(),
171        }),
172        "typescript" | "ts" => Some(RuntimeConfig {
173            command: find_binary(&["bun", "npx"])?,
174            args: if which_exists("bun") {
175                vec!["-e".to_string()]
176            } else {
177                vec!["tsx".to_string(), "-e".to_string()]
178            },
179            needs_temp_file: false,
180            file_extension: "ts".to_string(),
181            env: HashMap::new(),
182        }),
183        "python" | "py" => Some(RuntimeConfig {
184            command: find_binary(&["python3", "python"])?,
185            args: vec!["-c".to_string()],
186            needs_temp_file: false,
187            file_extension: "py".to_string(),
188            env: HashMap::from([("PYTHONDONTWRITEBYTECODE".into(), "1".into())]),
189        }),
190        "shell" | "bash" | "sh" => {
191            #[cfg(target_os = "windows")]
192            {
193                Some(RuntimeConfig {
194                    command: "cmd".to_string(),
195                    args: vec!["/C".to_string()],
196                    needs_temp_file: false,
197                    file_extension: "bat".to_string(),
198                    env: HashMap::new(),
199                })
200            }
201            #[cfg(not(target_os = "windows"))]
202            {
203                Some(RuntimeConfig {
204                    command: find_binary(&["bash", "sh"])?,
205                    args: vec!["-c".to_string()],
206                    needs_temp_file: false,
207                    file_extension: "sh".to_string(),
208                    env: HashMap::new(),
209                })
210            }
211        }
212        "ruby" | "rb" => Some(RuntimeConfig {
213            command: find_binary(&["ruby"])?,
214            args: vec!["-e".to_string()],
215            needs_temp_file: false,
216            file_extension: "rb".to_string(),
217            env: HashMap::new(),
218        }),
219        "go" | "golang" => Some(RuntimeConfig {
220            command: find_binary(&["go"])?,
221            args: vec!["run".to_string()],
222            needs_temp_file: true,
223            file_extension: "go".to_string(),
224            env: HashMap::new(),
225        }),
226        "rust" | "rs" => Some(RuntimeConfig {
227            command: "rustc_script".to_string(),
228            args: vec![],
229            needs_temp_file: true,
230            file_extension: "rs".to_string(),
231            env: HashMap::new(),
232        }),
233        "php" => Some(RuntimeConfig {
234            command: find_binary(&["php"])?,
235            args: vec!["-r".to_string()],
236            needs_temp_file: false,
237            file_extension: "php".to_string(),
238            env: HashMap::new(),
239        }),
240        "perl" | "pl" => Some(RuntimeConfig {
241            command: find_binary(&["perl"])?,
242            args: vec!["-e".to_string()],
243            needs_temp_file: false,
244            file_extension: "pl".to_string(),
245            env: HashMap::new(),
246        }),
247        "r" => Some(RuntimeConfig {
248            command: find_binary(&["Rscript"])?,
249            args: vec!["-e".to_string()],
250            needs_temp_file: false,
251            file_extension: "R".to_string(),
252            env: HashMap::new(),
253        }),
254        "elixir" | "ex" => Some(RuntimeConfig {
255            command: find_binary(&["elixir"])?,
256            args: vec!["-e".to_string()],
257            needs_temp_file: false,
258            file_extension: "exs".to_string(),
259            env: HashMap::new(),
260        }),
261        _ => None,
262    }
263}
264
265fn seatbelt_execute(
266    runtime: &RuntimeConfig,
267    code: &str,
268    timeout: u64,
269    cwd: Option<&std::path::Path>,
270) -> Result<(String, String, i32), String> {
271    let tmp_dir = std::env::temp_dir().join("lean-ctx-sandbox");
272    let _ = std::fs::create_dir_all(&tmp_dir);
273
274    let env_pairs: Vec<(String, String)> = runtime
275        .env
276        .iter()
277        .map(|(k, v)| (k.clone(), v.clone()))
278        .collect();
279
280    if runtime.needs_temp_file {
281        let suffix = format!(".{}", runtime.file_extension);
282        let tmp = tempfile::Builder::new()
283            .prefix("exec_")
284            .suffix(&suffix)
285            .tempfile_in(&tmp_dir)
286            .map_err(|e| format!("Failed to create temp file: {e}"))?;
287        let file_path = tmp.into_temp_path();
288        std::fs::write(&file_path, code).map_err(|e| format!("Failed to write temp file: {e}"))?;
289
290        let mut allowed = vec![file_path.to_path_buf()];
291        // The profile denies by default, so a working directory the caller
292        // chose has to be granted explicitly — otherwise the snippet starts
293        // there and cannot read a thing (#1666). Write permission is
294        // deliberately not granted: that boundary belongs to sandbox_level.
295        if let Some(dir) = cwd {
296            allowed.push(dir.to_path_buf());
297        }
298        let allowed_refs: Vec<&std::path::Path> =
299            allowed.iter().map(std::path::PathBuf::as_path).collect();
300        let file_str = file_path.to_string_lossy().to_string();
301
302        let mut args: Vec<&str> = runtime
303            .args
304            .iter()
305            .map(std::string::String::as_str)
306            .collect();
307        args.push(&file_str);
308
309        let result = super::sandbox_seatbelt::execute_sandboxed(
310            &runtime.command,
311            &args,
312            &allowed_refs,
313            &env_pairs,
314            timeout,
315            cwd,
316        );
317        let _ = std::fs::remove_file(&file_path);
318        result
319    } else {
320        let mut args: Vec<&str> = runtime
321            .args
322            .iter()
323            .map(std::string::String::as_str)
324            .collect();
325        args.push(code);
326        let allowed: Vec<std::path::PathBuf> =
327            cwd.map(|d| vec![d.to_path_buf()]).unwrap_or_default();
328        let allowed_refs: Vec<&std::path::Path> =
329            allowed.iter().map(std::path::PathBuf::as_path).collect();
330        super::sandbox_seatbelt::execute_sandboxed(
331            &runtime.command,
332            &args,
333            &allowed_refs,
334            &env_pairs,
335            timeout,
336            cwd,
337        )
338    }
339}
340
341#[cfg(target_os = "linux")]
342fn landlock_execute(
343    runtime: &RuntimeConfig,
344    code: &str,
345    timeout: u64,
346    cwd: Option<&std::path::Path>,
347) -> Result<(String, String, i32), String> {
348    let tmp_dir = std::env::temp_dir().join("lean-ctx-sandbox");
349    let _ = std::fs::create_dir_all(&tmp_dir);
350
351    let env_pairs: Vec<(String, String)> = runtime
352        .env
353        .iter()
354        .map(|(k, v)| (k.clone(), v.clone()))
355        .collect();
356
357    if runtime.needs_temp_file {
358        let suffix = format!(".{}", runtime.file_extension);
359        let tmp = tempfile::Builder::new()
360            .prefix("exec_")
361            .suffix(&suffix)
362            .tempfile_in(&tmp_dir)
363            .map_err(|e| format!("Failed to create temp file: {e}"))?;
364        let file_path = tmp.into_temp_path();
365        std::fs::write(&file_path, code).map_err(|e| format!("Failed to write temp file: {e}"))?;
366
367        let mut allowed = vec![file_path.to_path_buf()];
368        if let Some(dir) = cwd {
369            allowed.push(dir.to_path_buf());
370        }
371        let allowed_refs: Vec<&std::path::Path> =
372            allowed.iter().map(std::path::PathBuf::as_path).collect();
373        let file_str = file_path.to_string_lossy().to_string();
374
375        let mut args: Vec<&str> = runtime
376            .args
377            .iter()
378            .map(std::string::String::as_str)
379            .collect();
380        args.push(&file_str);
381
382        let result = super::sandbox_landlock::execute_sandboxed(
383            &runtime.command,
384            &args,
385            &allowed_refs,
386            &env_pairs,
387            timeout,
388            cwd,
389        );
390        let _ = std::fs::remove_file(&file_path);
391        result
392    } else {
393        let mut args: Vec<&str> = runtime
394            .args
395            .iter()
396            .map(std::string::String::as_str)
397            .collect();
398        args.push(code);
399        let allowed: Vec<std::path::PathBuf> =
400            cwd.map(|d| vec![d.to_path_buf()]).unwrap_or_default();
401        let allowed_refs: Vec<&std::path::Path> =
402            allowed.iter().map(std::path::PathBuf::as_path).collect();
403        super::sandbox_landlock::execute_sandboxed(
404            &runtime.command,
405            &args,
406            &allowed_refs,
407            &env_pairs,
408            timeout,
409            cwd,
410        )
411    }
412}
413
414const SANDBOX_ENV_ALLOWLIST: &[&str] = &[
415    "PATH",
416    "HOME",
417    "USER",
418    "LANG",
419    "LC_ALL",
420    "TERM",
421    "TMPDIR",
422    "TMP",
423    "TEMP",
424    "SYSTEMROOT",
425    "WINDIR",
426    "SystemDrive",
427];
428
429fn apply_sandbox_env(cmd: &mut Command, runtime: &RuntimeConfig) {
430    cmd.env_clear();
431    for key in SANDBOX_ENV_ALLOWLIST {
432        if let Ok(val) = std::env::var(key) {
433            cmd.env(key, val);
434        }
435    }
436    for (k, v) in &runtime.env {
437        cmd.env(k, v);
438    }
439    cmd.env("LEAN_CTX_SANDBOX", "1");
440}
441
442/// Run the child in `cwd` when the caller resolved one (GH #1666).
443///
444/// A directory that no longer exists would make `spawn` fail with a message
445/// about the *command*, which reads as a missing interpreter. Falling back to
446/// the inherited directory is not an option either — running somewhere other
447/// than the caller asked, without saying so, is the bug this exists to fix —
448/// so an unusable directory is reported as itself.
449fn apply_cwd(cmd: &mut Command, cwd: Option<&std::path::Path>) -> Result<(), String> {
450    let Some(dir) = cwd else { return Ok(()) };
451    if !dir.is_dir() {
452        return Err(format!(
453            "working directory does not exist: {}",
454            dir.display()
455        ));
456    }
457    cmd.current_dir(dir);
458    Ok(())
459}
460
461fn execute_with_stdin(
462    runtime: &RuntimeConfig,
463    code: &str,
464    timeout: u64,
465    cwd: Option<&std::path::Path>,
466) -> Result<(String, String, i32), String> {
467    let mut cmd = Command::new(&runtime.command);
468    apply_cwd(&mut cmd, cwd)?;
469    for arg in &runtime.args {
470        cmd.arg(arg);
471    }
472    cmd.arg(code);
473    apply_sandbox_env(&mut cmd, runtime);
474    run_runtime_command(cmd, timeout)
475}
476
477/// All level-zero interpreter, compiler and compiled-program launches pass
478/// here. A protected MCP process must delegate even when optional sandboxing
479/// is disabled; it must never spawn a child with access to its context store.
480fn run_runtime_command(mut cmd: Command, timeout: u64) -> Result<(String, String, i32), String> {
481    #[cfg(unix)]
482    {
483        use crate::core::protected_execution::{Mode, launch_mode};
484        match launch_mode()? {
485            Mode::Brokered(client) => {
486                let executable = resolve_program_path(&cmd)?;
487                let executable = executable.to_str().ok_or("runtime path is not UTF-8")?;
488                let args: Vec<&str> = cmd
489                    .get_args()
490                    .map(|arg| arg.to_str().ok_or("runtime argument is not UTF-8"))
491                    .collect::<Result<_, _>>()?;
492                let env: Vec<(String, String)> = cmd
493                    .get_envs()
494                    .filter_map(|(key, value)| value.map(|value| (key, value)))
495                    .map(|(key, value)| {
496                        Ok((
497                            key.to_str()
498                                .ok_or("runtime environment key is not UTF-8")?
499                                .to_owned(),
500                            value
501                                .to_str()
502                                .ok_or("runtime environment value is not UTF-8")?
503                                .to_owned(),
504                        ))
505                    })
506                    .collect::<Result<_, String>>()?;
507                return client.session_program(
508                    executable,
509                    &args,
510                    &env,
511                    timeout,
512                    cmd.get_current_dir(),
513                );
514            }
515            Mode::Sandboxed(_) => {
516                return Err("runtime execution must use the supervised program channel".into());
517            }
518            Mode::Direct => {}
519        }
520    }
521    #[cfg(not(unix))]
522    let _protected = crate::cli::protected_child_prefix()?;
523    // GH #1347: isolate child into its own process group so an interactive
524    // shell (bash -ic) cannot SIGTSTP the MCP server, and close stdin to
525    // prevent terminal job-control attempts.
526    cmd.stdin(std::process::Stdio::null());
527    cmd.stdout(std::process::Stdio::piped());
528    cmd.stderr(std::process::Stdio::piped());
529    #[cfg(unix)]
530    cmd.process_group(0);
531
532    let program = cmd.get_program().to_string_lossy().into_owned();
533    let output = wait_with_timeout(&mut cmd, timeout, |e| {
534        format!("Failed to spawn {program}: {e}")
535    })?;
536    Ok((
537        crate::shell::decode_output(&output.stdout),
538        crate::shell::decode_output(&output.stderr),
539        crate::shell::exit_status::exit_code(output.status),
540    ))
541}
542
543#[cfg(unix)]
544fn resolve_program_path(cmd: &Command) -> Result<std::path::PathBuf, String> {
545    use std::os::unix::fs::PermissionsExt;
546    let program = std::path::Path::new(cmd.get_program());
547    if program.is_absolute() {
548        return Ok(program.to_path_buf());
549    }
550    let cwd = cmd
551        .get_current_dir()
552        .map(std::path::Path::to_path_buf)
553        .unwrap_or(std::env::current_dir().map_err(|_| "runtime working directory unavailable")?);
554    if program.components().count() > 1 {
555        return Ok(cwd.join(program));
556    }
557    let path = cmd
558        .get_envs()
559        .find(|(key, _)| *key == "PATH")
560        .and_then(|(_, value)| value.map(std::ffi::OsStr::to_os_string))
561        .or_else(|| std::env::var_os("PATH"))
562        .ok_or("runtime PATH unavailable")?;
563    for directory in std::env::split_paths(&path) {
564        let directory = if directory.is_absolute() {
565            directory
566        } else {
567            cwd.join(directory)
568        };
569        let candidate = directory.join(program);
570        if candidate
571            .metadata()
572            .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
573        {
574            // Preserve argv[0] for shims such as rustup's rustc symlink.
575            return Ok(candidate);
576        }
577    }
578    Err("runtime executable unavailable".into())
579}
580
581fn execute_with_file(
582    runtime: &RuntimeConfig,
583    code: &str,
584    timeout: u64,
585    cwd: Option<&std::path::Path>,
586) -> Result<(String, String, i32), String> {
587    let tmp_dir = std::env::temp_dir().join("lean-ctx-sandbox");
588    let _ = std::fs::create_dir_all(&tmp_dir);
589
590    let suffix = format!(".{}", runtime.file_extension);
591    let tmp = tempfile::Builder::new()
592        .prefix("exec_")
593        .suffix(&suffix)
594        .tempfile_in(&tmp_dir)
595        .map_err(|e| format!("Failed to create temp file: {e}"))?;
596    let file_path = tmp.into_temp_path();
597
598    std::fs::write(&file_path, code).map_err(|e| format!("Failed to write temp file: {e}"))?;
599
600    let result = if runtime.command == "rustc_script" {
601        execute_rust(&file_path, timeout, cwd)
602    } else {
603        let mut cmd = Command::new(&runtime.command);
604        apply_cwd(&mut cmd, cwd)?;
605        for arg in &runtime.args {
606            cmd.arg(arg);
607        }
608        cmd.arg(&file_path);
609        apply_sandbox_env(&mut cmd, runtime);
610        run_runtime_command(cmd, timeout)
611    };
612
613    let _ = std::fs::remove_file(&file_path);
614    result
615}
616
617fn execute_rust(
618    source_path: &std::path::Path,
619    timeout: u64,
620    cwd: Option<&std::path::Path>,
621) -> Result<(String, String, i32), String> {
622    let binary_path = source_path.with_extension("");
623
624    let mut compile_cmd = Command::new("rustc");
625    compile_cmd.arg(source_path).arg("-o").arg(&binary_path);
626    compile_cmd.env_clear();
627    for key in SANDBOX_ENV_ALLOWLIST {
628        if let Ok(val) = std::env::var(key) {
629            compile_cmd.env(key, val);
630        }
631    }
632    compile_cmd.env("LEAN_CTX_SANDBOX", "1");
633
634    let (_, stderr, code) = run_runtime_command(compile_cmd, timeout)?;
635
636    if code != 0 {
637        let _ = std::fs::remove_file(&binary_path);
638        return Ok((String::new(), stderr, code));
639    }
640
641    let mut run_cmd = Command::new(&binary_path);
642    apply_cwd(&mut run_cmd, cwd)?;
643    run_cmd.env_clear();
644    for key in SANDBOX_ENV_ALLOWLIST {
645        if let Ok(val) = std::env::var(key) {
646            run_cmd.env(key, val);
647        }
648    }
649    run_cmd.env("LEAN_CTX_SANDBOX", "1");
650    let result = run_runtime_command(run_cmd, timeout);
651    let _ = std::fs::remove_file(&binary_path);
652    result
653}
654
655fn wait_with_timeout(
656    cmd: &mut Command,
657    timeout_secs: u64,
658    spawn_error: impl FnOnce(std::io::Error) -> String,
659) -> Result<std::process::Output, String> {
660    // #1920: contain the whole tree, so a timeout on Windows ends what the
661    // snippet started instead of only the interpreter.
662    crate::shell::process_tree::ProcessTree::prepare(cmd);
663    let mut child = cmd.spawn().map_err(spawn_error)?;
664    let tree = crate::shell::process_tree::ProcessTree::start(&mut child)?;
665    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
666
667    loop {
668        match child.try_wait() {
669            Ok(Some(_)) => {
670                tree.release();
671                return child.wait_with_output().map_err(|e| e.to_string());
672            }
673            Ok(None) => {
674                if std::time::Instant::now() > deadline {
675                    tree.kill(&mut child);
676                    // GH #1504: after killing, drain whatever the child wrote
677                    // before the timeout so partial output is preserved instead
678                    // of being silently discarded.
679                    if let Ok(mut output) = child.wait_with_output() {
680                        output.stderr.extend_from_slice(
681                            format!("\n[lean-ctx] Execution timed out after {timeout_secs}s")
682                                .as_bytes(),
683                        );
684                        return Ok(output);
685                    }
686                    return Err(format!("Execution timed out after {timeout_secs}s"));
687                }
688                std::thread::sleep(std::time::Duration::from_millis(50));
689            }
690            Err(e) => {
691                tree.kill(&mut child);
692                let _ = child.wait();
693                return Err(e.to_string());
694            }
695        }
696    }
697}
698
699fn find_binary(candidates: &[&str]) -> Option<String> {
700    for name in candidates {
701        if which_exists(name) {
702            return Some(name.to_string());
703        }
704    }
705    None
706}
707
708fn which_exists(name: &str) -> bool {
709    #[cfg(target_os = "windows")]
710    let check_cmd = Command::new("where")
711        .arg(name)
712        .stdout(std::process::Stdio::null())
713        .stderr(std::process::Stdio::null())
714        .status();
715
716    #[cfg(not(target_os = "windows"))]
717    let check_cmd = Command::new("which")
718        .arg(name)
719        .stdout(std::process::Stdio::null())
720        .stderr(std::process::Stdio::null())
721        .status();
722
723    check_cmd.is_ok_and(|s| s.success())
724}
725
726fn truncate_output(output: &str) -> String {
727    if output.len() <= MAX_OUTPUT_BYTES {
728        return output.to_string();
729    }
730    truncate_smart(output, MAX_OUTPUT_BYTES)
731}
732
733fn truncate_smart(output: &str, max_bytes: usize) -> String {
734    if output.len() <= max_bytes {
735        return output.to_string();
736    }
737
738    let lines: Vec<&str> = output.lines().collect();
739    let total_lines = lines.len();
740
741    let head_count = (total_lines * 60) / 100;
742    let tail_count = total_lines - head_count;
743
744    let head: Vec<&str> = lines.iter().take(head_count).copied().collect();
745    let tail: Vec<&str> = lines
746        .iter()
747        .skip(total_lines - tail_count)
748        .copied()
749        .collect();
750
751    let head_text = head.join("\n");
752    let tail_text = tail.join("\n");
753
754    if head_text.len() + tail_text.len() + 100 > max_bytes {
755        let half = max_bytes / 2;
756        let h = &output[..output.floor_char_boundary(half.min(output.len()))];
757        let t_start = output.ceil_char_boundary(output.len().saturating_sub(half));
758        let t = &output[t_start..];
759        let skipped = output.len() - h.len() - t.len();
760        return format!("{h}\n\n... [{skipped} bytes truncated — showing head + tail] ...\n\n{t}");
761    }
762
763    let skipped_lines = total_lines - head_count - tail_count;
764    let skipped_bytes = output.len() - head_text.len() - tail_text.len();
765    format!(
766        "{head_text}\n\n... [{skipped_lines} lines / {skipped_bytes} bytes truncated — showing first {head_count} + last {tail_count} lines] ...\n\n{tail_text}"
767    )
768}
769
770pub fn supported_languages() -> &'static [&'static str] {
771    &[
772        "javascript",
773        "typescript",
774        "python",
775        "shell",
776        "ruby",
777        "go",
778        "rust",
779        "php",
780        "perl",
781        "r",
782        "elixir",
783    ]
784}
785
786#[cfg(test)]
787pub mod tests {
788    use super::*;
789
790    fn python_available() -> bool {
791        find_binary(&["python3", "python"]).is_some()
792    }
793
794    #[cfg(target_os = "macos")]
795    #[test]
796    fn level_zero_interpreters_and_compilers_require_the_protected_channel() {
797        let _lock = crate::core::data_dir::test_env_lock();
798        let isolation = crate::core::data_dir::isolated_data_dir();
799        let _session = crate::cli::pin_synthetic_session(isolation.path()).unwrap();
800        let runtime = RuntimeConfig {
801            command: "/bin/sh".into(),
802            args: vec!["-c".into()],
803            needs_temp_file: false,
804            file_extension: "sh".into(),
805            env: HashMap::new(),
806        };
807        let stdin_error = execute_with_stdin(&runtime, "printf bypass", 1, None).unwrap_err();
808        assert!(
809            stdin_error.contains("supervised execution channel"),
810            "{stdin_error}"
811        );
812        let file_error = execute_with_file(&runtime, "printf bypass", 1, None).unwrap_err();
813        assert!(
814            file_error.contains("supervised execution channel"),
815            "{file_error}"
816        );
817        let source = tempfile::Builder::new().suffix(".rs").tempfile().unwrap();
818        std::fs::write(source.path(), "fn main() {}\n").unwrap();
819        let rust_error = execute_rust(source.path(), 1, None).unwrap_err();
820        assert!(
821            rust_error.contains("supervised execution channel"),
822            "{rust_error}"
823        );
824        assert!(!source.path().with_extension("").exists());
825    }
826
827    #[test]
828    fn execute_python_hello() {
829        let _lock = crate::core::data_dir::test_env_lock();
830        if !python_available() {
831            return;
832        }
833        let result = execute("python", "print('hello sandbox')", None);
834        assert_eq!(result.exit_code, 0);
835        assert!(result.stdout.contains("hello sandbox"));
836    }
837
838    /// GH #1666: a snippet must run where the caller said, because relative
839    /// paths inside it are resolved there. The `cwd: None` half of this test is
840    /// the pre-fix behaviour — it is what made a script edit the project root
841    /// while the caller was working in a worktree, and report success.
842    #[test]
843    #[cfg(not(target_os = "windows"))]
844    fn execute_in_resolves_relative_paths_against_the_given_directory() {
845        let _lock = crate::core::data_dir::test_env_lock();
846        let dir = tempfile::tempdir().expect("tempdir");
847        std::fs::write(dir.path().join("only-here.txt"), "x").expect("write marker");
848
849        let scoped = execute_in("shell", "cat only-here.txt", None, Some(dir.path()));
850        assert_eq!(scoped.exit_code, 0, "stderr: {}", scoped.stderr);
851        assert!(scoped.stdout.contains('x'), "{scoped:?}");
852
853        // Without a cwd the same relative path resolves somewhere else, which
854        // is exactly what the reported bug did silently.
855        let unscoped = execute_in("shell", "cat only-here.txt", None, None);
856        assert_ne!(
857            unscoped.exit_code, 0,
858            "precondition: the marker is only reachable from the given directory"
859        );
860    }
861
862    /// A directory that cannot be entered is reported as itself. Falling back
863    /// to the inherited directory would reinstate the silent wrong-tree run.
864    #[test]
865    #[cfg(not(target_os = "windows"))]
866    fn execute_in_reports_a_missing_directory_instead_of_falling_back() {
867        let _lock = crate::core::data_dir::test_env_lock();
868        let dir = tempfile::tempdir().expect("tempdir");
869        let missing = dir.path().join("does-not-exist");
870
871        let result = execute_in("shell", "pwd", None, Some(&missing));
872        assert_ne!(result.exit_code, 0, "{result:?}");
873        assert!(
874            result.stderr.contains("working directory does not exist"),
875            "{result:?}"
876        );
877    }
878
879    #[test]
880    #[cfg(not(target_os = "windows"))]
881    fn execute_shell_echo() {
882        let _lock = crate::core::data_dir::test_env_lock();
883        let result = execute("shell", "echo 'test output'", None);
884        assert_eq!(result.exit_code, 0);
885        assert!(result.stdout.contains("test output"));
886    }
887
888    #[test]
889    fn execute_unsupported_language() {
890        let result = execute("brainfuck", "++++", None);
891        assert_eq!(result.exit_code, 1);
892        assert!(result.stderr.contains("Unsupported language"));
893    }
894
895    #[test]
896    fn execute_rejects_oversized_code() {
897        let huge = "a".repeat(MAX_CODE_BYTES + 1);
898        let result = execute("python", &huge, None);
899        assert_eq!(result.exit_code, 1);
900        assert!(result.stderr.contains("exceeds the"));
901    }
902
903    #[cfg(windows)]
904    #[test]
905    fn sandbox_env_preserves_system_drive() {
906        let expected =
907            std::env::var_os("SystemDrive").expect("SystemDrive must be defined on Windows");
908
909        let runtime = RuntimeConfig {
910            command: "cmd".to_string(),
911            args: Vec::new(),
912            needs_temp_file: false,
913            file_extension: "bat".to_string(),
914            env: HashMap::new(),
915        };
916
917        let mut cmd = Command::new("cmd");
918        apply_sandbox_env(&mut cmd, &runtime);
919
920        let preserved = cmd.get_envs().any(|(key, value)| {
921            key.to_string_lossy().eq_ignore_ascii_case("SystemDrive")
922                && value == Some(expected.as_os_str())
923        });
924
925        assert!(
926            preserved,
927            "Windows sandbox child environment must preserve SystemDrive"
928        );
929    }
930
931    #[test]
932    fn execute_python_error() {
933        let _lock = crate::core::data_dir::test_env_lock();
934        if !python_available() {
935            return;
936        }
937        let result = execute("python", "raise ValueError('test error')", None);
938        assert_ne!(result.exit_code, 0);
939        assert!(result.stderr.contains("ValueError"));
940    }
941
942    #[test]
943    fn execute_with_timeout() {
944        let _lock = crate::core::data_dir::test_env_lock();
945        if !python_available() {
946            return;
947        }
948        let result = execute("python", "import time; time.sleep(60)", Some(1));
949        assert_ne!(result.exit_code, 0);
950        assert!(
951            result.stderr.contains("timed out"),
952            "stderr should mention timeout: {}",
953            result.stderr
954        );
955    }
956
957    /// GH #1504: partial stdout emitted before a timeout must be preserved.
958    #[test]
959    fn timeout_preserves_partial_output() {
960        let _lock = crate::core::data_dir::test_env_lock();
961        if !python_available() {
962            return;
963        }
964        let result = execute(
965            "python",
966            "import sys; sys.stdout.write('PARTIAL_1504'); sys.stdout.flush(); import time; time.sleep(60)",
967            Some(2),
968        );
969        assert_ne!(result.exit_code, 0);
970        assert!(
971            result.stdout.contains("PARTIAL_1504"),
972            "partial stdout before timeout must be preserved, got: {:?}",
973            result.stdout
974        );
975        assert!(
976            result.stderr.contains("timed out"),
977            "stderr should mention timeout: {}",
978            result.stderr
979        );
980    }
981
982    #[test]
983    fn truncate_preserves_head_and_tail() {
984        let lines: Vec<String> = (0..100)
985            .map(|i| format!("line {i}: some content here"))
986            .collect();
987        let output = lines.join("\n");
988        let truncated = truncate_smart(&output, 500);
989        assert!(truncated.contains("line 0:"));
990        assert!(truncated.contains("line 99:"));
991        assert!(truncated.contains("truncated"));
992    }
993
994    #[test]
995    fn supported_languages_list() {
996        let langs = supported_languages();
997        assert!(langs.contains(&"python"));
998        assert!(langs.contains(&"javascript"));
999        assert!(langs.contains(&"rust"));
1000        assert_eq!(langs.len(), 11);
1001    }
1002
1003    #[test]
1004    fn sandbox_env_is_set() {
1005        let _lock = crate::core::data_dir::test_env_lock();
1006        if !python_available() {
1007            return;
1008        }
1009        let result = execute(
1010            "python",
1011            "import os; print(os.environ.get('LEAN_CTX_SANDBOX', 'missing'))",
1012            None,
1013        );
1014        assert_eq!(result.exit_code, 0);
1015        assert!(result.stdout.contains('1'));
1016    }
1017
1018    #[test]
1019    #[cfg(not(target_os = "windows"))]
1020    fn batch_execute_multiple() {
1021        let _lock = crate::core::data_dir::test_env_lock();
1022        let items = vec![
1023            ("python".to_string(), "print(1+1)".to_string()),
1024            ("shell".to_string(), "echo hello".to_string()),
1025        ];
1026        let results = batch_execute(&items);
1027        assert_eq!(results.len(), 2);
1028        assert!(results[0].stdout.contains('2'));
1029        assert!(results[1].stdout.contains("hello"));
1030    }
1031}