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), [`InstallPackages`] (`install_packages`,
3//! programs and Python libraries for the workspace, with Nix or pixi, or in the workspace's
4//! container), [`InstallPythonPackages`] (`install_python_packages`, into byob's managed
5//! venv with `uv`, where there is no package manager for `install_packages`) and
6//! [`InstallSystemPackages`] (`install_system_packages`, Homebrew/winget, the last resort a
7//! person approves every time).
8//!
9//! Every run is prepared by [`env::Envs`]: it runs in the workspace's container if the user
10//! opted in; otherwise installed packages, the workspace's `.venv` and (once the user agreed)
11//! its dev shell go on `PATH`, and the `nix` CLI works inside the sandbox.
12//!
13//! Everything runs through [`byob_sandbox`]: read the system, read+write the workspace and
14//! a private temp folder, no network unless the call asks (and the user approves), a
15//! minimal environment without inherited secrets, wall-clock timeout, bounded output,
16//! and the whole process tree is killed on timeout or Stop. Where the OS can't sandbox
17//! (no Landlock), commands still run, with a warning in the log and in the tool output;
18//! `BYOB_SANDBOX=off` turns the sandbox off explicitly ([`Mode::Unsandboxed`]).
19#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
20
21pub mod env;
22pub mod python;
23pub mod shell;
24
25use std::ffi::OsString;
26use std::path::{Path, PathBuf};
27use std::process::Command;
28use std::sync::Arc;
29use std::time::Duration;
30
31use env::{Envs, Layer, Runner, hints};
32
33use byob_sandbox::{Limits, Outcome, Policy, RunOptions, Sandbox, Snapshot, TempDir};
34use byob_tools::{Access, FileChange, Registry, Tool, ToolContext, ToolOutput, ToolSpec, parse_args};
35use serde::Deserialize;
36use serde_json::{Value, json};
37
38pub use python::Python;
39use shell::Shell;
40
41pub const DEFAULT_TIMEOUT_S: u64 = 120;
42pub const MAX_TIMEOUT_S: u64 = 600;
43const INSTALL_TIMEOUT: Duration = Duration::from_secs(900);
44/// Bytes kept per stream (head and tail halves) for the model.
45pub const MAX_OUTPUT: usize = 24 * 1024;
46const MAX_COMMAND_LEN: usize = 64 * 1024;
47const MAX_CODE_LEN: usize = 512 * 1024;
48const MAX_ARGS: usize = 64;
49const MAX_PACKAGES: usize = 20;
50/// Most changed files listed in the text the model sees.
51const MAX_LISTED: usize = 30;
52
53/// How commands run.
54#[derive(Debug, Clone)]
55pub enum Mode {
56    Sandboxed(Sandbox),
57    /// The user turned the sandbox off (`BYOB_SANDBOX=off`): plain child processes, still
58    /// with the clean environment, timeout, output caps and group kill.
59    Unsandboxed,
60}
61
62impl Mode {
63    /// `Unsandboxed` if the user opted out (logged), else the sandbox via this binary.
64    /// Logs what the sandbox can enforce here (a warning if it can't confine anything).
65    pub fn from_env() -> Result<Self, String> {
66        if byob_sandbox::disabled_by_user() {
67            log::warn!("{}=off: commands and Python run WITHOUT a sandbox", byob_sandbox::DISABLE_ENV);
68            return Ok(Self::Unsandboxed);
69        }
70        let sb = Sandbox::from_current_exe()?;
71        let e = sb.probe();
72        if e.confined() {
73            log::info!("sandbox: filesystem {}, network {}, process tree {}", e.filesystem, e.network, e.process_tree);
74        } else {
75            log::warn!("sandbox unavailable ({}); commands and Python will run WITHOUT one", e.notes.join("; "));
76        }
77        Ok(Self::Sandboxed(sb))
78    }
79
80    /// A note for the model/user when runs aren't actually confined.
81    fn unconfined_note(&self) -> Option<String> {
82        match self {
83            Self::Unsandboxed => Some(format!("ran without a sandbox: {}=off", byob_sandbox::DISABLE_ENV)),
84            Self::Sandboxed(sb) => {
85                let e = sb.probe();
86                (!e.confined()).then(|| format!("ran without a sandbox: {}", e.notes.join("; ")))
87            }
88        }
89    }
90}
91
92/// Shared by the tools.
93#[derive(Debug, Clone)]
94pub struct Exec {
95    pub mode: Mode,
96    /// byob's data folder (holds the managed Python venv and installed packages); `None`
97    /// disables them.
98    pub data_dir: Option<PathBuf>,
99    /// Package managers and workspace environments ([`Envs::none`] for neither).
100    pub envs: Arc<Envs>,
101}
102
103impl Exec {
104    /// Detects the package managers on this machine.
105    pub fn new(mode: Mode, data_dir: Option<PathBuf>) -> Self {
106        let envs = Arc::new(Envs::detect(data_dir.as_deref()));
107        Self { mode, data_dir, envs }
108    }
109
110    /// Like [`Exec::new`], with the container settings (default image; `docker` or `podman`).
111    pub fn with_containers(mode: Mode, data_dir: Option<PathBuf>, image: Option<String>, runtime: Option<&str>) -> Self {
112        let found = env::Found::detect_with(data_dir.as_deref(), image, runtime);
113        let envs = Arc::new(Envs::new(data_dir.as_deref(), found, env::ProjectMode::from_env()));
114        Self { mode, data_dir, envs }
115    }
116
117    /// What the system prompt should say about getting software, if anything.
118    pub fn prompt(&self) -> Option<String> {
119        self.envs.prompt()
120    }
121
122    fn fix(&self) -> hints::Fix {
123        if self.envs.installer().is_some() {
124            hints::Fix::Packages
125        } else if self.data_dir.is_some() && python::which("uv".as_ref()).is_some() {
126            hints::Fix::PythonOnly
127        } else {
128            hints::Fix::None
129        }
130    }
131}
132
133/// Register `run_command`, `run_python`, and — when there's a data folder — either
134/// `install_packages` (a package manager like Nix is installed) or, failing that,
135/// `install_python_packages` (`uv` is installed).
136pub fn register(reg: &mut Registry, exec: Exec) {
137    let exec = Arc::new(exec);
138    reg.register(Arc::new(RunCommand(Arc::clone(&exec))));
139    reg.register(Arc::new(RunPython(Arc::clone(&exec))));
140    match exec.fix() {
141        hints::Fix::Packages => reg.register(Arc::new(InstallPackages(Arc::clone(&exec)))),
142        hints::Fix::PythonOnly => reg.register(Arc::new(InstallPythonPackages(Arc::clone(&exec)))),
143        hints::Fix::None => {}
144    }
145    // Workspaces that run in a container install there.
146    if exec.envs.containers().is_some() && reg.get("install_packages").is_none() {
147        reg.register(Arc::new(InstallPackages(Arc::clone(&exec))));
148    }
149    if exec.envs.system().is_some() {
150        reg.register(Arc::new(InstallSystemPackages(exec)));
151    }
152}
153
154/// One sandboxed invocation (what an [`env::EnvProvider`] hands its [`env::Runner`]).
155pub struct Job {
156    pub program: OsString,
157    pub args: Vec<OsString>,
158    pub network: bool,
159    pub timeout: Duration,
160    /// `PATH` entries, variables and sandbox access on top of the clean environment.
161    pub layer: Layer,
162    /// Variables set last (after the layer's).
163    pub env: Vec<(String, OsString)>,
164    /// No address-space limit: package managers (pixi) map far more than they use.
165    pub big_memory: bool,
166    /// Bytes of each stream kept (head and tail), [`MAX_OUTPUT`] unless raised.
167    pub max_output: usize,
168}
169
170impl Job {
171    pub fn new(program: OsString, args: Vec<OsString>, timeout: Duration) -> Self {
172        Self { program, args, network: false, timeout, layer: Layer::default(), env: Vec::new(), big_memory: false, max_output: MAX_OUTPUT }
173    }
174}
175
176/// The variables [`byob_sandbox::clean_env`] sets for a run with temp folder `tmp`.
177pub(crate) fn clean_env_vars(tmp: &Path) -> Vec<(String, String)> {
178    let mut cmd = Command::new("true");
179    byob_sandbox::clean_env(&mut cmd, tmp);
180    cmd.get_envs().filter_map(|(k, v)| Some((k.to_str()?.to_owned(), v?.to_str()?.to_owned()))).collect()
181}
182
183/// Runs provider jobs (dev shell loading, installs) in the tool call's sandbox.
184struct CallRunner<'a> {
185    exec: &'a Exec,
186    ctx: &'a ToolContext<'a>,
187}
188
189impl Runner for CallRunner<'_> {
190    fn run(&self, job: Job, cwd: &Path, tmp: &Path) -> Result<Outcome, String> {
191        self.exec.run(job, cwd, tmp, self.ctx)
192    }
193
194    fn ask(&self, q: &byob_tools::Question) -> byob_tools::Answer {
195        self.ctx.ask(q)
196    }
197
198    fn cancelled(&self) -> bool {
199        self.ctx.cancelled()
200    }
201
202    fn plan(&self) -> byob_tools::EnvPlan {
203        self.ctx.env()
204    }
205
206    fn chat(&self) -> Option<String> {
207        self.ctx.chat().map(str::to_owned)
208    }
209}
210
211impl Exec {
212    /// Run `job` with `tmp` as its private temp folder.
213    fn run(&self, job: Job, cwd: &Path, tmp: &Path, ctx: &ToolContext<'_>) -> Result<Outcome, String> {
214        let secs = job.timeout.as_secs().max(1);
215        let mut layer = job.layer;
216        layer.stack(&self.envs.support());
217        let host_path = std::env::var_os("PATH");
218        let path = (!layer.path.is_empty()).then(|| env::join_path(&layer.path, host_path.as_deref()));
219        let mut cmd = match &self.mode {
220            Mode::Sandboxed(sb) => {
221                let mut policy = Policy::for_workspace(cwd, tmp)
222                    .network(job.network)
223                    .limits(Limits { memory_bytes: if job.big_memory { None } else { Limits::for_timeout(secs).memory_bytes }, ..Limits::for_timeout(secs) })
224                    // Where the OS can't confine, run anyway (warned at startup and in the output).
225                    .allow_unsandboxed(true)
226                    .allow_path_dirs(path.as_deref().or(host_path.as_deref()));
227                for p in &layer.read {
228                    policy = policy.allow_read(p);
229                }
230                for p in &layer.write {
231                    policy = policy.allow_write(p);
232                }
233                // The other folders the project works in (its own is the workspace).
234                for p in byob_tools::sandbox::linked(ctx.workspace) {
235                    policy = policy.allow_write(&p);
236                }
237                for p in &layer.sockets {
238                    policy = policy.allow_unix_socket(p);
239                }
240                sb.command(&policy, &job.program, &job.args)
241            }
242            Mode::Unsandboxed => {
243                let mut c = Command::new(&job.program);
244                c.args(&job.args);
245                c
246            }
247        };
248        cmd.current_dir(cwd);
249        byob_sandbox::clean_env(&mut cmd, tmp);
250        if let Some(p) = path {
251            cmd.env("PATH", p);
252        }
253        for (k, v) in &layer.vars {
254            if !env::keep_var(k) {
255                cmd.env(k, v);
256            }
257        }
258        cmd.envs(job.env);
259        let opts = RunOptions { timeout: job.timeout, max_output: job.max_output, ..Default::default() };
260        let out = byob_sandbox::run(cmd, &opts, &|| ctx.cancelled())?;
261        match out.sandbox_error() {
262            Some(e) => Err(format!(
263                "the sandbox couldn't start: {e}. Nothing ran. (The user can set {}=off to run commands without a sandbox.)",
264                byob_sandbox::DISABLE_ENV
265            )),
266            None => Ok(out),
267        }
268    }
269
270    /// Run in the workspace and describe the result (output + changed files) for the model.
271    /// `build` makes the job from the workspace environment's layer; `prepare` adds
272    /// arguments once the run's temp folder exists.
273    fn run_in_workspace(
274        &self,
275        build: impl FnOnce(&Layer, Where) -> Result<Job, String>,
276        prepare: impl FnOnce(&Path) -> Result<Vec<OsString>, String>,
277        command: Option<&str>,
278        ctx: &ToolContext<'_>,
279    ) -> ToolOutput {
280        if ctx.cancelled() {
281            return ToolOutput::err("Stopped by the user.");
282        }
283        let root = match byob_tools::sandbox::root(ctx.workspace) {
284            Ok(r) => r,
285            Err(e) => return ToolOutput::err(e),
286        };
287        let mut notes = Vec::new();
288        if let Some(ready) = self.envs.container(&root, &CallRunner { exec: self, ctx }, &mut notes) {
289            let out = match ready {
290                Ok(r) => self.run_in_container(&r, build, prepare, command, &root, ctx),
291                Err(e) => ToolOutput::err(e),
292            };
293            return with_notes(out, &notes);
294        }
295        let mut prepared = self.envs.prepare(&root, &CallRunner { exec: self, ctx });
296        notes.append(&mut prepared.notes);
297        prepared.notes = notes;
298        if ctx.cancelled() {
299            return ToolOutput::err("Stopped by the user.");
300        }
301        let mut job = match build(&prepared.layer, Where::Host) {
302            Ok(j) => j,
303            Err(e) => return with_notes(ToolOutput::err(e), &prepared.notes),
304        };
305        job.layer.stack(&prepared.layer);
306        let tmp = match TempDir::new("byob-run-") {
307            Ok(t) => t,
308            Err(e) => return ToolOutput::err(e),
309        };
310        match prepare(tmp.path()) {
311            Ok(extra) => job.args.extend(extra),
312            Err(e) => return ToolOutput::err(e),
313        }
314        let timeout = job.timeout;
315        let before = Snapshot::take(&root);
316        let out = match self.run(job, &root, tmp.path(), ctx) {
317            Ok(o) => o,
318            Err(e) => return ToolOutput::err(e),
319        };
320        let changes = before.changes(&Snapshot::take(&root));
321        let mut res = describe(&out, &changes, &root, timeout, self.mode.unconfined_note());
322        if res.failed
323            && let Some(h) =
324                hints::hint(&out.stdout.text(), &out.stderr.text(), command, self.fix(), self.envs.system().map(env::system::SystemInstaller::name))
325        {
326            res.text.push_str(&format!("\n\n{h}"));
327        }
328        with_notes(res, &prepared.notes)
329    }
330}
331
332impl Exec {
333    /// [`Exec::run_in_workspace`] inside the workspace's container.
334    fn run_in_container(
335        &self,
336        ready: &env::container::Ready,
337        build: impl FnOnce(&Layer, Where) -> Result<Job, String>,
338        prepare: impl FnOnce(&Path) -> Result<Vec<OsString>, String>,
339        command: Option<&str>,
340        root: &Path,
341        ctx: &ToolContext<'_>,
342    ) -> ToolOutput {
343        let Some(containers) = self.envs.containers() else { return ToolOutput::err("no container runtime") };
344        let job = match build(&Layer::default(), Where::Container) {
345            Ok(j) => j,
346            Err(e) => return ToolOutput::err(e),
347        };
348        let tmp = match env::container::RunTmp::new(&ready.tmp_base) {
349            Ok(t) => t,
350            Err(e) => return ToolOutput::err(e),
351        };
352        let mut argv = vec![job.program];
353        argv.extend(job.args);
354        match prepare(tmp.path()) {
355            Ok(extra) => argv.extend(extra),
356            Err(e) => return ToolOutput::err(e),
357        }
358        let timeout = job.timeout;
359        let run = env::container::Exec { argv, env: job.env, network: job.network, timeout };
360        let before = Snapshot::take(root);
361        let (out, problem) = match containers.exec(ready, run, root, tmp.path(), &|| ctx.cancelled()) {
362            Ok(o) => o,
363            Err(e) => return ToolOutput::err(e),
364        };
365        let changes = before.changes(&Snapshot::take(root));
366        let mut res = describe(&out, &changes, root, timeout, problem);
367        if res.failed
368            && let Some(h) = hints::hint(&out.stdout.text(), &out.stderr.text(), command, hints::Fix::Packages, None)
369        {
370            res.text.push_str(&format!("\n\n{h}"));
371        }
372        res
373    }
374}
375
376/// Where a job runs: here (in the sandbox) or in the workspace's container.
377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
378enum Where {
379    Host,
380    Container,
381}
382
383/// Put the environment's one-time notes in front of a tool's output.
384fn with_notes(mut out: ToolOutput, notes: &[String]) -> ToolOutput {
385    if !notes.is_empty() {
386        out.text = format!("({})\n\n{}", notes.join(")\n("), out.text);
387    }
388    out
389}
390
391fn describe(out: &Outcome, changes: &byob_sandbox::Changes, root: &Path, timeout: Duration, unconfined: Option<String>) -> ToolOutput {
392    let mut text = String::new();
393    if out.cancelled {
394        text.push_str("Stopped by the user.\n");
395    } else if out.timed_out {
396        text.push_str(&format!("Timed out after {} s and was stopped (with everything it started).\n", timeout.as_secs()));
397    } else {
398        match (out.exit_code, out.signal) {
399            (Some(c), _) => text.push_str(&format!("Exit code: {c}\n")),
400            (None, Some(s)) => text.push_str(&format!("Killed by signal {s}\n")),
401            (None, None) => text.push_str("Exit code: unknown\n"),
402        }
403    }
404    for (name, cap) in [("stdout", &out.stdout), ("stderr", &out.stderr)] {
405        let t = cap.text();
406        // Nix's warning in a run without network is misleading: the daemon still downloads.
407        let t = if name == "stderr" { t.replace(env::nix::OFFLINE_WARNING, "").trim_start_matches('\n').to_owned() } else { t };
408        if !t.trim().is_empty() {
409            text.push_str(&format!("\n{name}:\n{}\n", t.trim_end()));
410        }
411    }
412    let rel = |p: &PathBuf| byob_tools::sandbox::slash(p.strip_prefix(root).unwrap_or(p));
413    for (label, list) in [("Files created", &changes.created), ("Files modified", &changes.modified), ("Files deleted", &changes.deleted)] {
414        if list.is_empty() {
415            continue;
416        }
417        let mut names: Vec<String> = list.iter().take(MAX_LISTED).map(rel).collect();
418        if list.len() > MAX_LISTED {
419            names.push(format!("… and {} more", list.len() - MAX_LISTED));
420        }
421        text.push_str(&format!("\n{label}: {}\n", names.join(", ")));
422    }
423    if !text.contains("\nstdout:\n") && !text.contains("\nstderr:\n") && changes.is_empty() && out.success() {
424        text.push_str("(no output)\n");
425    }
426    if let Some(note) = unconfined {
427        text.push_str(&format!("\n({note})\n"));
428    }
429    let mut fc: Vec<FileChange> = changes.created.iter().cloned().map(FileChange::Created).collect();
430    fc.extend(changes.modified.iter().cloned().map(FileChange::Modified));
431    fc.extend(changes.deleted.iter().cloned().map(FileChange::Deleted));
432    ToolOutput { text: text.trim_end().to_owned(), failed: !out.success(), changes: fc, images: Vec::new() }
433}
434
435fn timeout_of(secs: Option<f64>) -> Duration {
436    let s = secs.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(DEFAULT_TIMEOUT_S as f64);
437    Duration::from_secs_f64(s.min(MAX_TIMEOUT_S as f64).max(1.0))
438}
439
440/// One line, at most `max` chars, for titles.
441fn short(s: &str, max: usize) -> String {
442    let line = s.trim().lines().next().unwrap_or_default();
443    let mut out: String = line.chars().filter(|c| !c.is_control()).take(max).collect();
444    if line.chars().count() > max || s.trim().lines().nth(1).is_some() {
445        out.push('…');
446    }
447    out
448}
449
450fn with_network(title: String, args: &Value) -> String {
451    if args.get("network").and_then(Value::as_bool) == Some(true) { format!("{title} — with internet access") } else { title }
452}
453
454const 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.";
455
456/// `run_command`: a shell command in the workspace.
457pub struct RunCommand(Arc<Exec>);
458
459#[derive(Deserialize)]
460#[serde(deny_unknown_fields)]
461struct CommandArgs {
462    command: String,
463    #[serde(default)]
464    timeout_s: Option<f64>,
465    #[serde(default)]
466    network: bool,
467}
468
469impl Tool for RunCommand {
470    fn spec(&self) -> ToolSpec {
471        ToolSpec {
472            name: "run_command".into(),
473            description: format!(
474                "Run a shell command ({}) in the workspace folder and get its exit code, output and the files it created or changed. {} \
475                Use it to inspect, search, convert or process files (e.g. {}). No interactive programs.{}",
476                shell_doc(),
477                if cfg!(windows) {
478                    "Not sandboxed on Windows: it runs as the user, with no network rule."
479                } else {
480                    "Sandboxed: it can read system files and read/write only the workspace (plus a private temp folder); no network unless `network` is true."
481                },
482                if cfg!(windows) {
483                    "`Get-ChildItem -Recurse`, `(Get-Content data.csv).Count`, `Get-Content data.csv -TotalCount 5`"
484                } else {
485                    "`wc -l data.csv`, `head -5 data.csv`, `ls -R`"
486                },
487                self.0.envs.installer().map_or(String::new(), |_| {
488                    " Packages from install_packages are on PATH, and so is the workspace's own environment (flake.nix, pixi.toml, …) once the user agrees to load it. \
489                    If a program is missing, call install_packages instead of pip, apt or sudo."
490                        .into()
491                })
492            ),
493            parameters: json!({
494                "type": "object",
495                "properties": {
496                    "command": {"type": "string", "description": if cfg!(windows) {
497                        "The PowerShell command, e.g. `Get-ChildItem` or `(Select-String error log.txt).Count`."
498                    } else {
499                        "The shell command, e.g. `ls -la` or `grep -c error log.txt`."
500                    }},
501                    "timeout_s": {"type": "number", "description": format!("Stop it after this many seconds (default {DEFAULT_TIMEOUT_S}, max {MAX_TIMEOUT_S}).")},
502                    "network": {"type": "boolean", "description": NETWORK_DOC}
503                },
504                "required": ["command"]
505            }),
506        }
507    }
508
509    fn title(&self, args: &Value) -> String {
510        let cmd = args.get("command").and_then(Value::as_str).unwrap_or_default();
511        with_network(format!("Run `{}`", short(cmd, 60)), args)
512    }
513
514    fn pending_title(&self, args: &Value) -> String {
515        self.title(args)
516    }
517
518    fn access(&self, _args: &Value) -> Access {
519        Access::Execute
520    }
521
522    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
523        let a: CommandArgs = match parse_args(args) {
524            Ok(a) => a,
525            Err(e) => return ToolOutput::err(e),
526        };
527        if a.command.trim().is_empty() || a.command.len() > MAX_COMMAND_LEN || a.command.contains('\0') {
528            return ToolOutput::err(format!("the command must be non-empty text of at most {MAX_COMMAND_LEN} bytes"));
529        }
530        let command = a.command.clone();
531        let build = |_: &Layer, at: Where| {
532            let shell = if at == Where::Container { Shell::Sh } else { Shell::host() };
533            let (program, args) = shell.argv(&a.command);
534            let mut job = Job::new(program, args, timeout_of(a.timeout_s));
535            job.network = a.network;
536            Ok(job)
537        };
538        self.0.run_in_workspace(build, |_| Ok(Vec::new()), Some(&command), ctx)
539    }
540}
541
542/// How `run_command`'s description names its shell.
543fn shell_doc() -> String {
544    match Shell::host() {
545        Shell::Sh => Shell::Sh.describe().into(),
546        // A workspace container is Linux whatever the host.
547        h => format!("{} on Windows; `sh -c` when the workspace runs in a container", h.describe()),
548    }
549}
550
551/// `run_python`: Python code (or a workspace script) in the workspace.
552pub struct RunPython(Arc<Exec>);
553
554#[derive(Deserialize)]
555#[serde(deny_unknown_fields)]
556struct PythonArgs {
557    #[serde(default)]
558    code: Option<String>,
559    #[serde(default)]
560    script: Option<String>,
561    #[serde(default)]
562    args: Vec<String>,
563    #[serde(default)]
564    timeout_s: Option<f64>,
565    #[serde(default)]
566    network: bool,
567}
568
569impl Tool for RunPython {
570    fn spec(&self) -> ToolSpec {
571        ToolSpec {
572            name: "run_python".into(),
573            description:
574                "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. \
575                Use it to analyze data (pandas, numpy if installed) and to draw charts with matplotlib: save each figure as a PNG in the workspace, \
576                e.g. `plt.savefig('sales.png', dpi=150, bbox_inches='tight')` — saved images are shown to the user. `print` the numbers you need. \
577                Same sandbox as run_command (workspace only, no network unless `network` is true)."
578                    .into(),
579            parameters: json!({
580                "type": "object",
581                "properties": {
582                    "code": {"type": "string", "description": "Python source to run. Give this or `script`."},
583                    "script": {"type": "string", "description": "A .py file in the workspace to run instead of `code`."},
584                    "args": {"type": "array", "items": {"type": "string"}, "description": "Command-line arguments (sys.argv[1:])."},
585                    "timeout_s": {"type": "number", "description": format!("Stop it after this many seconds (default {DEFAULT_TIMEOUT_S}, max {MAX_TIMEOUT_S}).")},
586                    "network": {"type": "boolean", "description": NETWORK_DOC}
587                }
588            }),
589        }
590    }
591
592    fn title(&self, args: &Value) -> String {
593        let t = match args.get("script").and_then(Value::as_str) {
594            Some(s) => format!("Run {}", short(s, 60)),
595            None => "Run Python code".into(),
596        };
597        with_network(t, args)
598    }
599
600    fn pending_title(&self, args: &Value) -> String {
601        self.title(args)
602    }
603
604    fn access(&self, _args: &Value) -> Access {
605        Access::Execute
606    }
607
608    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
609        let a: PythonArgs = match parse_args(args) {
610            Ok(a) => a,
611            Err(e) => return ToolOutput::err(e),
612        };
613        if a.args.len() > MAX_ARGS || a.args.iter().any(|s| s.contains('\0') || s.len() > 4096) {
614            return ToolOutput::err(format!("at most {MAX_ARGS} arguments, each under 4096 bytes"));
615        }
616        let script = match (a.code, a.script) {
617            (Some(code), None) if code.len() <= MAX_CODE_LEN && !code.contains('\0') => Source::Code(code),
618            (Some(_), None) => return ToolOutput::err(format!("code must be text of at most {MAX_CODE_LEN} bytes")),
619            (None, Some(s)) => match byob_tools::sandbox::resolve_follow(ctx.workspace, &s) {
620                Ok(r) if r.abs.is_file() => Source::Script(r.abs),
621                Ok(r) => return ToolOutput::err(format!("{} is not a file in the workspace", r.show())),
622                Err(e) => return ToolOutput::err(e),
623            },
624            _ => return ToolOutput::err("give exactly one of `code` or `script`"),
625        };
626        let user_args: Vec<OsString> = a.args.into_iter().map(OsString::from).collect();
627        let data_dir = self.0.data_dir.clone();
628        let fix = self.0.fix();
629        let build = move |layer: &Layer, at: Where| {
630            if at == Where::Container {
631                let mut job = Job::new("python3".into(), Vec::new(), timeout_of(a.timeout_s));
632                job.network = a.network;
633                return Ok(job);
634            }
635            let Some(py) = Python::resolve_in(data_dir.as_deref(), &layer.path) else {
636                return Err(match fix {
637                    hints::Fix::Packages => "No Python found. Call install_packages with {\"packages\": [\"python3\"]} (add the libraries you need, e.g. \"matplotlib\"), then try again.".to_owned(),
638                    _ => format!("No Python found: install python3 (or set {}).", python::PYTHON_ENV),
639                });
640            };
641            let mut job = Job::new(py.path.clone().into_os_string(), Vec::new(), timeout_of(a.timeout_s));
642            job.network = a.network;
643            job.layer.read = py.read_paths();
644            Ok(job)
645        };
646        self.0.run_in_workspace(
647            build,
648            move |tmp| {
649                let path = match script {
650                    Source::Script(p) => p,
651                    Source::Code(code) => {
652                        let p = tmp.join("main.py");
653                        std::fs::write(&p, code).map_err(|e| format!("can't write the code to a temp file: {e}"))?;
654                        p
655                    }
656                };
657                let mut v = vec![path.into_os_string()];
658                v.extend(user_args);
659                Ok(v)
660            },
661            None,
662            ctx,
663        )
664    }
665}
666
667enum Source {
668    Code(String),
669    Script(PathBuf),
670}
671
672/// `install_python_packages`: add packages to byob's managed venv (created on first use)
673/// with `uv`. Wheels only (`--only-binary :all:`), so installing never runs package code.
674pub struct InstallPythonPackages(Arc<Exec>);
675
676#[derive(Deserialize)]
677#[serde(deny_unknown_fields)]
678struct InstallArgs {
679    packages: Vec<String>,
680}
681
682impl Tool for InstallPythonPackages {
683    fn spec(&self) -> ToolSpec {
684        ToolSpec {
685            name: "install_python_packages".into(),
686            description: "Install Python packages (from PyPI, prebuilt wheels only) into byob's own Python environment, which run_python then uses. \
687                Use it when run_python fails with ModuleNotFoundError, e.g. packages: [\"pandas\", \"matplotlib\"]. Needs internet; the user is asked."
688                .into(),
689            parameters: json!({
690                "type": "object",
691                "properties": {
692                    "packages": {"type": "array", "items": {"type": "string"}, "description": "Package names, optionally with versions, e.g. \"pandas\" or \"numpy>=2\"."}
693                },
694                "required": ["packages"]
695            }),
696        }
697    }
698
699    fn title(&self, args: &Value) -> String {
700        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();
701        format!("Install Python packages: {}", short(&names.join(", "), 80))
702    }
703
704    fn pending_title(&self, args: &Value) -> String {
705        self.title(args)
706    }
707
708    fn access(&self, _args: &Value) -> Access {
709        Access::Network
710    }
711
712    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
713        let a: InstallArgs = match parse_args(args) {
714            Ok(a) => a,
715            Err(e) => return ToolOutput::err(e),
716        };
717        if a.packages.is_empty() || a.packages.len() > MAX_PACKAGES {
718            return ToolOutput::err(format!("give 1 to {MAX_PACKAGES} packages"));
719        }
720        if let Some(bad) = a.packages.iter().find(|p| !python::valid_requirement(p)) {
721            return ToolOutput::err(format!("{bad:?} is not a package name (like \"pandas\" or \"numpy>=2\")"));
722        }
723        let Some(data) = self.0.data_dir.as_deref() else { return ToolOutput::err("byob has no data folder for a Python environment") };
724        match install(&self.0, data, &a.packages, ctx) {
725            Ok(text) => ToolOutput::ok(text),
726            Err(e) => ToolOutput::err(e),
727        }
728    }
729}
730
731/// `install_packages`: programs and Python libraries for this workspace, from the machine's
732/// package manager (Nix). They stay installed (per workspace) and are on `PATH` for every
733/// later `run_command` / `run_python`.
734pub struct InstallPackages(Arc<Exec>);
735
736impl Tool for InstallPackages {
737    fn spec(&self) -> ToolSpec {
738        let by = self.0.envs.installer().unwrap_or("the package manager");
739        ToolSpec {
740            name: "install_packages".into(),
741            description: format!(
742                "Install programs and Python libraries for this workspace with {by}, so run_command and run_python can use them. \
743                 Use it whenever a command is \"not found\" or Python says ModuleNotFoundError — not pip install, apt, brew or sudo, which don't work here. \
744                 Give package names: programs like \"jq\", \"ffmpeg\", \"imagemagick\", \"ripgrep\", \"nodejs\", \"pandoc\"; Python libraries by their pip name, \
745                 like \"matplotlib\", \"pandas\", \"scikit-learn\" (they go into run_python's python3). Packages stay installed for this workspace. \
746                 Needs internet; the user is asked."
747            ),
748            parameters: json!({
749                "type": "object",
750                "properties": {
751                    "packages": {"type": "array", "items": {"type": "string"}, "description": "Package names, e.g. [\"jq\", \"matplotlib\"]."}
752                },
753                "required": ["packages"]
754            }),
755        }
756    }
757
758    fn title(&self, args: &Value) -> String {
759        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();
760        format!("Install packages: {}", short(&names.join(", "), 80))
761    }
762
763    fn pending_title(&self, args: &Value) -> String {
764        self.title(args)
765    }
766
767    fn access(&self, _args: &Value) -> Access {
768        Access::Network
769    }
770
771    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
772        let a: InstallArgs = match parse_args(args) {
773            Ok(a) => a,
774            Err(e) => return ToolOutput::err(e),
775        };
776        if a.packages.is_empty() || a.packages.len() > MAX_PACKAGES {
777            return ToolOutput::err(format!("give 1 to {MAX_PACKAGES} packages"));
778        }
779        let root = match byob_tools::sandbox::root(ctx.workspace) {
780            Ok(r) => r,
781            Err(e) => return ToolOutput::err(e),
782        };
783        match self.0.envs.install(&root, &a.packages, &CallRunner { exec: &self.0, ctx }) {
784            Ok(done) => ToolOutput { text: done.text, failed: done.failed, changes: Vec::new(), images: Vec::new() },
785            Err(e) => ToolOutput::err(e),
786        }
787    }
788}
789
790/// `install_system_packages`: the last resort, Homebrew or winget, system-wide. Every call
791/// needs a person's approval (it is never auto-approved), and while there is a workspace
792/// installer it only takes packages `install_packages` couldn't find.
793pub struct InstallSystemPackages(Arc<Exec>);
794
795impl InstallSystemPackages {
796    fn names(args: &Value) -> Vec<String> {
797        args.get("packages")
798            .and_then(Value::as_array)
799            .map(|a| a.iter().filter_map(Value::as_str).take(MAX_PACKAGES).map(str::to_owned).collect())
800            .unwrap_or_default()
801    }
802
803    fn by(&self) -> &'static str {
804        self.0.envs.system().map_or("the system package manager", env::system::SystemInstaller::name)
805    }
806}
807
808impl Tool for InstallSystemPackages {
809    fn spec(&self) -> ToolSpec {
810        let by = self.by();
811        let first = match self.0.envs.installer() {
812            Some(_) => "Only for packages install_packages couldn't find: always try install_packages first.",
813            None => "Only when nothing else works.",
814        };
815        ToolSpec {
816            name: "install_system_packages".into(),
817            description: format!(
818                "Last resort: install programs SYSTEM-WIDE with {by}, outside the workspace and the sandbox. {first} \
819                 The user must approve every call and byob can't undo it, so say why you need it."
820            ),
821            parameters: json!({
822                "type": "object",
823                "properties": {
824                    "packages": {"type": "array", "items": {"type": "string"}, "description": format!("{by} package names, e.g. [\"jq\"].")}
825                },
826                "required": ["packages"]
827            }),
828        }
829    }
830
831    fn title(&self, args: &Value) -> String {
832        format!("Install system-wide with {}: {}", self.by(), short(&Self::names(args).join(", "), 80))
833    }
834
835    fn pending_title(&self, args: &Value) -> String {
836        self.title(args)
837    }
838
839    fn access(&self, _args: &Value) -> Access {
840        Access::Execute
841    }
842
843    fn always_ask(&self, args: &Value) -> Option<String> {
844        let names = Self::names(args);
845        Some(self.0.envs.system().map_or_else(|| "Installs system-wide.".to_owned(), |s| s.warning(&names)))
846    }
847
848    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
849        let a: InstallArgs = match parse_args(args) {
850            Ok(a) => a,
851            Err(e) => return ToolOutput::err(e),
852        };
853        if a.packages.is_empty() || a.packages.len() > MAX_PACKAGES {
854            return ToolOutput::err(format!("give 1 to {MAX_PACKAGES} packages"));
855        }
856        let Some(system) = self.0.envs.system() else { return ToolOutput::err("no system package manager here") };
857        let root = match byob_tools::sandbox::root(ctx.workspace) {
858            Ok(r) => r,
859            Err(e) => return ToolOutput::err(e),
860        };
861        if let Err(e) = self.0.envs.system_allowed(&root, &a.packages, &ctx.env()) {
862            return ToolOutput::err(e);
863        }
864        match system.install(&a.packages, &|| ctx.cancelled()) {
865            Ok(text) => ToolOutput::ok(text),
866            Err(e) => ToolOutput::err(e),
867        }
868    }
869}
870
871/// Create the managed venv if needed and install `packages` into it. Usable by the app
872/// directly (e.g. a "set up Python for data analysis" button). Runs in the sandbox with
873/// network on, writing only under `<data>/python`.
874pub fn install(exec: &Exec, data_dir: &Path, packages: &[String], ctx: &ToolContext<'_>) -> Result<String, String> {
875    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")?;
876    let root = python::managed_root(data_dir);
877    std::fs::create_dir_all(&root).map_err(|e| format!("can't create {}: {e}", root.display()))?;
878    let root = root.canonicalize().map_err(|e| format!("{}: {e}", root.display()))?;
879    let venv = root.join("venv");
880    let tmp = TempDir::new("byob-install-")?;
881    let mut read: Vec<PathBuf> = uv.canonicalize().ok().and_then(|p| p.parent().map(Path::to_path_buf)).into_iter().collect();
882    let base = python::system_python();
883    if let Some(b) = &base {
884        read.extend(Python { path: b.clone(), managed: false }.read_paths());
885    }
886    let env = vec![
887        ("UV_CACHE_DIR".to_owned(), root.join("cache").into_os_string()),
888        ("UV_PYTHON_INSTALL_DIR".to_owned(), root.join("interpreters").into_os_string()),
889        ("UV_NO_CONFIG".to_owned(), "1".into()),
890    ];
891    let job = |args: Vec<OsString>| {
892        let mut j = Job::new(uv.clone().into_os_string(), args, INSTALL_TIMEOUT);
893        j.network = true;
894        j.layer.read = read.clone();
895        j.layer.write = vec![root.clone()];
896        j.env = env.clone();
897        j
898    };
899    let mut log = String::new();
900    let python_bin = python::venv_python(&venv);
901    if !python_bin.exists() {
902        let mut args: Vec<OsString> = vec!["venv".into(), "--quiet".into()];
903        if let Some(b) = &base {
904            args.extend(["--python".into(), b.clone().into_os_string()]);
905        }
906        args.push(venv.clone().into_os_string());
907        let out = exec.run(job(args), &root, tmp.path(), ctx)?;
908        if !out.success() {
909            return Err(format!("creating the Python environment failed:\n{}", out.stderr.text().trim()));
910        }
911        log.push_str(&format!("Created a Python environment in {}.\n", venv.display()));
912    }
913    let mut args: Vec<OsString> = vec!["pip".into(), "install".into(), "--only-binary".into(), ":all:".into(), "--python".into(), python_bin.into_os_string()];
914    args.extend(packages.iter().map(OsString::from));
915    let out = exec.run(job(args), &root, tmp.path(), ctx)?;
916    let detail = [out.stdout.text(), out.stderr.text()].iter().map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect::<Vec<_>>().join("\n");
917    if out.cancelled {
918        return Err("Stopped by the user.".into());
919    }
920    if !out.success() {
921        return Err(format!("installing failed:\n{detail}"));
922    }
923    log.push_str(&format!("Installed {}. run_python now uses this environment.\n{detail}", packages.join(", ")));
924    Ok(log.trim_end().to_owned())
925}
926
927#[cfg(test)]
928mod tests {
929    use super::*;
930
931    fn exec() -> Arc<Exec> {
932        Arc::new(Exec { mode: Mode::Unsandboxed, data_dir: None, envs: Arc::new(Envs::none()) })
933    }
934
935    /// On Windows commands go to PowerShell, quotes and all, and a failing program's exit
936    /// code comes back (there is no `sh` there).
937    #[cfg(windows)]
938    #[test]
939    fn windows_commands_run_in_powershell() {
940        let mut reg = Registry::default();
941        register(&mut reg, Exec { mode: Mode::Unsandboxed, data_dir: None, envs: Arc::new(Envs::none()) });
942        let ws = tempfile::tempdir().unwrap();
943        let cancel = std::sync::atomic::AtomicBool::new(false);
944        let ctx = ToolContext::new(ws.path(), &cancel);
945        let tool = reg.get("run_command").unwrap();
946        assert!(tool.spec().description.contains("PowerShell"));
947        let out = tool.run(&json!({"command": r#"Set-Content -Path "a b.txt" -Value 'it''s "quoted" ✓'; Get-Content "a b.txt""#}), &ctx);
948        assert!(!out.failed && out.text.contains(r#"it's "quoted" ✓"#), "{}", out.text);
949        let out = tool.run(&json!({"command": "cmd /c exit 3"}), &ctx);
950        assert!(out.text.contains('3'), "{}", out.text);
951        assert!(out.failed || out.text.to_lowercase().contains("exit"), "{}", out.text);
952    }
953
954    /// The sandbox helper accepts a Windows workspace policy (it once carried `/usr`, which
955    /// isn't absolute on Windows, so nothing ran).
956    #[cfg(windows)]
957    #[test]
958    fn a_windows_workspace_policy_is_valid() {
959        let ws = tempfile::tempdir().unwrap();
960        let p = Policy::for_workspace(ws.path(), &std::env::temp_dir());
961        assert!(Policy::from_json(&p.to_json()).is_ok(), "{}", p.to_json());
962    }
963
964    #[test]
965    fn titles_show_network_and_stay_short() {
966        let t = RunCommand(exec());
967        assert_eq!(t.title(&json!({"command": "ls -la"})), "Run `ls -la`");
968        assert_eq!(t.title(&json!({"command": "curl x", "network": true})), "Run `curl x` — with internet access");
969        assert!(t.title(&json!({"command": "a\nb"})).ends_with("…`"));
970        assert!(t.title(&json!({"command": "x".repeat(500)})).chars().count() < 80);
971        assert_eq!(t.title(&json!(null)), "Run ``");
972        let p = RunPython(exec());
973        assert_eq!(p.title(&json!({"code": "print(1)"})), "Run Python code");
974        assert_eq!(p.title(&json!({"script": "a.py", "network": true})), "Run a.py — with internet access");
975        assert_eq!(InstallPythonPackages(exec()).title(&json!({"packages": ["pandas", "numpy"]})), "Install Python packages: pandas, numpy");
976    }
977
978    #[test]
979    fn access_levels() {
980        assert_eq!(RunCommand(exec()).access(&json!({})), Access::Execute);
981        assert_eq!(RunPython(exec()).access(&json!({})), Access::Execute);
982        assert_eq!(InstallPythonPackages(exec()).access(&json!({})), Access::Network);
983    }
984
985    #[test]
986    fn timeouts_are_clamped() {
987        assert_eq!(timeout_of(None), Duration::from_secs(DEFAULT_TIMEOUT_S));
988        assert_eq!(timeout_of(Some(1e9)), Duration::from_secs(MAX_TIMEOUT_S));
989        assert_eq!(timeout_of(Some(-3.0)), Duration::from_secs(DEFAULT_TIMEOUT_S));
990        assert_eq!(timeout_of(Some(f64::NAN)), Duration::from_secs(DEFAULT_TIMEOUT_S));
991        assert_eq!(timeout_of(Some(0.01)), Duration::from_secs(1));
992    }
993
994    #[test]
995    fn bad_arguments_are_refused_before_running() {
996        let d = tempfile::tempdir().unwrap();
997        let cancel = std::sync::atomic::AtomicBool::new(false);
998        let ctx = ToolContext::new(d.path(), &cancel);
999        let e = exec();
1000        for args in [json!({}), json!({"command": ""}), json!({"command": 1}), json!({"command": "ls", "extra": 1})] {
1001            assert!(RunCommand(Arc::clone(&e)).run(&args, &ctx).failed, "{args}");
1002        }
1003        for args in [json!({}), json!({"code": "1", "script": "a.py"}), json!({"script": "../x.py"}), json!({"script": "missing.py"})] {
1004            let out = RunPython(Arc::clone(&e)).run(&args, &ctx);
1005            assert!(out.failed, "{args}");
1006        }
1007        for args in [json!({"packages": []}), json!({"packages": ["--index-url=http://evil"]}), json!({"packages": ["a b"]})] {
1008            assert!(InstallPythonPackages(Arc::clone(&e)).run(&args, &ctx).failed, "{args}");
1009        }
1010    }
1011
1012    /// A fake `brew` that logs its arguments next to itself and fails for `bad-pkg`.
1013    #[cfg(unix)]
1014    fn fake_brew(dir: &Path) -> PathBuf {
1015        use std::os::unix::fs::PermissionsExt;
1016        let bin = dir.join("bin");
1017        std::fs::create_dir_all(&bin).unwrap();
1018        let brew = bin.join("brew");
1019        std::fs::write(
1020            &brew,
1021            "#!/bin/sh\necho \"$@\" >> \"$0.log\"\ncase \"$*\" in *bad-pkg*) echo 'Error: No formula' >&2; exit 1;; esac\necho \"==> Pouring $2\"\n",
1022        )
1023        .unwrap();
1024        std::fs::set_permissions(&brew, std::fs::Permissions::from_mode(0o755)).unwrap();
1025        brew
1026    }
1027
1028    #[cfg(unix)]
1029    #[test]
1030    fn system_installs_are_a_confirmed_last_resort() {
1031        use env::system::{Kind, SystemInstaller};
1032        let d = tempfile::tempdir().unwrap();
1033        let brew = fake_brew(d.path());
1034        let found = env::Found { system: Some(SystemInstaller { kind: Kind::Brew, program: brew.clone() }), ..Default::default() };
1035        let envs = Arc::new(Envs::new(Some(d.path()), found, env::ProjectMode::Ask));
1036        let mut reg = Registry::default();
1037        register(&mut reg, Exec { mode: Mode::Unsandboxed, data_dir: Some(d.path().to_path_buf()), envs });
1038        let tool = reg.get("install_system_packages").expect("offered where brew exists");
1039        let args = json!({"packages": ["jq"]});
1040        let warning = tool.always_ask(&args).expect("every call needs a person");
1041        assert!(warning.contains("SYSTEM-WIDE") && warning.contains("brew uninstall jq"), "{warning}");
1042        assert_eq!(tool.title(&args), "Install system-wide with Homebrew: jq");
1043        assert!(tool.spec().description.contains("Last resort"));
1044
1045        let ws = tempfile::tempdir().unwrap();
1046        let cancel = std::sync::atomic::AtomicBool::new(false);
1047        let ctx = ToolContext::new(ws.path(), &cancel);
1048        // No workspace installer here (no Nix, no pixi): it may install anything.
1049        let out = tool.run(&args, &ctx);
1050        assert!(!out.failed && out.text.contains("Installed system-wide with Homebrew: jq"), "{}", out.text);
1051        assert_eq!(std::fs::read_to_string(brew.with_extension("log")).unwrap(), "install jq\n");
1052        let out = tool.run(&json!({"packages": ["--force"]}), &ctx);
1053        assert!(out.failed && out.text.contains("not a package name"), "{}", out.text);
1054        let out = tool.run(&json!({"packages": ["bad-pkg"]}), &ctx);
1055        assert!(out.failed && out.text.contains("No formula"), "{}", out.text);
1056        assert_eq!(std::fs::read_to_string(brew.with_extension("log")).unwrap().lines().count(), 2, "the bad name never reached brew");
1057        // A failed run names the last resort next to pixi.
1058        let h = hints::hint("", "sh: 1: jq: not found", None, hints::Fix::None, Some("Homebrew")).unwrap();
1059        assert!(h.contains("install_system_packages"), "{h}");
1060    }
1061
1062    /// With a workspace installer (a fake pixi that finds nothing), the system installer
1063    /// only takes what install_packages reported missing.
1064    #[cfg(unix)]
1065    #[test]
1066    fn system_installs_wait_for_the_workspace_installer() {
1067        use env::system::{Kind, SystemInstaller};
1068        use std::os::unix::fs::PermissionsExt;
1069        let d = tempfile::tempdir().unwrap();
1070        let brew = fake_brew(d.path());
1071        let pixi = d.path().join("bin/pixi");
1072        std::fs::write(&pixi, "#!/bin/sh\nfor a; do last=$a; done\nprintf 'Error: Cannot solve the request because of: No candidates were found for\\n    %s *.\\n' \"$last\" >&2\nexit 1\n").unwrap();
1073        std::fs::set_permissions(&pixi, std::fs::Permissions::from_mode(0o755)).unwrap();
1074        let found = env::Found { pixi: Some(pixi), system: Some(SystemInstaller { kind: Kind::Brew, program: brew.clone() }), ..Default::default() };
1075        let envs = Arc::new(Envs::new(Some(d.path()), found, env::ProjectMode::Ask));
1076        assert_eq!(envs.installer(), Some("pixi"));
1077        let mut reg = Registry::default();
1078        register(&mut reg, Exec { mode: Mode::Unsandboxed, data_dir: Some(d.path().to_path_buf()), envs });
1079        assert!(reg.get("install_python_packages").is_none());
1080        let ws = tempfile::tempdir().unwrap();
1081        let cancel = std::sync::atomic::AtomicBool::new(false);
1082        let ctx = ToolContext::new(ws.path(), &cancel);
1083        let system = reg.get("install_system_packages").unwrap();
1084        assert!(system.spec().description.contains("try install_packages first"));
1085        let out = system.run(&json!({"packages": ["sometool"]}), &ctx);
1086        assert!(out.failed && out.text.contains("Call install_packages with {\"packages\":[\"sometool\"]} first"), "{}", out.text);
1087        assert!(!brew.with_extension("log").exists());
1088        let out = reg.get("install_packages").unwrap().run(&json!({"packages": ["sometool"]}), &ctx);
1089        assert!(out.failed && out.text.contains("Not found on conda-forge: \"sometool\""), "{}", out.text);
1090        assert!(out.text.contains("install_system_packages can install [\"sometool\"] system-wide with Homebrew"), "{}", out.text);
1091        let out = system.run(&json!({"packages": ["sometool"]}), &ctx);
1092        assert!(!out.failed, "{}", out.text);
1093        assert_eq!(std::fs::read_to_string(brew.with_extension("log")).unwrap(), "install sometool\n");
1094        assert!(std::fs::read_dir(ws.path()).unwrap().next().is_none(), "the workspace is untouched");
1095    }
1096
1097    /// Answers every question with `.0`.
1098    struct Says(byob_tools::Answer);
1099    impl byob_tools::Asker for Says {
1100        fn ask(&self, _q: &byob_tools::Question) -> byob_tools::Answer {
1101            self.0
1102        }
1103    }
1104
1105    /// A workspace with containers through a fake `docker` whose daemon is down.
1106    #[cfg(unix)]
1107    fn fake_docker_world(d: &Path, runtime: bool) -> (Registry, Arc<Envs>, PathBuf) {
1108        use std::os::unix::fs::PermissionsExt;
1109        let docker = d.join("bin/docker");
1110        std::fs::create_dir_all(d.join("bin")).unwrap();
1111        std::fs::write(&docker, "#!/bin/sh\necho \"$@\" >> \"$0.log\"\necho 'Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?' >&2\nexit 1\n").unwrap();
1112        std::fs::set_permissions(&docker, std::fs::Permissions::from_mode(0o755)).unwrap();
1113        let rt = env::container::Runtime { kind: env::container::RuntimeKind::Docker, program: docker.clone() };
1114        let found = env::Found { containers: runtime.then_some(rt), ..Default::default() };
1115        let envs = Arc::new(Envs::new(Some(d), found, env::ProjectMode::Ask));
1116        let mut reg = Registry::default();
1117        register(&mut reg, Exec { mode: Mode::Unsandboxed, data_dir: Some(d.to_path_buf()), envs: Arc::clone(&envs) });
1118        (reg, envs, docker.with_extension("log"))
1119    }
1120
1121    #[cfg(unix)]
1122    #[test]
1123    fn container_problems_are_clear_and_nothing_runs() {
1124        use byob_tools::EnvControl;
1125        let d = tempfile::tempdir().unwrap();
1126        let ws = tempfile::tempdir().unwrap();
1127        let ws = ws.path().canonicalize().unwrap();
1128        let cancel = std::sync::atomic::AtomicBool::new(false);
1129        let (reg, envs, log) = fake_docker_world(d.path(), true);
1130        assert!(reg.get("install_packages").is_some(), "containers install there");
1131        let run = |reg: &Registry, answer| {
1132            let says = Says(answer);
1133            let ctx = ToolContext::new(&ws, &cancel).with_asker(&says);
1134            reg.get("run_command").unwrap().run(&json!({"command": "touch ran.txt"}), &ctx)
1135        };
1136        // A devcontainer.json the user declines: runs here, no docker call, told once.
1137        std::fs::write(ws.join(".devcontainer.json"), r#"{"image": "alpine"}"#).unwrap();
1138        let out = run(&reg, byob_tools::Answer::No);
1139        assert!(!out.failed && out.text.contains("chose to run commands on their machine"), "{}", out.text);
1140        assert!(!log.exists(), "docker wasn't called");
1141        assert!(!run(&reg, byob_tools::Answer::Yes).text.contains("chose to run"), "told once, and the answer stuck");
1142        assert_eq!(envs.describe(&ws, &byob_tools::EnvPlan::default()).container.use_container, Some(false));
1143        std::fs::remove_file(ws.join("ran.txt")).unwrap();
1144        // Turned on, but the daemon is down: a clear error, nothing ran.
1145        envs.apply(&ws, &byob_protocol::EnvAction::Container { on: Some(true) }).unwrap();
1146        let out = run(&reg, byob_tools::Answer::Yes);
1147        assert!(out.failed && out.text.contains("Docker isn't running") && out.text.contains("Cannot connect"), "{}", out.text);
1148        assert!(!ws.join("ran.txt").exists());
1149        let d = envs.describe(&ws, &byob_tools::EnvPlan::default()).container;
1150        assert_eq!((d.runtime.as_deref(), d.use_container, d.state, d.image.as_str()), (Some("docker"), Some(true), None, "alpine"));
1151        // Turned on where there's no runtime at all.
1152        let d2 = tempfile::tempdir().unwrap();
1153        let (reg2, envs2, _) = fake_docker_world(d2.path(), false);
1154        envs2.apply(&ws, &byob_protocol::EnvAction::Container { on: Some(true) }).unwrap();
1155        let out = run(&reg2, byob_tools::Answer::Yes);
1156        assert!(out.failed && out.text.contains("neither Docker nor Podman is installed"), "{}", out.text);
1157        assert!(envs2.apply(&ws, &byob_protocol::EnvAction::StopContainer).is_err());
1158    }
1159
1160    /// The workspace's (or chat's) environment setting decides where commands run, with no
1161    /// question, and names the image; the folder's own answers apply only without one.
1162    #[cfg(unix)]
1163    #[test]
1164    fn environment_settings_decide_without_asking() {
1165        use byob_tools::{EnvControl, EnvPlan};
1166        let d = tempfile::tempdir().unwrap();
1167        let ws = tempfile::tempdir().unwrap();
1168        let ws = ws.path().canonicalize().unwrap();
1169        std::fs::write(ws.join(".devcontainer.json"), r#"{"image": "alpine"}"#).unwrap();
1170        let cancel = std::sync::atomic::AtomicBool::new(false);
1171        let (reg, envs, log) = fake_docker_world(d.path(), true);
1172        /// Fails the test if anything is asked.
1173        struct NoQuestions;
1174        impl byob_tools::Asker for NoQuestions {
1175            fn ask(&self, q: &byob_tools::Question) -> byob_tools::Answer {
1176                panic!("asked {q:?}")
1177            }
1178        }
1179        let run = |plan: &EnvPlan| {
1180            let ctx = ToolContext::new(&ws, &cancel).with_asker(&NoQuestions).with_env(plan).with_chat("c1");
1181            reg.get("run_command").unwrap().run(&json!({"command": "echo hi"}), &ctx)
1182        };
1183        // Container: straight to docker (whose daemon is down here), with the chosen image.
1184        let container = EnvPlan { container: Some(true), image: Some("debian:stable-slim".into()), ..EnvPlan::default() };
1185        let out = run(&container);
1186        assert!(out.failed && out.text.contains("Docker isn't running"), "{}", out.text);
1187        assert!(std::fs::read_to_string(&log).unwrap().contains("info"), "docker was asked");
1188        let shown = envs.describe(&ws, &container).container;
1189        assert_eq!((shown.use_container, shown.image.as_str()), (Some(true), "debian:stable-slim"));
1190        // A chat that runs on this machine: no docker, no devcontainer question.
1191        std::fs::remove_file(&log).unwrap();
1192        let host = EnvPlan { container: Some(false), ..EnvPlan::default() };
1193        let out = run(&host);
1194        assert!(!out.failed && out.text.contains("hi") && out.text.contains("chose to run commands on their machine"), "{}", out.text);
1195        assert!(!log.exists(), "docker wasn't called");
1196        // The folder's own answer is untouched by settings.
1197        assert_eq!(envs.describe(&ws, &EnvPlan::default()).container.use_container, None);
1198        // Forgetting the workspace clears what byob kept for it.
1199        envs.apply(&ws, &byob_protocol::EnvAction::Container { on: Some(false) }).unwrap();
1200        assert!(envs.forget(&ws).unwrap().contains("forgot its answers"));
1201        assert_eq!(envs.describe(&ws, &EnvPlan::default()).container.use_container, None);
1202        assert_eq!(EnvControl::support(&*envs).runtime.as_deref(), Some("docker"));
1203        assert!(envs.check_containers().unwrap_err().contains("Docker isn't running"));
1204    }
1205
1206    #[test]
1207    fn specs_are_valid() {
1208        let mut reg = Registry::default();
1209        register(&mut reg, Exec { mode: Mode::Unsandboxed, data_dir: None, envs: Arc::new(Envs::none()) });
1210        assert!(reg.get("run_command").is_some() && reg.get("run_python").is_some());
1211        assert!(reg.get("install_python_packages").is_none(), "no data dir, no installer");
1212        for s in reg.specs() {
1213            assert_eq!(s.parameters["type"], "object");
1214        }
1215    }
1216    /// A plugin's command provider (`environments` in its manifest): detected by its file,
1217    /// asked once like byob's own, its printed variables reach the command.
1218    #[cfg(unix)]
1219    #[test]
1220    fn a_plugins_command_provider_loads_the_workspace_environment() {
1221        let d = tempfile::tempdir().unwrap();
1222        let plugin = tempfile::tempdir().unwrap();
1223        std::fs::write(plugin.path().join("env.sh"), "#!/bin/sh\nprintf '{\"DEMO_GREETING\": \"hello from %s\"}' \"$(cat demo.env)\"\n").unwrap();
1224        let envs = Arc::new(Envs::new(Some(d.path()), env::Found::default(), env::ProjectMode::Ask));
1225        let mut reg = Registry::default();
1226        register(&mut reg, Exec { mode: Mode::Unsandboxed, data_dir: Some(d.path().to_path_buf()), envs });
1227        let ws = tempfile::tempdir().unwrap();
1228        let ws = ws.path().canonicalize().unwrap();
1229        let plan = byob_tools::EnvPlan {
1230            providers: Some(byob_tools::EnvProviders {
1231                off: vec![],
1232                external: vec![byob_tools::CommandEnv {
1233                    id: "demo-env".into(),
1234                    label: "demo environment".into(),
1235                    detect: vec!["demo.env".into()],
1236                    inputs: vec![],
1237                    program: "sh".into(),
1238                    args: vec!["env.sh".into()],
1239                    dir: plugin.path().to_path_buf(),
1240                }],
1241            }),
1242            ..Default::default()
1243        };
1244        let cancel = std::sync::atomic::AtomicBool::new(false);
1245        let says = Says(byob_tools::Answer::Yes);
1246        let ctx = ToolContext::new(&ws, &cancel).with_asker(&says).with_env(&plan);
1247        let run = |ctx: &ToolContext<'_>| reg.get("run_command").unwrap().run(&json!({"command": "echo \"[$DEMO_GREETING]\""}), ctx);
1248        let out = run(&ctx);
1249        assert!(out.text.contains("[]"), "no demo.env, nothing loaded: {}", out.text);
1250        std::fs::write(ws.join("demo.env"), "the workspace").unwrap();
1251        let out = run(&ctx);
1252        assert!(out.text.contains("[hello from the workspace]"), "{}", out.text);
1253        assert!(out.text.contains("Loaded the workspace's demo environment from demo.env"), "{}", out.text);
1254        // Without the provider in the chat's plan it isn't there.
1255        let off = byob_tools::EnvPlan { providers: Some(byob_tools::EnvProviders::default()), ..Default::default() };
1256        let out = run(&ToolContext::new(&ws, &cancel).with_asker(&says).with_env(&off));
1257        assert!(out.text.contains("[]"), "{}", out.text);
1258    }
1259}