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