Skip to main content

byob_exec/env/
mod.rs

1//! Workspace environments: where the programs and libraries a run needs come from.
2//!
3//! Models fail most often not on the task but on a missing tool (`jq: not found`,
4//! `No module named 'matplotlib'`, a `pip install` that can't work on NixOS). So every
5//! `run_command` / `run_python` call is prepared by [`Envs`]. If the user opted the
6//! workspace into a [`container`] (Docker/Podman; asked once when it has a
7//! devcontainer.json), the call runs there. Otherwise [`Envs`] stacks **layers** onto the
8//! clean sandbox environment, first match winning:
9//!
10//! 1. **Installed**: packages the model asked for with `install_packages`, kept per
11//!    workspace under `<data>/envs/` (Nix: one `buildEnv`, a GC root, nixpkgs pinned;
12//!    without Nix: a [`pixi`] manifest of conda-forge packages).
13//! 2. **Project venv**: a `.venv` / `venv` in the workspace (any OS).
14//! 3. **Project environments** (`Project`): what the workspace declares itself, loaded
15//!    once the user agreed ([`choices`], asked once per workspace), then cached until its
16//!    files change — a `flake.nix` / `shell.nix` dev shell (`nix print-dev-env`, shellHook
17//!    included), a pixi project (`pixi shell-hook --json`), mise tools (`mise env --json`).
18//! 4. **Support**: what a package manager's own CLI needs inside the sandbox, so the model
19//!    can also run `nix shell nixpkgs#foo --command …` itself (store, daemon socket,
20//!    config, a persistent eval cache), and Homebrew's `bin`.
21//!
22//! The last resort, [`system`] (Homebrew / winget, system-wide), always needs a person's
23//! approval. Failed output gets a [`hints`] line that names the one tool to call, because
24//! small models follow an explicit next step far better than prose. Design and plans:
25//! `docs/environments.md`.
26
27pub mod choices;
28pub mod container;
29pub mod devcontainer;
30pub mod hints;
31pub mod nix;
32pub mod pixi;
33pub mod project;
34pub mod system;
35
36use std::collections::{BTreeMap, BTreeSet};
37use std::ffi::OsString;
38use std::path::{Path, PathBuf};
39use std::sync::{Mutex, PoisonError};
40
41use byob_protocol::{ContainerEnv, EnvAction, EnvSupport, WorkspaceEnv};
42use byob_sandbox::Outcome;
43use byob_tools::{Access, Answer, EnvControl, EnvPlan, Question};
44use serde::{Deserialize, Serialize};
45
46use crate::Job;
47
48/// Changes a run gets: `PATH` entries in front of the host's, variables, and sandbox access.
49#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
50pub struct Layer {
51    /// Put in front of `PATH`, in this order.
52    #[serde(default)]
53    pub path: Vec<PathBuf>,
54    /// Variables to set (never `PATH`; see [`Layer::path`]).
55    #[serde(default)]
56    pub vars: Vec<(String, String)>,
57    #[serde(default)]
58    pub read: Vec<PathBuf>,
59    #[serde(default)]
60    pub write: Vec<PathBuf>,
61    /// Unix sockets the run may connect to without network (the Nix daemon's).
62    #[serde(default)]
63    pub sockets: Vec<PathBuf>,
64}
65
66impl Layer {
67    pub fn is_empty(&self) -> bool {
68        self == &Self::default()
69    }
70
71    /// Add `other` underneath: its `PATH` entries go after ours and it can't override our
72    /// variables.
73    pub fn stack(&mut self, other: &Layer) {
74        for p in &other.path {
75            if !self.path.contains(p) {
76                self.path.push(p.clone());
77            }
78        }
79        for (k, v) in &other.vars {
80            if !self.vars.iter().any(|(have, _)| have == k) {
81                self.vars.push((k.clone(), v.clone()));
82            }
83        }
84        self.read.extend(other.read.iter().cloned());
85        self.write.extend(other.write.iter().cloned());
86        self.sockets.extend(other.sockets.iter().cloned());
87    }
88
89    pub fn var(&self, name: &str) -> Option<&str> {
90        self.vars.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
91    }
92}
93
94/// Variables a layer must never set: the sandbox's own home, temp and cache folders, and
95/// what only makes sense inside a Nix build (mirrors `nix develop`'s ignore list).
96pub const KEEP_VARS: &[&str] = &[
97    "PATH",
98    "HOME",
99    "USER",
100    "LOGNAME",
101    "USERPROFILE",
102    "TMPDIR",
103    "TMP",
104    "TEMP",
105    "TEMPDIR",
106    "XDG_CACHE_HOME",
107    "XDG_CONFIG_HOME",
108    "MPLCONFIGDIR",
109    "TERM",
110    "TZ",
111    "PWD",
112    "OLDPWD",
113    "SHLVL",
114    "_",
115    "UID",
116    "PPID",
117    "BASHOPTS",
118    "SHELLOPTS",
119    "NIX_BUILD_TOP",
120    "NIX_LOG_FD",
121    "NIX_ENFORCE_PURITY",
122    "NIX_REMOTE",
123    "NIX_ATTRS_JSON_FILE",
124    "NIX_ATTRS_SH_FILE",
125    "SSL_CERT_FILE",
126    "NIX_SSL_CERT_FILE",
127    "SOURCE_DATE_EPOCH",
128    "DISPLAY",
129    "WAYLAND_DISPLAY",
130    "out",
131    "shellHook",
132];
133
134pub fn keep_var(name: &str) -> bool {
135    KEEP_VARS.contains(&name)
136}
137
138/// Runs a sandboxed job for a provider (the tool's own sandbox, with the support layer).
139pub(crate) trait Runner {
140    /// Run `job` in `cwd` with `tmp` as its private temp folder.
141    fn run(&self, job: Job, cwd: &Path, tmp: &Path) -> Result<Outcome, String>;
142    /// Ask the user (see [`byob_tools::ToolContext::ask`]).
143    fn ask(&self, _q: &Question) -> Answer {
144        Answer::AutoNo
145    }
146    /// The user pressed Stop.
147    fn cancelled(&self) -> bool {
148        false
149    }
150    /// What the chat's settings decide about where it runs (see [`EnvPlan`]).
151    fn plan(&self) -> EnvPlan {
152        EnvPlan::default()
153    }
154    /// The chat the call runs in, if known (the model is told things once per chat).
155    fn chat(&self) -> Option<String> {
156        None
157    }
158}
159
160/// What [`Envs::prepare`] found for one run.
161#[derive(Debug, Default)]
162pub(crate) struct Prepared {
163    pub layer: Layer,
164    /// One-time messages for the model (a dev shell just loaded, or failed to).
165    pub notes: Vec<String>,
166}
167
168/// The result of installing packages.
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct Installed {
171    pub text: String,
172    /// Some packages weren't found or the build failed.
173    pub failed: bool,
174    /// The names it couldn't find (what `install_system_packages` may then try).
175    pub missing: Vec<String>,
176}
177
178/// Override the per-workspace question: `BYOB_WORKSPACE_ENV=off` never loads a workspace's
179/// own environment (installed packages and the Nix CLI still work), `on` loads it without
180/// asking. Unset (or `ask`): ask once per workspace and remember the answer.
181pub const WORKSPACE_ENV: &str = "BYOB_WORKSPACE_ENV";
182
183/// Whether project environments load (see [`WORKSPACE_ENV`]).
184#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
185pub enum ProjectMode {
186    /// Ask once per workspace.
187    #[default]
188    Ask,
189    Always,
190    Never,
191}
192
193impl ProjectMode {
194    pub fn from_env() -> Self {
195        match std::env::var(WORKSPACE_ENV).map(|v| v.trim().to_ascii_lowercase()).as_deref() {
196            Ok("off" | "0" | "false" | "no") => Self::Never,
197            Ok("on" | "1" | "true" | "yes") => Self::Always,
198            _ => Self::Ask,
199        }
200    }
201}
202
203/// An environment a workspace declares in a project file (`flake.nix`, `pixi.toml`,
204/// `mise.toml`, …): loaded once (slow, may download), then cached until its files change.
205pub(crate) trait Project: Send + Sync + std::fmt::Debug {
206    /// Names the cache file.
207    fn id(&self) -> &'static str;
208    /// For messages: "Nix dev shell".
209    fn label(&self) -> &'static str;
210    /// The file in `ws` that declares it, if any.
211    fn file(&self, ws: &Path) -> Option<&'static str>;
212    /// Files whose contents key the cache (lock files included).
213    fn inputs(&self) -> &'static [&'static str];
214    /// Load it now: a sandboxed run with network that may write the workspace and `dir`.
215    fn load(&self, ws: &Path, dir: &Path, run: &dyn Runner) -> Result<Layer, String>;
216}
217
218/// The result of [`load_project`].
219#[derive(Debug)]
220pub(crate) struct ProjectEnv {
221    pub file: &'static str,
222    pub result: Result<Layer, String>,
223    /// Loaded just now (else from the cache).
224    pub fresh: bool,
225}
226
227#[derive(Debug, Serialize, Deserialize)]
228struct ProjectCache {
229    stamp: String,
230    #[serde(default)]
231    layer: Option<Layer>,
232    #[serde(default)]
233    error: Option<String>,
234}
235
236/// Cache key: the project's input files' contents.
237fn stamp(ws: &Path, p: &dyn Project) -> String {
238    let mut bytes = format!("{}\0", p.id()).into_bytes();
239    for f in p.inputs() {
240        bytes.extend_from_slice(f.as_bytes());
241        bytes.push(0);
242        bytes.extend(std::fs::read(ws.join(f)).unwrap_or_default());
243        bytes.push(0);
244    }
245    format!("{:016x}", fnv64(&bytes))
246}
247
248/// `p`'s environment for `ws`, from `<dir>/<id>.json` while its files are unchanged (and the
249/// folders it put on `PATH` still exist), else loaded now. Failures are cached too, so a
250/// broken project file is reported once rather than retried before every command.
251pub(crate) fn load_project(p: &dyn Project, ws: &Path, dir: &Path, run: &dyn Runner) -> Option<ProjectEnv> {
252    let file = p.file(ws)?;
253    let cache_file = dir.join(format!("{}.json", p.id()));
254    let now = stamp(ws, p);
255    if let Some(c) = std::fs::read_to_string(&cache_file).ok().and_then(|s| serde_json::from_str::<ProjectCache>(&s).ok())
256        && c.stamp == now
257    {
258        match (c.layer, c.error) {
259            (Some(l), _) if l.path.iter().all(|p| p.exists()) => return Some(ProjectEnv { file, result: Ok(l), fresh: false }),
260            (_, Some(e)) => return Some(ProjectEnv { file, result: Err(e), fresh: false }),
261            _ => {}
262        }
263    }
264    let result = std::fs::create_dir_all(dir)
265        .map_err(|e| format!("can't create {}: {e}", dir.display()))
266        .and_then(|()| dir.canonicalize().map_err(|e| e.to_string()))
267        .and_then(|dir| p.load(ws, &dir, run));
268    // Stamp after loading: the tool may just have written its lock file.
269    let cache = match &result {
270        Ok(l) => ProjectCache { stamp: stamp(ws, p), layer: Some(l.clone()), error: None },
271        Err(e) => ProjectCache { stamp: stamp(ws, p), layer: None, error: Some(e.clone()) },
272    };
273    if result.as_ref().err().is_none_or(|e| e != STOPPED)
274        && let Err(e) = write_atomic(&cache_file, serde_json::to_string(&cache).unwrap_or_default().as_bytes())
275    {
276        log::warn!("environments: {e}");
277    }
278    Some(ProjectEnv { file, result, fresh: true })
279}
280
281pub(crate) const STOPPED: &str = "Stopped by the user.";
282
283/// The package managers and tools found on this machine. [`Found::detect`] looks on
284/// `PATH`; tests build one by hand to hide what they don't want used (e.g. Nix, to test
285/// the pixi installer on a machine that has both).
286#[derive(Debug, Clone, Default)]
287pub struct Found {
288    pub nix: Option<nix::Nix>,
289    /// The `pixi` program.
290    pub pixi: Option<PathBuf>,
291    /// The `mise` program.
292    pub mise: Option<PathBuf>,
293    /// Homebrew or winget, for `install_system_packages` (the last resort).
294    pub system: Option<system::SystemInstaller>,
295    /// Docker or Podman, for workspaces whose commands run in a container.
296    pub containers: Option<container::Runtime>,
297    /// The image for containers without a devcontainer.json (default [`container::DEFAULT_IMAGE`]).
298    pub container_image: Option<String>,
299}
300
301impl Found {
302    /// Look for everything. `data_dir` holds caches and installed packages.
303    pub fn detect(data_dir: Option<&Path>) -> Self {
304        Self::detect_with(data_dir, None, None)
305    }
306
307    /// Like [`Found::detect`], with the settings for containers: the default image and
308    /// `docker` / `podman` (else Podman if installed, else Docker).
309    pub fn detect_with(data_dir: Option<&Path>, container_image: Option<String>, container_runtime: Option<&str>) -> Self {
310        let nix = nix::Nix::detect(data_dir);
311        if let Some(n) = &nix {
312            log::info!("environments: Nix {} ({})", n.binary().display(), if n.daemon() { "daemon" } else { "single-user" });
313        }
314        let pixi = byob_sandbox::which("pixi".as_ref());
315        let mise = byob_sandbox::which("mise".as_ref());
316        for (name, p) in [("pixi", &pixi), ("mise", &mise)] {
317            if let Some(p) = p {
318                log::info!("environments: {name} ({})", p.display());
319            }
320        }
321        let system = system::SystemInstaller::detect();
322        if let Some(s) = &system {
323            log::info!("environments: {} ({}), only as an approved last resort", s.name(), s.program.display());
324        }
325        let containers = container::Runtime::detect(container_runtime);
326        if let Some(c) = &containers {
327            log::info!("environments: containers with {} ({}), opt-in per workspace", c.name(), c.program.display());
328        }
329        Self { nix, pixi, mise, system, containers, container_image }
330    }
331}
332
333/// The package managers found on this machine, the per-workspace state they keep, and
334/// what the user decided per workspace.
335#[derive(Debug, Default)]
336pub struct Envs {
337    nix: Option<nix::Nix>,
338    /// The installer where there's no Nix.
339    pixi: Option<pixi::Pixi>,
340    /// Project environments, in order of precedence.
341    projects: Vec<Box<dyn Project>>,
342    /// `<data>/envs`, holding one folder per workspace.
343    state: Option<PathBuf>,
344    mode: ProjectMode,
345    choices: choices::Choices,
346    /// Workspaces whose declined environment the model was told about.
347    told: Mutex<BTreeSet<PathBuf>>,
348    system: Option<system::SystemInstaller>,
349    containers: Option<container::Containers>,
350    /// Workspaces (and chats in them) whose container the model was told about (or whose
351    /// declined devcontainer it was told about).
352    told_container: Mutex<BTreeSet<(PathBuf, Option<String>)>>,
353    /// Per workspace: names `install_packages` couldn't find (the only ones
354    /// `install_system_packages` may install while there is a workspace installer).
355    missing: Mutex<BTreeMap<PathBuf, BTreeSet<String>>>,
356    /// One question at a time, so two runs don't ask the same thing.
357    asking: Mutex<()>,
358    /// One activation or install at a time (they share caches and GC roots).
359    busy: Mutex<()>,
360}
361
362impl Envs {
363    /// Detect what this machine has. `data_dir` holds caches, installed packages and the
364    /// per-workspace answers; without it only the package managers' CLIs are made to work
365    /// inside the sandbox.
366    pub fn detect(data_dir: Option<&Path>) -> Self {
367        Self::new(data_dir, Found::detect(data_dir), ProjectMode::from_env())
368    }
369
370    /// Use exactly what `found` lists.
371    pub fn new(data_dir: Option<&Path>, found: Found, mode: ProjectMode) -> Self {
372        let mut projects: Vec<Box<dyn Project>> = Vec::new();
373        if let Some(n) = &found.nix {
374            projects.push(Box::new(nix::NixShell(n.clone())));
375        }
376        // Loading these goes through `sh`, which Windows lacks (like run_command itself).
377        if !cfg!(windows) {
378            for (kind, program) in [(project::Kind::Pixi, &found.pixi), (project::Kind::Mise, &found.mise)] {
379                if let Some(program) = program {
380                    projects.push(Box::new(project::JsonEnvTool::new(kind, program.clone(), data_dir)));
381                }
382            }
383        }
384        let state = data_dir.map(|d| d.join("envs"));
385        let choices = choices::Choices::new(state.as_ref().map(|s| s.join("workspaces.json")));
386        // Nix first wherever it's present (conda-forge binaries need nix-ld on NixOS).
387        let pixi = match (&found.nix, &found.pixi, data_dir) {
388            (None, Some(program), Some(data)) => Some(pixi::Pixi::new(program.clone(), data)),
389            _ => None,
390        };
391        // Containers keep their temp folders in the data folder.
392        let containers = found.containers.filter(|_| data_dir.is_some()).map(|rt| container::Containers::new(rt, found.container_image));
393        Self { nix: found.nix, pixi, projects, state, mode, choices, system: found.system, containers, ..Self::default() }
394    }
395
396    /// No package managers (tests, or a machine without any).
397    pub fn none() -> Self {
398        Self::default()
399    }
400
401    /// The package manager `install_packages` uses here, if any.
402    pub fn installer(&self) -> Option<&'static str> {
403        self.state.as_ref()?;
404        if self.nix.is_some() { Some("Nix") } else { self.pixi.as_ref().map(|_| "pixi") }
405    }
406
407    /// Docker or Podman, if workspaces can run their commands in a container.
408    pub fn containers(&self) -> Option<&container::Containers> {
409        self.containers.as_ref()
410    }
411
412    /// A short paragraph for the system prompt.
413    pub fn prompt(&self) -> Option<String> {
414        let name = self.installer().or_else(|| self.containers.as_ref().map(|_| "the container's package manager"))?;
415        Some(format!(
416            "Software: run_command and run_python only have what is installed. When a program or a Python library is missing \
417             (\"command not found\", ModuleNotFoundError), call install_packages — it uses {name} and keeps the packages for this \
418             workspace — then run the command again. Don't use pip install, apt, brew or sudo: they don't work here."
419        ))
420    }
421
422    /// Per-workspace state folder: `<data>/envs/<name>-<hash of the path>`.
423    fn ws_dir(&self, ws: &Path) -> Option<PathBuf> {
424        let base = self.state.as_ref()?;
425        let name: String = ws
426            .file_name()
427            .map(|n| n.to_string_lossy().chars().filter(|c| c.is_ascii_alphanumeric() || "-_".contains(*c)).take(32).collect())
428            .unwrap_or_default();
429        let hash = fnv64(ws.as_os_str().as_encoded_bytes());
430        Some(base.join(format!("{}-{hash:016x}", if name.is_empty() { "ws" } else { &name })))
431    }
432
433    /// The support layer every sandboxed run gets.
434    pub(crate) fn support(&self) -> Layer {
435        let mut l = self.nix.as_ref().map(nix::Nix::support).unwrap_or_default();
436        if let Some(s) = &self.system {
437            l.stack(&s.layer());
438        }
439        l
440    }
441
442    /// Homebrew or winget, if `install_system_packages` is offered.
443    pub fn system(&self) -> Option<&system::SystemInstaller> {
444        self.system.as_ref()
445    }
446
447    /// May `install_system_packages` install `packages` for `ws`? Only what the workspace
448    /// installer couldn't find, or anything where there is none.
449    pub(crate) fn system_allowed(&self, ws: &Path, packages: &[String], plan: &EnvPlan) -> Result<(), String> {
450        if self.containers.is_some() && plan.container.or(self.choices.get(ws).container) == Some(true) {
451            return Err("This workspace's commands run in its container: call install_packages, which installs there.".into());
452        }
453        let Some(installer) = self.installer() else { return Ok(()) };
454        let missing = self.missing.lock().unwrap_or_else(PoisonError::into_inner);
455        let known = missing.get(ws);
456        let untried: Vec<&str> = packages.iter().filter(|p| !known.is_some_and(|k| k.contains(p.as_str()))).map(String::as_str).collect();
457        if untried.is_empty() {
458            return Ok(());
459        }
460        Err(format!(
461            "Call install_packages with {} first: it installs into this workspace with {installer}. install_system_packages is only \
462             for packages install_packages couldn't find.",
463            serde_json::json!({"packages": untried})
464        ))
465    }
466
467    /// Layers for one run in workspace `ws` (canonical path).
468    pub(crate) fn prepare(&self, ws: &Path, run: &dyn Runner) -> Prepared {
469        let mut out = Prepared::default();
470        let load = self.project_consent(ws, run, &mut out.notes);
471        let _busy = self.busy.lock().unwrap_or_else(PoisonError::into_inner);
472        let dir = self.ws_dir(ws);
473        if let Some(dir) = &dir {
474            let installed = match (&self.nix, &self.pixi) {
475                (Some(nix), _) => nix.installed(dir),
476                (None, Some(pixi)) => pixi.installed(dir),
477                (None, None) => None,
478            };
479            if let Some(l) = installed {
480                out.layer.stack(&l);
481            }
482        }
483        if let Some(l) = venv_layer(ws) {
484            out.layer.stack(&l);
485        }
486        let Some(dir) = dir.filter(|_| load) else { return out };
487        for p in &self.projects {
488            let Some(env) = load_project(p.as_ref(), ws, &dir, run) else { continue };
489            match env.result {
490                Ok(l) => {
491                    out.layer.stack(&l);
492                    if env.fresh {
493                        out.notes.push(format!("Loaded the workspace's {} from {} (its programs are on PATH; cached until it changes).", p.label(), env.file));
494                    }
495                }
496                Err(e) if env.fresh => out.notes.push(format!("The workspace's {} ({}) failed to load, so this ran without it:\n{e}", p.label(), env.file)),
497                Err(_) => {}
498            }
499        }
500        out
501    }
502
503    /// Whether `ws`'s commands run in its container, and if so the container (created or
504    /// started as needed). `None`: on this machine. Asks once per workspace when it has a
505    /// devcontainer.json; without one, only the user's setting turns it on. `notes` gets
506    /// what the model should hear once.
507    pub(crate) fn container(&self, ws: &Path, run: &dyn Runner, notes: &mut Vec<String>) -> Option<Result<container::Ready, String>> {
508        let devcontainer = devcontainer::find(ws);
509        let plan = run.plan();
510        // The workspace's (or chat's) environment setting decides; else the folder's answer.
511        let choice = plan.container.or_else(|| self.choices.get(ws).container);
512        let Some(c) = &self.containers else {
513            return (choice == Some(true)).then(|| {
514                Err("This workspace is set to run commands in a container, but neither Docker nor Podman is installed. Nothing ran. \
515                     Install one, or change the environment in the workspace's settings."
516                    .to_owned())
517            });
518        };
519        let dir = self.ws_dir(ws)?;
520        let want = match (choice, devcontainer, self.mode) {
521            (Some(v), ..) => v,
522            (None, None, _) | (None, Some(_), ProjectMode::Never) => false,
523            (None, Some(_), ProjectMode::Always) => true,
524            (None, Some(file), ProjectMode::Ask) => {
525                let _one = self.asking.lock().unwrap_or_else(PoisonError::into_inner);
526                match self.choices.get(ws).container {
527                    Some(v) => v,
528                    None => {
529                        let answer = run.ask(&container_question(file, c.runtime.name()));
530                        if let Err(e) = self.choices.set(ws, choices::Field::Container, Some(answer.allowed()), answer.by_user()) {
531                            log::warn!("environments: {e}");
532                        }
533                        answer.allowed()
534                    }
535                }
536            }
537        };
538        let first = self.told_container.lock().unwrap_or_else(PoisonError::into_inner).insert((ws.to_path_buf(), run.chat().filter(|_| want)));
539        if !want {
540            if let (Some(file), true) = (devcontainer, first) {
541                notes.push(format!("This workspace has {file}, but the user chose to run commands on their machine, not in the dev container."));
542            }
543            return None;
544        }
545        let spec = match spec_for(ws, &plan, &c.default_image) {
546            Ok(s) => s,
547            Err(e) => return Some(Err(format!("The workspace's dev container can't be used: {e}. Nothing ran."))),
548        };
549        let ready = c.ensure(ws, &spec, &dir.join("ctmp"), &|| run.cancelled());
550        if let Ok(r) = &ready {
551            if first || r.fresh {
552                let mut n = format!(
553                    "Commands run inside this workspace's {} container {} (image {}), as the user, not on their machine; the workspace is \
554                     mounted at the same path. install_packages installs with the container's package manager or pip. No internet unless a \
555                     call sets network: true.",
556                    c.runtime.name(),
557                    r.name,
558                    r.image
559                );
560                if !spec.ignored.is_empty() {
561                    n.push_str(&format!(" Settings in {} that byob ignores: {}.", spec.file.unwrap_or("devcontainer.json"), spec.ignored.join(", ")));
562                }
563                notes.push(n);
564            }
565            notes.extend(r.notes.iter().cloned());
566        }
567        Some(ready)
568    }
569
570    /// Remember what an install couldn't find, and point at the last resort.
571    fn note_missing(&self, ws: &Path, done: &mut Installed) {
572        if done.missing.is_empty() {
573            return;
574        }
575        self.missing.lock().unwrap_or_else(PoisonError::into_inner).entry(ws.to_path_buf()).or_default().extend(done.missing.iter().cloned());
576        if let Some(s) = &self.system {
577            done.text.push_str(&format!(
578                "\nOnly if there is no other way: install_system_packages can install {} system-wide with {} (the user must approve it).",
579                serde_json::json!(done.missing),
580                s.name()
581            ));
582        }
583    }
584
585    /// The project files of `ws` byob can load an environment from, with their labels.
586    fn project_files(&self, ws: &Path) -> Vec<(&'static str, &'static str)> {
587        self.projects.iter().filter_map(|p| p.file(ws).map(|f| (f, p.label()))).collect()
588    }
589
590    /// May `ws`'s project environment be loaded? Asks the user the first time (once per
591    /// workspace; a person's answer is saved, the policy's lasts for this process). When
592    /// it may not, the model is told once.
593    fn project_consent(&self, ws: &Path, run: &dyn Runner, notes: &mut Vec<String>) -> bool {
594        let files = self.project_files(ws);
595        if files.is_empty() || self.state.is_none() {
596            return false;
597        }
598        let allowed = match (self.mode, run.plan().project) {
599            (ProjectMode::Never, _) => return false,
600            (ProjectMode::Always, _) => true,
601            // The workspace's environment setting (Nix) decided; no question.
602            (ProjectMode::Ask, Some(v)) => v,
603            (ProjectMode::Ask, None) => {
604                let _one = self.asking.lock().unwrap_or_else(PoisonError::into_inner);
605                match self.choices.get(ws).project {
606                    Some(v) => v,
607                    None => {
608                        let answer = run.ask(&project_question(&files));
609                        let save = answer.by_user();
610                        if let Err(e) = self.choices.set(ws, choices::Field::Project, Some(answer.allowed()), save) {
611                            log::warn!("environments: {e}");
612                        }
613                        answer.allowed()
614                    }
615                }
616            }
617        };
618        if !allowed && self.told.lock().unwrap_or_else(PoisonError::into_inner).insert(ws.to_path_buf()) {
619            let what: Vec<String> = files.iter().map(|(f, label)| format!("{f} ({label})")).collect();
620            notes.push(format!(
621                "This workspace declares an environment in {}, but the user chose not to load it, so commands run without it. \
622                 Don't load it yourself (e.g. with nix develop).",
623                what.join(", ")
624            ));
625        }
626        allowed
627    }
628
629    /// Install `packages` for workspace `ws`.
630    pub(crate) fn install(&self, ws: &Path, packages: &[String], run: &dyn Runner) -> Result<Installed, String> {
631        let mut notes = Vec::new();
632        if let Some(ready) = self.container(ws, run, &mut notes) {
633            let ready = ready?;
634            let c = self.containers.as_ref().ok_or("no container runtime")?;
635            let mut done = c.install(&ready, ws, packages, &|| run.cancelled())?;
636            if !notes.is_empty() {
637                done.text = format!("({})\n\n{}", notes.join(")\n("), done.text);
638            }
639            return Ok(done);
640        }
641        let _busy = self.busy.lock().unwrap_or_else(PoisonError::into_inner);
642        let Some(dir) = self.ws_dir(ws) else { return Err("byob has no data folder to install packages into".into()) };
643        let mut done = match (&self.nix, &self.pixi) {
644            (Some(nix), _) => nix.install(&dir, packages, run)?,
645            (None, Some(pixi)) => pixi.install(&dir, packages, run)?,
646            (None, None) => return Err(format!("no package manager is available here: {}", hints::GET_PIXI)),
647        };
648        self.note_missing(ws, &mut done);
649        Ok(done)
650    }
651}
652
653/// The canonical path of a workspace (how its answers are keyed), or `ws` as given.
654fn canonical(ws: &Path) -> PathBuf {
655    ws.canonicalize().unwrap_or_else(|_| ws.to_path_buf())
656}
657
658/// How to make `ws`'s container: the image its settings name, else its devcontainer.json,
659/// else `default_image`.
660fn spec_for(ws: &Path, plan: &EnvPlan, default_image: &str) -> Result<devcontainer::Spec, String> {
661    match plan.image.as_deref().filter(|i| devcontainer::valid_image(i)) {
662        Some(image) => Ok(devcontainer::Spec::default_image(image)),
663        None => devcontainer::Spec::for_workspace(ws, default_image),
664    }
665}
666
667impl EnvControl for Envs {
668    fn describe(&self, ws: &Path, plan: &EnvPlan) -> WorkspaceEnv {
669        let ws = canonical(ws);
670        let c = self.choices.get(&ws);
671        WorkspaceEnv {
672            workspace: ws.display().to_string(),
673            project_files: self.project_files(&ws).into_iter().map(|(f, _)| f.to_owned()).collect(),
674            project_env: c.project,
675            project_env_forced: match (self.mode, plan.project) {
676                (ProjectMode::Always, _) => Some(true),
677                (ProjectMode::Never, _) => Some(false),
678                (ProjectMode::Ask, forced) => forced,
679            },
680            installer: self.installer().map(str::to_owned),
681            container: match &self.containers {
682                None => ContainerEnv {
683                    use_container: plan.container.or(c.container),
684                    devcontainer: devcontainer::find(&ws).map(str::to_owned),
685                    ..ContainerEnv::default()
686                },
687                Some(k) => ContainerEnv {
688                    runtime: Some(k.runtime.name().to_owned()),
689                    devcontainer: devcontainer::find(&ws).map(str::to_owned),
690                    use_container: plan.container.or(c.container),
691                    image: spec_for(&ws, plan, &k.default_image).map_or_else(|e| e, |s| s.describe(&ws)),
692                    state: k.state(&ws),
693                },
694            },
695            message: None,
696            failed: false,
697        }
698    }
699
700    fn support(&self) -> EnvSupport {
701        EnvSupport {
702            nix: self.nix.is_some(),
703            installer: self.installer().map(str::to_owned),
704            runtime: self.containers.as_ref().map(|c| c.runtime.name().to_owned()),
705        }
706    }
707
708    fn check_containers(&self) -> Result<String, String> {
709        let c = self.containers.as_ref().ok_or("Neither Docker nor Podman is installed on the machine byob runs on.")?;
710        c.runtime.check()?;
711        Ok(format!("{} is running.", c.runtime.name()))
712    }
713
714    fn forget(&self, ws: &Path) -> Result<String, String> {
715        let ws = canonical(ws);
716        let mut done = Vec::new();
717        if let Some(c) = &self.containers
718            && c.state(&ws).is_some()
719        {
720            c.remove(&ws)?;
721            done.push("removed its container");
722        }
723        if let Some(dir) = self.ws_dir(&ws).filter(|d| d.exists()) {
724            std::fs::remove_dir_all(&dir).map_err(|e| format!("couldn't delete {}: {e}", dir.display()))?;
725            done.push("deleted its installed packages and caches");
726        }
727        let had = self.choices.get(&ws) != choices::Choice::default();
728        self.choices.set(&ws, choices::Field::Project, None, true)?;
729        self.choices.set(&ws, choices::Field::Container, None, true)?;
730        if had {
731            done.push("forgot its answers");
732        }
733        self.told.lock().unwrap_or_else(PoisonError::into_inner).remove(&ws);
734        self.told_container.lock().unwrap_or_else(PoisonError::into_inner).retain(|(w, _)| *w != ws);
735        self.missing.lock().unwrap_or_else(PoisonError::into_inner).remove(&ws);
736        Ok(if done.is_empty() { "byob kept nothing else for this folder.".into() } else { format!("byob {}.", done.join(", ")) })
737    }
738
739    fn apply(&self, ws: &Path, action: &EnvAction) -> Result<String, String> {
740        let ws = canonical(ws);
741        match action {
742            EnvAction::ProjectEnv { load } => {
743                self.choices.set(&ws, choices::Field::Project, *load, true)?;
744                self.told.lock().unwrap_or_else(PoisonError::into_inner).remove(&ws);
745                Ok(match load {
746                    Some(true) => "The workspace's environment loads from the next command on.",
747                    Some(false) => "Commands run without the workspace's environment.",
748                    None => "byob asks again before the next command.",
749                }
750                .into())
751            }
752            EnvAction::Container { on } => {
753                self.choices.set(&ws, choices::Field::Container, *on, true)?;
754                self.told_container.lock().unwrap_or_else(PoisonError::into_inner).retain(|(w, _)| *w != ws);
755                Ok(match on {
756                    Some(true) => "Commands run in the workspace's container from the next one on.",
757                    Some(false) => "Commands run on this machine (the container is kept until you remove it).",
758                    None => "byob asks again if the workspace has a devcontainer.json.",
759                }
760                .into())
761            }
762            EnvAction::StopContainer => self.containers.as_ref().ok_or("Neither Docker nor Podman is installed.")?.stop(&ws),
763            EnvAction::RemoveContainer => self.containers.as_ref().ok_or("Neither Docker nor Podman is installed.")?.remove(&ws),
764        }
765    }
766}
767
768/// "Run commands in the dev container?", asked once per workspace with a devcontainer.json.
769fn container_question(file: &str, runtime: &str) -> Question {
770    Question {
771        title: format!("Run this workspace's commands in its dev container ({file})"),
772        text: format!(
773            "byob would create a long-lived {runtime} container from {file} for this workspace and run run_command and run_python inside it, \
774             as your user, with the workspace mounted at the same path. Getting or building the image can take minutes and uses the \
775             internet; its setup commands run once. Your answer is remembered for this workspace; change it in the workspace's settings (its menu in the chat list)."
776        ),
777        warning: None,
778        access: Access::Execute,
779        always_ask: false,
780    }
781}
782
783/// "Load this workspace's environment?", asked once per workspace.
784fn project_question(files: &[(&str, &str)]) -> Question {
785    let labels: Vec<&str> = files.iter().map(|(_, l)| *l).collect();
786    let names: Vec<&str> = files.iter().map(|(f, _)| *f).collect();
787    Question {
788        title: format!("Load this workspace's {} ({})", labels.join(" and "), names.join(", ")),
789        text: format!(
790            "byob would load the environment {} declares before every run_command and run_python, so its programs are available. \
791             The first load can take minutes, downloads with internet access, runs the project's setup code, and may write lock files \
792             (flake.lock, pixi.lock) or a .pixi folder into the workspace. Your answer is remembered for this workspace; \
793             change it in the workspace's settings (its menu in the chat list).",
794            names.join(" / ")
795        ),
796        warning: None,
797        access: Access::Execute,
798        always_ask: false,
799    }
800}
801
802/// A Python virtual environment in the workspace (`.venv` or `venv`): its scripts folder
803/// goes first on `PATH`, as `activate` would do.
804pub fn venv_layer(ws: &Path) -> Option<Layer> {
805    for name in [".venv", "venv"] {
806        let venv = ws.join(name);
807        if !venv.join("pyvenv.cfg").is_file() {
808            continue;
809        }
810        let bin = if cfg!(windows) { venv.join("Scripts") } else { venv.join("bin") };
811        if bin.is_dir() {
812            return Some(Layer { path: vec![bin], vars: vec![("VIRTUAL_ENV".into(), venv.to_string_lossy().into_owned())], ..Default::default() });
813        }
814    }
815    None
816}
817
818/// `PATH` for a run: `prefix` then the host's.
819pub fn join_path(prefix: &[PathBuf], host: Option<&std::ffi::OsStr>) -> OsString {
820    let mut all: Vec<PathBuf> = prefix.to_vec();
821    if let Some(h) = host {
822        for p in std::env::split_paths(h) {
823            if !all.contains(&p) {
824                all.push(p);
825            }
826        }
827    }
828    std::env::join_paths(all).unwrap_or_default()
829}
830
831/// FNV-1a: a stable 64-bit hash for cache keys (std's hasher may change between releases).
832pub fn fnv64(bytes: &[u8]) -> u64 {
833    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
834    for b in bytes {
835        h ^= u64::from(*b);
836        h = h.wrapping_mul(0x0100_0000_01b3);
837    }
838    h
839}
840
841/// Write `bytes` to `path` via a temp file and rename, so readers never see half a file.
842pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
843    if let Some(parent) = path.parent() {
844        std::fs::create_dir_all(parent).map_err(|e| format!("can't create {}: {e}", parent.display()))?;
845    }
846    let tmp = path.with_extension("tmp");
847    std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)).map_err(|e| format!("can't write {}: {e}", path.display()))
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853
854    #[test]
855    fn stacking_keeps_the_first_value_and_order() {
856        let mut a = Layer { path: vec!["/a".into()], vars: vec![("X".into(), "1".into())], ..Default::default() };
857        let b = Layer {
858            path: vec!["/b".into(), "/a".into()],
859            vars: vec![("X".into(), "2".into()), ("Y".into(), "3".into())],
860            sockets: vec!["/s".into()],
861            ..Default::default()
862        };
863        a.stack(&b);
864        assert_eq!(a.path, vec![PathBuf::from("/a"), PathBuf::from("/b")]);
865        assert_eq!(a.var("X"), Some("1"));
866        assert_eq!(a.var("Y"), Some("3"));
867        assert_eq!(a.sockets, vec![PathBuf::from("/s")]);
868    }
869
870    #[cfg(unix)]
871    #[test]
872    fn path_is_prefix_then_host_without_duplicates() {
873        let p = join_path(&["/env/bin".into(), "/usr/bin".into()], Some("/usr/bin:/bin".as_ref()));
874        assert_eq!(p, "/env/bin:/usr/bin:/bin");
875    }
876
877    #[test]
878    fn venv_in_the_workspace_goes_first() {
879        let d = tempfile::tempdir().unwrap();
880        assert!(venv_layer(d.path()).is_none());
881        let bin = if cfg!(windows) { "Scripts" } else { "bin" };
882        std::fs::create_dir_all(d.path().join(".venv").join(bin)).unwrap();
883        assert!(venv_layer(d.path()).is_none(), "no pyvenv.cfg, not a venv");
884        std::fs::write(d.path().join(".venv/pyvenv.cfg"), "home = /usr/bin\n").unwrap();
885        let l = venv_layer(d.path()).unwrap();
886        assert_eq!(l.path, vec![d.path().join(".venv").join(bin)]);
887        assert!(l.var("VIRTUAL_ENV").is_some());
888    }
889
890    /// Loads by counting; fails while `bad` exists in the workspace.
891    #[derive(Debug, Default)]
892    struct Fake(std::sync::atomic::AtomicUsize);
893
894    impl Project for Fake {
895        fn id(&self) -> &'static str {
896            "fake"
897        }
898        fn label(&self) -> &'static str {
899            "fake env"
900        }
901        fn file(&self, ws: &Path) -> Option<&'static str> {
902            ws.join("fake.toml").is_file().then_some("fake.toml")
903        }
904        fn inputs(&self) -> &'static [&'static str] {
905            &["fake.toml", "fake.lock"]
906        }
907        fn load(&self, ws: &Path, _dir: &Path, _run: &dyn Runner) -> Result<Layer, String> {
908            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
909            // Like `nix` writing flake.lock on first load.
910            std::fs::write(ws.join("fake.lock"), "locked").map_err(|e| e.to_string())?;
911            if ws.join("bad").exists() { Err("broken".into()) } else { Ok(Layer { vars: vec![("A".into(), "1".into())], ..Default::default() }) }
912        }
913    }
914
915    struct NoRun;
916    impl Runner for NoRun {
917        fn run(&self, _job: Job, _cwd: &Path, _tmp: &Path) -> Result<Outcome, String> {
918            Err("not in this test".into())
919        }
920    }
921
922    /// Answers every question with `answer`, counting them.
923    struct Asks {
924        answer: Answer,
925        asked: std::sync::atomic::AtomicUsize,
926    }
927    impl Asks {
928        fn new(answer: Answer) -> Self {
929            Self { answer, asked: std::sync::atomic::AtomicUsize::new(0) }
930        }
931        fn count(&self) -> usize {
932            self.asked.load(std::sync::atomic::Ordering::SeqCst)
933        }
934    }
935    impl Runner for Asks {
936        fn run(&self, _job: Job, _cwd: &Path, _tmp: &Path) -> Result<Outcome, String> {
937            Err("not in this test".into())
938        }
939        fn ask(&self, q: &Question) -> Answer {
940            assert!(q.title.contains("fake.toml") && !q.always_ask, "{q:?}");
941            self.asked.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
942            self.answer
943        }
944    }
945
946    impl Project for std::sync::Arc<Fake> {
947        fn id(&self) -> &'static str {
948            self.as_ref().id()
949        }
950        fn label(&self) -> &'static str {
951            self.as_ref().label()
952        }
953        fn file(&self, ws: &Path) -> Option<&'static str> {
954            self.as_ref().file(ws)
955        }
956        fn inputs(&self) -> &'static [&'static str] {
957            self.as_ref().inputs()
958        }
959        fn load(&self, ws: &Path, dir: &Path, run: &dyn Runner) -> Result<Layer, String> {
960            self.as_ref().load(ws, dir, run)
961        }
962    }
963
964    fn envs_with_fake(data: &Path, mode: ProjectMode) -> (Envs, std::sync::Arc<Fake>) {
965        let fake = std::sync::Arc::new(Fake::default());
966        let state = data.join("envs");
967        let e = Envs {
968            projects: vec![Box::new(std::sync::Arc::clone(&fake))],
969            choices: choices::Choices::new(Some(state.join("workspaces.json"))),
970            state: Some(state),
971            mode,
972            ..Envs::default()
973        };
974        (e, fake)
975    }
976
977    #[test]
978    fn project_envs_load_only_after_the_user_agrees_once_per_workspace() {
979        let data = tempfile::tempdir().unwrap();
980        let ws = tempfile::tempdir().unwrap();
981        let ws = ws.path().canonicalize().unwrap();
982        let (e, fake) = envs_with_fake(data.path(), ProjectMode::Ask);
983        let loads = || fake.0.load(std::sync::atomic::Ordering::SeqCst);
984        // No project file: nothing to ask.
985        let yes = Asks::new(Answer::Yes);
986        assert!(e.prepare(&ws, &yes).notes.is_empty() && yes.count() == 0);
987
988        std::fs::write(ws.join("fake.toml"), "v1").unwrap();
989        // The user says no: not loaded, the model is told once, and the answer is saved.
990        let no = Asks::new(Answer::No);
991        let p = e.prepare(&ws, &no);
992        assert_eq!((no.count(), loads()), (1, 0));
993        assert!(p.notes.len() == 1 && p.notes[0].contains("chose not to load") && p.notes[0].contains("fake.toml"), "{:?}", p.notes);
994        let p = e.prepare(&ws, &no);
995        assert!(p.notes.is_empty() && no.count() == 1 && loads() == 0, "asked and told once");
996        let (fresh, _) = envs_with_fake(data.path(), ProjectMode::Ask);
997        let p = fresh.prepare(&ws, &no);
998        assert_eq!(no.count(), 1, "remembered across restarts");
999        assert_eq!(p.notes.len(), 1, "a new process tells the model again, once");
1000
1001        // Forget it in the settings: asked again; yes loads it, and is remembered.
1002        let forgot = e.apply(&ws, &EnvAction::ProjectEnv { load: None }).unwrap();
1003        assert!(forgot.contains("asks again"), "{forgot}");
1004        assert_eq!(e.describe(&ws, &byob_tools::EnvPlan::default()).project_env, None);
1005        let p = e.prepare(&ws, &yes);
1006        assert_eq!((yes.count(), loads()), (1, 1));
1007        assert!(p.layer.var("A") == Some("1") && p.notes[0].starts_with("Loaded"), "{:?}", p.notes);
1008        e.prepare(&ws, &yes);
1009        assert_eq!(yes.count(), 1);
1010        let d = e.describe(&ws, &byob_tools::EnvPlan::default());
1011        assert_eq!((d.project_files, d.project_env, d.project_env_forced), (vec!["fake.toml".to_owned()], Some(true), None));
1012    }
1013
1014    #[test]
1015    fn automatic_answers_last_for_the_session_and_the_override_wins() {
1016        let data = tempfile::tempdir().unwrap();
1017        let ws = tempfile::tempdir().unwrap();
1018        let ws = ws.path().canonicalize().unwrap();
1019        std::fs::write(ws.join("fake.toml"), "v1").unwrap();
1020        // --auto-approve: loaded without a person, not saved.
1021        let (e, fake) = envs_with_fake(data.path(), ProjectMode::Ask);
1022        let auto = Asks::new(Answer::AutoYes);
1023        assert_eq!(e.prepare(&ws, &auto).layer.var("A"), Some("1"));
1024        e.prepare(&ws, &auto);
1025        assert_eq!(auto.count(), 1, "asked once per session");
1026        let (again, _) = envs_with_fake(data.path(), ProjectMode::Ask);
1027        assert_eq!(again.describe(&ws, &byob_tools::EnvPlan::default()).project_env, None, "not saved");
1028        // Nobody to ask (no asker): not loaded, nothing saved.
1029        let nobody = NoRun;
1030        assert!(again.prepare(&ws, &nobody).layer.var("A").is_none());
1031        // BYOB_WORKSPACE_ENV=off / on.
1032        let (never, _) = envs_with_fake(data.path(), ProjectMode::Never);
1033        let yes = Asks::new(Answer::Yes);
1034        assert!(never.prepare(&ws, &yes).layer.is_empty() && yes.count() == 0);
1035        let (always, _) = envs_with_fake(data.path(), ProjectMode::Always);
1036        assert!(always.prepare(&ws, &yes).layer.var("A") == Some("1") && yes.count() == 0);
1037        assert_eq!(always.describe(&ws, &byob_tools::EnvPlan::default()).project_env_forced, Some(true));
1038        assert!(fake.0.load(std::sync::atomic::Ordering::SeqCst) >= 1);
1039    }
1040
1041    #[test]
1042    fn project_envs_are_cached_until_their_files_change() {
1043        let ws = tempfile::tempdir().unwrap();
1044        let dir = tempfile::tempdir().unwrap();
1045        let p = Fake::default();
1046        let loads = || p.0.load(std::sync::atomic::Ordering::SeqCst);
1047        assert!(load_project(&p, ws.path(), dir.path(), &NoRun).is_none(), "no project file");
1048        std::fs::write(ws.path().join("fake.toml"), "v1").unwrap();
1049        let first = load_project(&p, ws.path(), dir.path(), &NoRun).unwrap();
1050        assert!(first.fresh && first.result.unwrap().var("A") == Some("1") && loads() == 1);
1051        let second = load_project(&p, ws.path(), dir.path(), &NoRun).unwrap();
1052        assert!(!second.fresh && second.result.is_ok() && loads() == 1, "cached, though the load wrote the lock file");
1053        std::fs::write(ws.path().join("fake.toml"), "v2").unwrap();
1054        std::fs::write(ws.path().join("bad"), "").unwrap();
1055        let broken = load_project(&p, ws.path(), dir.path(), &NoRun).unwrap();
1056        assert!(broken.fresh && broken.result.is_err() && loads() == 2);
1057        let again = load_project(&p, ws.path(), dir.path(), &NoRun).unwrap();
1058        assert!(!again.fresh && again.result.is_err() && loads() == 2, "a failure is cached too");
1059    }
1060
1061    #[test]
1062    fn workspace_folders_are_stable_and_distinct() {
1063        let e = Envs { state: Some("/data/envs".into()), ..Envs::default() };
1064        let a = e.ws_dir(Path::new("/home/me/My Project")).unwrap();
1065        assert_eq!(a, e.ws_dir(Path::new("/home/me/My Project")).unwrap());
1066        assert_ne!(a, e.ws_dir(Path::new("/home/you/My Project")).unwrap());
1067        assert!(a.file_name().unwrap().to_string_lossy().starts_with("MyProject-"));
1068        assert_eq!(fnv64(b""), 0xcbf2_9ce4_8422_2325);
1069        assert!(Envs::none().installer().is_none() && Envs::none().prompt().is_none());
1070    }
1071}