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