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    // GH #1347: isolate child into its own process group so an interactive
475    // shell (bash -ic) cannot SIGTSTP the MCP server, and close stdin to
476    // prevent terminal job-control attempts.
477    cmd.stdin(std::process::Stdio::null());
478    cmd.stdout(std::process::Stdio::piped());
479    cmd.stderr(std::process::Stdio::piped());
480    #[cfg(unix)]
481    cmd.process_group(0);
482
483    let child = cmd
484        .spawn()
485        .map_err(|e| format!("Failed to spawn {}: {e}", runtime.command))?;
486
487    let output = wait_with_timeout(child, timeout)?;
488    Ok((
489        crate::shell::decode_output(&output.stdout),
490        crate::shell::decode_output(&output.stderr),
491        output.status.code().unwrap_or(1),
492    ))
493}
494
495fn execute_with_file(
496    runtime: &RuntimeConfig,
497    code: &str,
498    timeout: u64,
499    cwd: Option<&std::path::Path>,
500) -> Result<(String, String, i32), String> {
501    let tmp_dir = std::env::temp_dir().join("lean-ctx-sandbox");
502    let _ = std::fs::create_dir_all(&tmp_dir);
503
504    let suffix = format!(".{}", runtime.file_extension);
505    let tmp = tempfile::Builder::new()
506        .prefix("exec_")
507        .suffix(&suffix)
508        .tempfile_in(&tmp_dir)
509        .map_err(|e| format!("Failed to create temp file: {e}"))?;
510    let file_path = tmp.into_temp_path();
511
512    std::fs::write(&file_path, code).map_err(|e| format!("Failed to write temp file: {e}"))?;
513
514    let result = if runtime.command == "rustc_script" {
515        execute_rust(&file_path, timeout, cwd)
516    } else {
517        let mut cmd = Command::new(&runtime.command);
518        apply_cwd(&mut cmd, cwd)?;
519        for arg in &runtime.args {
520            cmd.arg(arg);
521        }
522        cmd.arg(&file_path);
523        apply_sandbox_env(&mut cmd, runtime);
524        cmd.stdin(std::process::Stdio::null());
525        cmd.stdout(std::process::Stdio::piped());
526        cmd.stderr(std::process::Stdio::piped());
527        #[cfg(unix)]
528        cmd.process_group(0);
529
530        let child = cmd
531            .spawn()
532            .map_err(|e| format!("Failed to spawn {}: {e}", runtime.command))?;
533        let output = wait_with_timeout(child, timeout)?;
534        Ok((
535            crate::shell::decode_output(&output.stdout),
536            crate::shell::decode_output(&output.stderr),
537            output.status.code().unwrap_or(1),
538        ))
539    };
540
541    let _ = std::fs::remove_file(&file_path);
542    result
543}
544
545fn execute_rust(
546    source_path: &std::path::Path,
547    timeout: u64,
548    cwd: Option<&std::path::Path>,
549) -> Result<(String, String, i32), String> {
550    let binary_path = source_path.with_extension("");
551
552    let mut compile_cmd = Command::new("rustc");
553    compile_cmd.arg(source_path).arg("-o").arg(&binary_path);
554    compile_cmd.env_clear();
555    for key in SANDBOX_ENV_ALLOWLIST {
556        if let Ok(val) = std::env::var(key) {
557            compile_cmd.env(key, val);
558        }
559    }
560    compile_cmd.env("LEAN_CTX_SANDBOX", "1");
561
562    let compile = compile_cmd
563        .output()
564        .map_err(|e| format!("rustc not found: {e}"))?;
565
566    if !compile.status.success() {
567        let stderr = crate::shell::decode_output(&compile.stderr);
568        let _ = std::fs::remove_file(&binary_path);
569        return Ok((String::new(), stderr, compile.status.code().unwrap_or(1)));
570    }
571
572    let mut run_cmd = Command::new(&binary_path);
573    apply_cwd(&mut run_cmd, cwd)?;
574    run_cmd.env_clear();
575    for key in SANDBOX_ENV_ALLOWLIST {
576        if let Ok(val) = std::env::var(key) {
577            run_cmd.env(key, val);
578        }
579    }
580    run_cmd.env("LEAN_CTX_SANDBOX", "1");
581    run_cmd.stdin(std::process::Stdio::null());
582    run_cmd.stdout(std::process::Stdio::piped());
583    run_cmd.stderr(std::process::Stdio::piped());
584    #[cfg(unix)]
585    run_cmd.process_group(0);
586
587    let child = run_cmd
588        .spawn()
589        .map_err(|e| format!("Failed to run compiled binary: {e}"))?;
590
591    let output = wait_with_timeout(child, timeout)?;
592    let _ = std::fs::remove_file(&binary_path);
593
594    Ok((
595        crate::shell::decode_output(&output.stdout),
596        crate::shell::decode_output(&output.stderr),
597        output.status.code().unwrap_or(1),
598    ))
599}
600
601fn wait_with_timeout(
602    child: std::process::Child,
603    timeout_secs: u64,
604) -> Result<std::process::Output, String> {
605    let mut child = child;
606    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
607
608    loop {
609        match child.try_wait() {
610            Ok(Some(_)) => return child.wait_with_output().map_err(|e| e.to_string()),
611            Ok(None) => {
612                if std::time::Instant::now() > deadline {
613                    kill_process_tree(&mut child);
614                    // GH #1504: after killing, drain whatever the child wrote
615                    // before the timeout so partial output is preserved instead
616                    // of being silently discarded.
617                    if let Ok(mut output) = child.wait_with_output() {
618                        output.stderr.extend_from_slice(
619                            format!("\n[lean-ctx] Execution timed out after {timeout_secs}s")
620                                .as_bytes(),
621                        );
622                        return Ok(output);
623                    }
624                    return Err(format!("Execution timed out after {timeout_secs}s"));
625                }
626                std::thread::sleep(std::time::Duration::from_millis(50));
627            }
628            Err(e) => return Err(e.to_string()),
629        }
630    }
631}
632
633/// Kill a child process and its entire process group (Unix) or just the child
634/// (non-Unix). Uses SIGKILL on the negative PID to hit the whole group created
635/// by `process_group(0)`.
636fn kill_process_tree(child: &mut std::process::Child) {
637    #[cfg(unix)]
638    {
639        let pid = child.id() as i32;
640        // SAFETY: libc::kill with negative pid targets the process group.
641        unsafe { libc::kill(-pid, libc::SIGKILL) };
642    }
643    #[cfg(not(unix))]
644    {
645        let _ = child.kill();
646    }
647}
648
649fn find_binary(candidates: &[&str]) -> Option<String> {
650    for name in candidates {
651        if which_exists(name) {
652            return Some(name.to_string());
653        }
654    }
655    None
656}
657
658fn which_exists(name: &str) -> bool {
659    #[cfg(target_os = "windows")]
660    let check_cmd = Command::new("where")
661        .arg(name)
662        .stdout(std::process::Stdio::null())
663        .stderr(std::process::Stdio::null())
664        .status();
665
666    #[cfg(not(target_os = "windows"))]
667    let check_cmd = Command::new("which")
668        .arg(name)
669        .stdout(std::process::Stdio::null())
670        .stderr(std::process::Stdio::null())
671        .status();
672
673    check_cmd.is_ok_and(|s| s.success())
674}
675
676fn truncate_output(output: &str) -> String {
677    if output.len() <= MAX_OUTPUT_BYTES {
678        return output.to_string();
679    }
680    truncate_smart(output, MAX_OUTPUT_BYTES)
681}
682
683fn truncate_smart(output: &str, max_bytes: usize) -> String {
684    if output.len() <= max_bytes {
685        return output.to_string();
686    }
687
688    let lines: Vec<&str> = output.lines().collect();
689    let total_lines = lines.len();
690
691    let head_count = (total_lines * 60) / 100;
692    let tail_count = total_lines - head_count;
693
694    let head: Vec<&str> = lines.iter().take(head_count).copied().collect();
695    let tail: Vec<&str> = lines
696        .iter()
697        .skip(total_lines - tail_count)
698        .copied()
699        .collect();
700
701    let head_text = head.join("\n");
702    let tail_text = tail.join("\n");
703
704    if head_text.len() + tail_text.len() + 100 > max_bytes {
705        let half = max_bytes / 2;
706        let h = &output[..output.floor_char_boundary(half.min(output.len()))];
707        let t_start = output.ceil_char_boundary(output.len().saturating_sub(half));
708        let t = &output[t_start..];
709        let skipped = output.len() - h.len() - t.len();
710        return format!("{h}\n\n... [{skipped} bytes truncated — showing head + tail] ...\n\n{t}");
711    }
712
713    let skipped_lines = total_lines - head_count - tail_count;
714    let skipped_bytes = output.len() - head_text.len() - tail_text.len();
715    format!(
716        "{head_text}\n\n... [{skipped_lines} lines / {skipped_bytes} bytes truncated — showing first {head_count} + last {tail_count} lines] ...\n\n{tail_text}"
717    )
718}
719
720pub fn supported_languages() -> &'static [&'static str] {
721    &[
722        "javascript",
723        "typescript",
724        "python",
725        "shell",
726        "ruby",
727        "go",
728        "rust",
729        "php",
730        "perl",
731        "r",
732        "elixir",
733    ]
734}
735
736#[cfg(test)]
737pub mod tests {
738    use super::*;
739
740    fn python_available() -> bool {
741        find_binary(&["python3", "python"]).is_some()
742    }
743
744    #[test]
745    fn execute_python_hello() {
746        if !python_available() {
747            return;
748        }
749        let result = execute("python", "print('hello sandbox')", None);
750        assert_eq!(result.exit_code, 0);
751        assert!(result.stdout.contains("hello sandbox"));
752    }
753
754    /// GH #1666: a snippet must run where the caller said, because relative
755    /// paths inside it are resolved there. The `cwd: None` half of this test is
756    /// the pre-fix behaviour — it is what made a script edit the project root
757    /// while the caller was working in a worktree, and report success.
758    #[test]
759    #[cfg(not(target_os = "windows"))]
760    fn execute_in_resolves_relative_paths_against_the_given_directory() {
761        let dir = tempfile::tempdir().expect("tempdir");
762        std::fs::write(dir.path().join("only-here.txt"), "x").expect("write marker");
763
764        let scoped = execute_in("shell", "cat only-here.txt", None, Some(dir.path()));
765        assert_eq!(scoped.exit_code, 0, "stderr: {}", scoped.stderr);
766        assert!(scoped.stdout.contains('x'), "{scoped:?}");
767
768        // Without a cwd the same relative path resolves somewhere else, which
769        // is exactly what the reported bug did silently.
770        let unscoped = execute_in("shell", "cat only-here.txt", None, None);
771        assert_ne!(
772            unscoped.exit_code, 0,
773            "precondition: the marker is only reachable from the given directory"
774        );
775    }
776
777    /// A directory that cannot be entered is reported as itself. Falling back
778    /// to the inherited directory would reinstate the silent wrong-tree run.
779    #[test]
780    #[cfg(not(target_os = "windows"))]
781    fn execute_in_reports_a_missing_directory_instead_of_falling_back() {
782        let dir = tempfile::tempdir().expect("tempdir");
783        let missing = dir.path().join("does-not-exist");
784
785        let result = execute_in("shell", "pwd", None, Some(&missing));
786        assert_ne!(result.exit_code, 0, "{result:?}");
787        assert!(
788            result.stderr.contains("working directory does not exist"),
789            "{result:?}"
790        );
791    }
792
793    #[test]
794    #[cfg(not(target_os = "windows"))]
795    fn execute_shell_echo() {
796        let result = execute("shell", "echo 'test output'", None);
797        assert_eq!(result.exit_code, 0);
798        assert!(result.stdout.contains("test output"));
799    }
800
801    #[test]
802    fn execute_unsupported_language() {
803        let result = execute("brainfuck", "++++", None);
804        assert_eq!(result.exit_code, 1);
805        assert!(result.stderr.contains("Unsupported language"));
806    }
807
808    #[test]
809    fn execute_rejects_oversized_code() {
810        let huge = "a".repeat(MAX_CODE_BYTES + 1);
811        let result = execute("python", &huge, None);
812        assert_eq!(result.exit_code, 1);
813        assert!(result.stderr.contains("exceeds the"));
814    }
815
816    #[cfg(windows)]
817    #[test]
818    fn sandbox_env_preserves_system_drive() {
819        let expected =
820            std::env::var_os("SystemDrive").expect("SystemDrive must be defined on Windows");
821
822        let runtime = RuntimeConfig {
823            command: "cmd".to_string(),
824            args: Vec::new(),
825            needs_temp_file: false,
826            file_extension: "bat".to_string(),
827            env: HashMap::new(),
828        };
829
830        let mut cmd = Command::new("cmd");
831        apply_sandbox_env(&mut cmd, &runtime);
832
833        let preserved = cmd.get_envs().any(|(key, value)| {
834            key.to_string_lossy().eq_ignore_ascii_case("SystemDrive")
835                && value == Some(expected.as_os_str())
836        });
837
838        assert!(
839            preserved,
840            "Windows sandbox child environment must preserve SystemDrive"
841        );
842    }
843
844    #[test]
845    fn execute_python_error() {
846        if !python_available() {
847            return;
848        }
849        let result = execute("python", "raise ValueError('test error')", None);
850        assert_ne!(result.exit_code, 0);
851        assert!(result.stderr.contains("ValueError"));
852    }
853
854    #[test]
855    fn execute_with_timeout() {
856        if !python_available() {
857            return;
858        }
859        let result = execute("python", "import time; time.sleep(60)", Some(1));
860        assert_ne!(result.exit_code, 0);
861        assert!(
862            result.stderr.contains("timed out"),
863            "stderr should mention timeout: {}",
864            result.stderr
865        );
866    }
867
868    /// GH #1504: partial stdout emitted before a timeout must be preserved.
869    #[test]
870    fn timeout_preserves_partial_output() {
871        if !python_available() {
872            return;
873        }
874        let result = execute(
875            "python",
876            "import sys; sys.stdout.write('PARTIAL_1504'); sys.stdout.flush(); import time; time.sleep(60)",
877            Some(2),
878        );
879        assert_ne!(result.exit_code, 0);
880        assert!(
881            result.stdout.contains("PARTIAL_1504"),
882            "partial stdout before timeout must be preserved, got: {:?}",
883            result.stdout
884        );
885        assert!(
886            result.stderr.contains("timed out"),
887            "stderr should mention timeout: {}",
888            result.stderr
889        );
890    }
891
892    #[test]
893    fn truncate_preserves_head_and_tail() {
894        let lines: Vec<String> = (0..100)
895            .map(|i| format!("line {i}: some content here"))
896            .collect();
897        let output = lines.join("\n");
898        let truncated = truncate_smart(&output, 500);
899        assert!(truncated.contains("line 0:"));
900        assert!(truncated.contains("line 99:"));
901        assert!(truncated.contains("truncated"));
902    }
903
904    #[test]
905    fn supported_languages_list() {
906        let langs = supported_languages();
907        assert!(langs.contains(&"python"));
908        assert!(langs.contains(&"javascript"));
909        assert!(langs.contains(&"rust"));
910        assert_eq!(langs.len(), 11);
911    }
912
913    #[test]
914    fn sandbox_env_is_set() {
915        if !python_available() {
916            return;
917        }
918        let result = execute(
919            "python",
920            "import os; print(os.environ.get('LEAN_CTX_SANDBOX', 'missing'))",
921            None,
922        );
923        assert_eq!(result.exit_code, 0);
924        assert!(result.stdout.contains('1'));
925    }
926
927    #[test]
928    #[cfg(not(target_os = "windows"))]
929    fn batch_execute_multiple() {
930        let items = vec![
931            ("python".to_string(), "print(1+1)".to_string()),
932            ("shell".to_string(), "echo hello".to_string()),
933        ];
934        let results = batch_execute(&items);
935        assert_eq!(results.len(), 2);
936        assert!(results[0].stdout.contains('2'));
937        assert!(results[1].stdout.contains("hello"));
938    }
939}