Skip to main content

byob_exec/
lib.rs

1//! Tools that run code: [`RunCommand`] (`run_command`, a shell command), [`RunPython`]
2//! (`run_python`, Python code or a script) and [`InstallPythonPackages`]
3//! (`install_python_packages`, into byob's managed venv with `uv`).
4//!
5//! Everything runs through [`byob_sandbox`]: read the system, read+write the workspace and
6//! a private temp folder, no network unless the call asks (and the user approves), a
7//! minimal environment without inherited secrets, wall-clock timeout, bounded output,
8//! and the whole process tree is killed on timeout or Stop. Where the OS can't sandbox
9//! (no Landlock), commands still run, with a warning in the log and in the tool output;
10//! `BYOB_SANDBOX=off` turns the sandbox off explicitly ([`Mode::Unsandboxed`]).
11#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
12
13pub mod python;
14
15use std::ffi::OsString;
16use std::path::{Path, PathBuf};
17use std::process::Command;
18use std::sync::Arc;
19use std::time::Duration;
20
21use byob_sandbox::{Limits, Outcome, Policy, RunOptions, Sandbox, Snapshot, TempDir};
22use byob_tools::{Access, FileChange, Registry, Tool, ToolContext, ToolOutput, ToolSpec, parse_args};
23use serde::Deserialize;
24use serde_json::{Value, json};
25
26pub use python::Python;
27
28pub const DEFAULT_TIMEOUT_S: u64 = 120;
29pub const MAX_TIMEOUT_S: u64 = 600;
30const INSTALL_TIMEOUT: Duration = Duration::from_secs(900);
31/// Bytes kept per stream (head and tail halves) for the model.
32pub const MAX_OUTPUT: usize = 24 * 1024;
33const MAX_COMMAND_LEN: usize = 64 * 1024;
34const MAX_CODE_LEN: usize = 512 * 1024;
35const MAX_ARGS: usize = 64;
36const MAX_PACKAGES: usize = 20;
37/// Most changed files listed in the text the model sees.
38const MAX_LISTED: usize = 30;
39
40/// How commands run.
41#[derive(Debug, Clone)]
42pub enum Mode {
43    Sandboxed(Sandbox),
44    /// The user turned the sandbox off (`BYOB_SANDBOX=off`): plain child processes, still
45    /// with the clean environment, timeout, output caps and group kill.
46    Unsandboxed,
47}
48
49impl Mode {
50    /// `Unsandboxed` if the user opted out (logged), else the sandbox via this binary.
51    /// Logs what the sandbox can enforce here (a warning if it can't confine anything).
52    pub fn from_env() -> Result<Self, String> {
53        if byob_sandbox::disabled_by_user() {
54            log::warn!("{}=off: commands and Python run WITHOUT a sandbox", byob_sandbox::DISABLE_ENV);
55            return Ok(Self::Unsandboxed);
56        }
57        let sb = Sandbox::from_current_exe()?;
58        let e = sb.probe();
59        if e.confined() {
60            log::info!("sandbox: filesystem {}, network {}, process tree {}", e.filesystem, e.network, e.process_tree);
61        } else {
62            log::warn!("sandbox unavailable ({}); commands and Python will run WITHOUT one", e.notes.join("; "));
63        }
64        Ok(Self::Sandboxed(sb))
65    }
66
67    /// A note for the model/user when runs aren't actually confined.
68    fn unconfined_note(&self) -> Option<String> {
69        match self {
70            Self::Unsandboxed => Some(format!("ran without a sandbox: {}=off", byob_sandbox::DISABLE_ENV)),
71            Self::Sandboxed(sb) => {
72                let e = sb.probe();
73                (!e.confined()).then(|| format!("ran without a sandbox: {}", e.notes.join("; ")))
74            }
75        }
76    }
77}
78
79/// Shared by the tools.
80#[derive(Debug, Clone)]
81pub struct Exec {
82    pub mode: Mode,
83    /// byob's data folder (holds the managed Python venv); `None` disables it.
84    pub data_dir: Option<PathBuf>,
85}
86
87/// Register `run_command`, `run_python`, and — when `uv` is installed and there's a data
88/// folder — `install_python_packages`.
89pub fn register(reg: &mut Registry, exec: Exec) {
90    let exec = Arc::new(exec);
91    reg.register(Arc::new(RunCommand(Arc::clone(&exec))));
92    reg.register(Arc::new(RunPython(Arc::clone(&exec))));
93    if exec.data_dir.is_some() && python::which("uv".as_ref()).is_some() {
94        reg.register(Arc::new(InstallPythonPackages(exec)));
95    }
96}
97
98/// One sandboxed invocation.
99struct Job {
100    program: OsString,
101    args: Vec<OsString>,
102    network: bool,
103    timeout: Duration,
104    read: Vec<PathBuf>,
105    write: Vec<PathBuf>,
106    env: Vec<(String, OsString)>,
107}
108
109impl Exec {
110    /// Run `job` with `tmp` as its private temp folder.
111    fn run(&self, job: Job, cwd: &Path, tmp: &Path, ctx: &ToolContext<'_>) -> Result<Outcome, String> {
112        let secs = job.timeout.as_secs().max(1);
113        let mut cmd = match &self.mode {
114            Mode::Sandboxed(sb) => {
115                let mut policy = Policy::for_workspace(cwd, tmp)
116                    .network(job.network)
117                    .limits(Limits::for_timeout(secs))
118                    // Where the OS can't confine, run anyway (warned at startup and in the output).
119                    .allow_unsandboxed(true)
120                    .allow_path_dirs(std::env::var_os("PATH").as_deref());
121                for p in job.read {
122                    policy = policy.allow_read(p);
123                }
124                for p in job.write {
125                    policy = policy.allow_write(p);
126                }
127                sb.command(&policy, &job.program, &job.args)
128            }
129            Mode::Unsandboxed => {
130                let mut c = Command::new(&job.program);
131                c.args(&job.args);
132                c
133            }
134        };
135        cmd.current_dir(cwd);
136        byob_sandbox::clean_env(&mut cmd, tmp);
137        cmd.envs(job.env);
138        let opts = RunOptions { timeout: job.timeout, max_output: MAX_OUTPUT, ..Default::default() };
139        let out = byob_sandbox::run(cmd, &opts, &|| ctx.cancelled())?;
140        match out.sandbox_error() {
141            Some(e) => Err(format!(
142                "the sandbox couldn't start: {e}. Nothing ran. (The user can set {}=off to run commands without a sandbox.)",
143                byob_sandbox::DISABLE_ENV
144            )),
145            None => Ok(out),
146        }
147    }
148
149    /// Run in the workspace and describe the result (output + changed files) for the model.
150    fn run_in_workspace(&self, mut job: Job, prepare: impl FnOnce(&Path) -> Result<Vec<OsString>, String>, ctx: &ToolContext<'_>) -> ToolOutput {
151        if ctx.cancelled() {
152            return ToolOutput::err("Stopped by the user.");
153        }
154        let root = match byob_tools::sandbox::root(ctx.workspace) {
155            Ok(r) => r,
156            Err(e) => return ToolOutput::err(e),
157        };
158        let tmp = match TempDir::new("byob-run-") {
159            Ok(t) => t,
160            Err(e) => return ToolOutput::err(e),
161        };
162        match prepare(tmp.path()) {
163            Ok(extra) => job.args.extend(extra),
164            Err(e) => return ToolOutput::err(e),
165        }
166        let timeout = job.timeout;
167        let before = Snapshot::take(&root);
168        let out = match self.run(job, &root, tmp.path(), ctx) {
169            Ok(o) => o,
170            Err(e) => return ToolOutput::err(e),
171        };
172        let changes = before.changes(&Snapshot::take(&root));
173        describe(&out, &changes, &root, timeout, self.mode.unconfined_note())
174    }
175}
176
177fn describe(out: &Outcome, changes: &byob_sandbox::Changes, root: &Path, timeout: Duration, unconfined: Option<String>) -> ToolOutput {
178    let mut text = String::new();
179    if out.cancelled {
180        text.push_str("Stopped by the user.\n");
181    } else if out.timed_out {
182        text.push_str(&format!("Timed out after {} s and was stopped (with everything it started).\n", timeout.as_secs()));
183    } else {
184        match (out.exit_code, out.signal) {
185            (Some(c), _) => text.push_str(&format!("Exit code: {c}\n")),
186            (None, Some(s)) => text.push_str(&format!("Killed by signal {s}\n")),
187            (None, None) => text.push_str("Exit code: unknown\n"),
188        }
189    }
190    for (name, cap) in [("stdout", &out.stdout), ("stderr", &out.stderr)] {
191        let t = cap.text();
192        if !t.trim().is_empty() {
193            text.push_str(&format!("\n{name}:\n{}\n", t.trim_end()));
194        }
195    }
196    let rel = |p: &PathBuf| byob_tools::sandbox::slash(p.strip_prefix(root).unwrap_or(p));
197    for (label, list) in [("Files created", &changes.created), ("Files modified", &changes.modified), ("Files deleted", &changes.deleted)] {
198        if list.is_empty() {
199            continue;
200        }
201        let mut names: Vec<String> = list.iter().take(MAX_LISTED).map(rel).collect();
202        if list.len() > MAX_LISTED {
203            names.push(format!("… and {} more", list.len() - MAX_LISTED));
204        }
205        text.push_str(&format!("\n{label}: {}\n", names.join(", ")));
206    }
207    if out.stdout.text().trim().is_empty() && out.stderr.text().trim().is_empty() && changes.is_empty() && out.success() {
208        text.push_str("(no output)\n");
209    }
210    if let Some(note) = unconfined {
211        text.push_str(&format!("\n({note})\n"));
212    }
213    let mut fc: Vec<FileChange> = changes.created.iter().cloned().map(FileChange::Created).collect();
214    fc.extend(changes.modified.iter().cloned().map(FileChange::Modified));
215    fc.extend(changes.deleted.iter().cloned().map(FileChange::Deleted));
216    ToolOutput { text: text.trim_end().to_owned(), failed: !out.success(), changes: fc }
217}
218
219fn timeout_of(secs: Option<f64>) -> Duration {
220    let s = secs.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(DEFAULT_TIMEOUT_S as f64);
221    Duration::from_secs_f64(s.min(MAX_TIMEOUT_S as f64).max(1.0))
222}
223
224/// One line, at most `max` chars, for titles.
225fn short(s: &str, max: usize) -> String {
226    let line = s.trim().lines().next().unwrap_or_default();
227    let mut out: String = line.chars().filter(|c| !c.is_control()).take(max).collect();
228    if line.chars().count() > max || s.trim().lines().nth(1).is_some() {
229        out.push('…');
230    }
231    out
232}
233
234fn with_network(title: String, args: &Value) -> String {
235    if args.get("network").and_then(Value::as_bool) == Some(true) { format!("{title} — with internet access") } else { title }
236}
237
238const NETWORK_DOC: &str = "Allow internet access for this run (off by default; the user is asked). Only set it when the task needs to download something.";
239
240/// `run_command`: a shell command in the workspace.
241pub struct RunCommand(Arc<Exec>);
242
243#[derive(Deserialize)]
244#[serde(deny_unknown_fields)]
245struct CommandArgs {
246    command: String,
247    #[serde(default)]
248    timeout_s: Option<f64>,
249    #[serde(default)]
250    network: bool,
251}
252
253impl Tool for RunCommand {
254    fn spec(&self) -> ToolSpec {
255        ToolSpec {
256            name: "run_command".into(),
257            description: "Run a shell command (`sh -c`) in the workspace folder and get its exit code, output and the files it created or changed. \
258                Sandboxed: it can read system files and read/write only the workspace (plus a private temp folder); no network unless `network` is true. \
259                Use it to inspect, search, convert or process files (e.g. `wc -l data.csv`, `head -5 data.csv`, `ls -R`). No interactive programs."
260                .into(),
261            parameters: json!({
262                "type": "object",
263                "properties": {
264                    "command": {"type": "string", "description": "The shell command, e.g. `ls -la` or `grep -c error log.txt`."},
265                    "timeout_s": {"type": "number", "description": format!("Stop it after this many seconds (default {DEFAULT_TIMEOUT_S}, max {MAX_TIMEOUT_S}).")},
266                    "network": {"type": "boolean", "description": NETWORK_DOC}
267                },
268                "required": ["command"]
269            }),
270        }
271    }
272
273    fn title(&self, args: &Value) -> String {
274        let cmd = args.get("command").and_then(Value::as_str).unwrap_or_default();
275        with_network(format!("Run `{}`", short(cmd, 60)), args)
276    }
277
278    fn pending_title(&self, args: &Value) -> String {
279        self.title(args)
280    }
281
282    fn access(&self, _args: &Value) -> Access {
283        Access::Execute
284    }
285
286    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
287        let a: CommandArgs = match parse_args(args) {
288            Ok(a) => a,
289            Err(e) => return ToolOutput::err(e),
290        };
291        if a.command.trim().is_empty() || a.command.len() > MAX_COMMAND_LEN || a.command.contains('\0') {
292            return ToolOutput::err(format!("the command must be non-empty text of at most {MAX_COMMAND_LEN} bytes"));
293        }
294        let job = Job {
295            program: "sh".into(),
296            args: vec!["-c".into(), a.command.into()],
297            network: a.network,
298            timeout: timeout_of(a.timeout_s),
299            read: Vec::new(),
300            write: Vec::new(),
301            env: Vec::new(),
302        };
303        self.0.run_in_workspace(job, |_| Ok(Vec::new()), ctx)
304    }
305}
306
307/// `run_python`: Python code (or a workspace script) in the workspace.
308pub struct RunPython(Arc<Exec>);
309
310#[derive(Deserialize)]
311#[serde(deny_unknown_fields)]
312struct PythonArgs {
313    #[serde(default)]
314    code: Option<String>,
315    #[serde(default)]
316    script: Option<String>,
317    #[serde(default)]
318    args: Vec<String>,
319    #[serde(default)]
320    timeout_s: Option<f64>,
321    #[serde(default)]
322    network: bool,
323}
324
325impl Tool for RunPython {
326    fn spec(&self) -> ToolSpec {
327        ToolSpec {
328            name: "run_python".into(),
329            description:
330                "Run Python 3 code with the workspace as the current folder (so `pd.read_csv('data.csv')` works) and get its output and the files it created. \
331                Use it to analyse data (pandas, numpy if installed) and to draw charts with matplotlib: save each figure as a PNG in the workspace, \
332                e.g. `plt.savefig('sales.png', dpi=150, bbox_inches='tight')` — saved images are shown to the user. `print` the numbers you need. \
333                Same sandbox as run_command (workspace only, no network unless `network` is true)."
334                    .into(),
335            parameters: json!({
336                "type": "object",
337                "properties": {
338                    "code": {"type": "string", "description": "Python source to run. Give this or `script`."},
339                    "script": {"type": "string", "description": "A .py file in the workspace to run instead of `code`."},
340                    "args": {"type": "array", "items": {"type": "string"}, "description": "Command-line arguments (sys.argv[1:])."},
341                    "timeout_s": {"type": "number", "description": format!("Stop it after this many seconds (default {DEFAULT_TIMEOUT_S}, max {MAX_TIMEOUT_S}).")},
342                    "network": {"type": "boolean", "description": NETWORK_DOC}
343                }
344            }),
345        }
346    }
347
348    fn title(&self, args: &Value) -> String {
349        let t = match args.get("script").and_then(Value::as_str) {
350            Some(s) => format!("Run {}", short(s, 60)),
351            None => "Run Python code".into(),
352        };
353        with_network(t, args)
354    }
355
356    fn pending_title(&self, args: &Value) -> String {
357        self.title(args)
358    }
359
360    fn access(&self, _args: &Value) -> Access {
361        Access::Execute
362    }
363
364    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
365        let a: PythonArgs = match parse_args(args) {
366            Ok(a) => a,
367            Err(e) => return ToolOutput::err(e),
368        };
369        if a.args.len() > MAX_ARGS || a.args.iter().any(|s| s.contains('\0') || s.len() > 4096) {
370            return ToolOutput::err(format!("at most {MAX_ARGS} arguments, each under 4096 bytes"));
371        }
372        let Some(py) = Python::resolve(self.0.data_dir.as_deref()) else {
373            return ToolOutput::err(format!("No Python found: install python3 (or set {}).", python::PYTHON_ENV));
374        };
375        let script = match (a.code, a.script) {
376            (Some(code), None) if code.len() <= MAX_CODE_LEN && !code.contains('\0') => Source::Code(code),
377            (Some(_), None) => return ToolOutput::err(format!("code must be text of at most {MAX_CODE_LEN} bytes")),
378            (None, Some(s)) => match byob_tools::sandbox::resolve_follow(ctx.workspace, &s) {
379                Ok(r) if r.abs.is_file() => Source::Script(r.abs),
380                Ok(r) => return ToolOutput::err(format!("{} is not a file in the workspace", r.show())),
381                Err(e) => return ToolOutput::err(e),
382            },
383            _ => return ToolOutput::err("give exactly one of `code` or `script`"),
384        };
385        let user_args: Vec<OsString> = a.args.into_iter().map(OsString::from).collect();
386        let job = Job {
387            program: py.path.clone().into_os_string(),
388            args: Vec::new(),
389            network: a.network,
390            timeout: timeout_of(a.timeout_s),
391            read: py.read_paths(),
392            write: Vec::new(),
393            env: Vec::new(),
394        };
395        self.0.run_in_workspace(
396            job,
397            move |tmp| {
398                let path = match script {
399                    Source::Script(p) => p,
400                    Source::Code(code) => {
401                        let p = tmp.join("main.py");
402                        std::fs::write(&p, code).map_err(|e| format!("can't write the code to a temp file: {e}"))?;
403                        p
404                    }
405                };
406                let mut v = vec![path.into_os_string()];
407                v.extend(user_args);
408                Ok(v)
409            },
410            ctx,
411        )
412    }
413}
414
415enum Source {
416    Code(String),
417    Script(PathBuf),
418}
419
420/// `install_python_packages`: add packages to byob's managed venv (created on first use)
421/// with `uv`. Wheels only (`--only-binary :all:`), so installing never runs package code.
422pub struct InstallPythonPackages(Arc<Exec>);
423
424#[derive(Deserialize)]
425#[serde(deny_unknown_fields)]
426struct InstallArgs {
427    packages: Vec<String>,
428}
429
430impl Tool for InstallPythonPackages {
431    fn spec(&self) -> ToolSpec {
432        ToolSpec {
433            name: "install_python_packages".into(),
434            description: "Install Python packages (from PyPI, prebuilt wheels only) into byob's own Python environment, which run_python then uses. \
435                Use it when run_python fails with ModuleNotFoundError, e.g. packages: [\"pandas\", \"matplotlib\"]. Needs internet; the user is asked."
436                .into(),
437            parameters: json!({
438                "type": "object",
439                "properties": {
440                    "packages": {"type": "array", "items": {"type": "string"}, "description": "Package names, optionally with versions, e.g. \"pandas\" or \"numpy>=2\"."}
441                },
442                "required": ["packages"]
443            }),
444        }
445    }
446
447    fn title(&self, args: &Value) -> String {
448        let names: Vec<&str> = args.get("packages").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).take(6).collect()).unwrap_or_default();
449        format!("Install Python packages: {}", short(&names.join(", "), 80))
450    }
451
452    fn pending_title(&self, args: &Value) -> String {
453        self.title(args)
454    }
455
456    fn access(&self, _args: &Value) -> Access {
457        Access::Network
458    }
459
460    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
461        let a: InstallArgs = match parse_args(args) {
462            Ok(a) => a,
463            Err(e) => return ToolOutput::err(e),
464        };
465        if a.packages.is_empty() || a.packages.len() > MAX_PACKAGES {
466            return ToolOutput::err(format!("give 1 to {MAX_PACKAGES} packages"));
467        }
468        if let Some(bad) = a.packages.iter().find(|p| !python::valid_requirement(p)) {
469            return ToolOutput::err(format!("{bad:?} is not a package name (like \"pandas\" or \"numpy>=2\")"));
470        }
471        let Some(data) = self.0.data_dir.as_deref() else { return ToolOutput::err("byob has no data folder for a Python environment") };
472        match install(&self.0, data, &a.packages, ctx) {
473            Ok(text) => ToolOutput::ok(text),
474            Err(e) => ToolOutput::err(e),
475        }
476    }
477}
478
479/// Create the managed venv if needed and install `packages` into it. Usable by the app
480/// directly (e.g. a "set up Python for data analysis" button). Runs in the sandbox with
481/// network on, writing only under `<data>/python`.
482pub fn install(exec: &Exec, data_dir: &Path, packages: &[String], ctx: &ToolContext<'_>) -> Result<String, String> {
483    let uv = python::which("uv".as_ref()).ok_or("uv is not installed (https://docs.astral.sh/uv/); it's needed to install Python packages")?;
484    let root = python::managed_root(data_dir);
485    std::fs::create_dir_all(&root).map_err(|e| format!("can't create {}: {e}", root.display()))?;
486    let root = root.canonicalize().map_err(|e| format!("{}: {e}", root.display()))?;
487    let venv = root.join("venv");
488    let tmp = TempDir::new("byob-install-")?;
489    let mut read: Vec<PathBuf> = uv.canonicalize().ok().and_then(|p| p.parent().map(Path::to_path_buf)).into_iter().collect();
490    let base = python::system_python();
491    if let Some(b) = &base {
492        read.extend(Python { path: b.clone(), managed: false }.read_paths());
493    }
494    let env = vec![
495        ("UV_CACHE_DIR".to_owned(), root.join("cache").into_os_string()),
496        ("UV_PYTHON_INSTALL_DIR".to_owned(), root.join("interpreters").into_os_string()),
497        ("UV_NO_CONFIG".to_owned(), "1".into()),
498    ];
499    let job = |args: Vec<OsString>| Job {
500        program: uv.clone().into_os_string(),
501        args,
502        network: true,
503        timeout: INSTALL_TIMEOUT,
504        read: read.clone(),
505        write: vec![root.clone()],
506        env: env.clone(),
507    };
508    let mut log = String::new();
509    let python_bin = python::venv_python(&venv);
510    if !python_bin.exists() {
511        let mut args: Vec<OsString> = vec!["venv".into(), "--quiet".into()];
512        if let Some(b) = &base {
513            args.extend(["--python".into(), b.clone().into_os_string()]);
514        }
515        args.push(venv.clone().into_os_string());
516        let out = exec.run(job(args), &root, tmp.path(), ctx)?;
517        if !out.success() {
518            return Err(format!("creating the Python environment failed:\n{}", out.stderr.text().trim()));
519        }
520        log.push_str(&format!("Created a Python environment in {}.\n", venv.display()));
521    }
522    let mut args: Vec<OsString> = vec!["pip".into(), "install".into(), "--only-binary".into(), ":all:".into(), "--python".into(), python_bin.into_os_string()];
523    args.extend(packages.iter().map(OsString::from));
524    let out = exec.run(job(args), &root, tmp.path(), ctx)?;
525    let detail = [out.stdout.text(), out.stderr.text()].iter().map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect::<Vec<_>>().join("\n");
526    if out.cancelled {
527        return Err("Stopped by the user.".into());
528    }
529    if !out.success() {
530        return Err(format!("installing failed:\n{detail}"));
531    }
532    log.push_str(&format!("Installed {}. run_python now uses this environment.\n{detail}", packages.join(", ")));
533    Ok(log.trim_end().to_owned())
534}
535
536#[cfg(test)]
537mod tests {
538    use super::*;
539
540    fn exec() -> Arc<Exec> {
541        Arc::new(Exec { mode: Mode::Unsandboxed, data_dir: None })
542    }
543
544    #[test]
545    fn titles_show_network_and_stay_short() {
546        let t = RunCommand(exec());
547        assert_eq!(t.title(&json!({"command": "ls -la"})), "Run `ls -la`");
548        assert_eq!(t.title(&json!({"command": "curl x", "network": true})), "Run `curl x` — with internet access");
549        assert!(t.title(&json!({"command": "a\nb"})).ends_with("…`"));
550        assert!(t.title(&json!({"command": "x".repeat(500)})).chars().count() < 80);
551        assert_eq!(t.title(&json!(null)), "Run ``");
552        let p = RunPython(exec());
553        assert_eq!(p.title(&json!({"code": "print(1)"})), "Run Python code");
554        assert_eq!(p.title(&json!({"script": "a.py", "network": true})), "Run a.py — with internet access");
555        assert_eq!(InstallPythonPackages(exec()).title(&json!({"packages": ["pandas", "numpy"]})), "Install Python packages: pandas, numpy");
556    }
557
558    #[test]
559    fn access_levels() {
560        assert_eq!(RunCommand(exec()).access(&json!({})), Access::Execute);
561        assert_eq!(RunPython(exec()).access(&json!({})), Access::Execute);
562        assert_eq!(InstallPythonPackages(exec()).access(&json!({})), Access::Network);
563    }
564
565    #[test]
566    fn timeouts_are_clamped() {
567        assert_eq!(timeout_of(None), Duration::from_secs(DEFAULT_TIMEOUT_S));
568        assert_eq!(timeout_of(Some(1e9)), Duration::from_secs(MAX_TIMEOUT_S));
569        assert_eq!(timeout_of(Some(-3.0)), Duration::from_secs(DEFAULT_TIMEOUT_S));
570        assert_eq!(timeout_of(Some(f64::NAN)), Duration::from_secs(DEFAULT_TIMEOUT_S));
571        assert_eq!(timeout_of(Some(0.01)), Duration::from_secs(1));
572    }
573
574    #[test]
575    fn bad_arguments_are_refused_before_running() {
576        let d = tempfile::tempdir().unwrap();
577        let cancel = std::sync::atomic::AtomicBool::new(false);
578        let ctx = ToolContext::new(d.path(), &cancel);
579        let e = exec();
580        for args in [json!({}), json!({"command": ""}), json!({"command": 1}), json!({"command": "ls", "extra": 1})] {
581            assert!(RunCommand(Arc::clone(&e)).run(&args, &ctx).failed, "{args}");
582        }
583        for args in [json!({}), json!({"code": "1", "script": "a.py"}), json!({"script": "../x.py"}), json!({"script": "missing.py"})] {
584            let out = RunPython(Arc::clone(&e)).run(&args, &ctx);
585            assert!(out.failed, "{args}");
586        }
587        for args in [json!({"packages": []}), json!({"packages": ["--index-url=http://evil"]}), json!({"packages": ["a b"]})] {
588            assert!(InstallPythonPackages(Arc::clone(&e)).run(&args, &ctx).failed, "{args}");
589        }
590    }
591
592    #[test]
593    fn specs_are_valid() {
594        let mut reg = Registry::default();
595        register(&mut reg, Exec { mode: Mode::Unsandboxed, data_dir: None });
596        assert!(reg.get("run_command").is_some() && reg.get("run_python").is_some());
597        assert!(reg.get("install_python_packages").is_none(), "no data dir, no installer");
598        for s in reg.specs() {
599            assert_eq!(s.parameters["type"], "object");
600        }
601    }
602}