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