A desktop coding agent with free access to frontier models.
TypeScript
fix: farm mode (stock) sandbox fails closed, says offline, final registry list
ogsamratd200613abf29
diff --git a/apps/desktop/box/go/cmd/boxd/egress.go b/apps/desktop/box/go/cmd/boxd/egress.goindex 73ae3f63..3afecb6f 100644--- a/apps/desktop/box/go/cmd/boxd/egress.go+++ b/apps/desktop/box/go/cmd/boxd/egress.go@@ -8,11 +8,12 @@// listener is inside the commands' namespace (127.0.0.1) and whose dials are// outside it. The proxy lets through the package registries in farmAllow// and answers 403 with a readable body for every other host, at once.-// Commands get HTTP(S)_PROXY and the package managers' proxy settings.+// Commands get HTTP(S)_PROXY and the package managers' proxy settings, and+// shims for git, curl and wget (offlineBin) that print the same line for a+// remote they cannot reach instead of a bare DNS or proxy error.//-// Where boxd may not make a namespace (a container without CAP_SYS_ADMIN),-// the proxy still runs and the variables are still set, but a program that-// ignores the proxy is not stopped: boxd logs "egress: proxy only".+// Fail closed: where boxd may not make a namespace (a container without+// CAP_SYS_ADMIN), it refuses to start; nothing runs with the network open.package mainimport (@@ -21,6 +22,8 @@ import ("log""net""net/http"+ "os"+ "path/filepath""runtime""strconv""strings"@@ -30,19 +33,30 @@ import ("unsafe")-// farmAllow: the hosts the farm proxy lets through (exact, or "*." for any subdomain).-// The registries the farm asked for, plus the mirrors the box images themselves use-// (Debian apt; Node headers for node-gyp; Maven and RubyGems for the java and ruby stacks).+// farmAllow: the hosts a farm box reaches (exact host names), the one list for the proxy and+// the shims: add a host here. Everything else, GitHub's hosts included, is refused.var farmAllow = []string{- "registry.npmjs.org", "registry.yarnpkg.com",- "pypi.org", "files.pythonhosted.org",- "index.crates.io", "static.crates.io", "crates.io",+ // npm / node+ "registry.npmjs.org", "registry.yarnpkg.com", "repo.yarnpkg.com", "nodejs.org",+ // Python+ "pypi.org", "pypi.python.org", "files.pythonhosted.org", "releases.astral.sh", "conda.anaconda.org",+ // Rust+ "crates.io", "index.crates.io", "static.crates.io", "static.rust-lang.org",+ // Go"proxy.golang.org", "sum.golang.org",- "repo.packagist.org",- "deb.debian.org", "security.debian.org",- "nodejs.org",- "repo.maven.apache.org", "repo1.maven.org",+ // PHP+ "packagist.org", "repo.packagist.org",+ // Ruby"rubygems.org", "index.rubygems.org",+ // JVM+ "repo.maven.apache.org", "repo1.maven.org", "plugins.gradle.org", "plugins-artifacts.gradle.org", "services.gradle.org", "downloads.gradle.org",+ // Others+ "api.nuget.org", "pub.dev", "jsr.io", "deno.land", "repo.hex.pm", "builds.hex.pm",+ // Debian (the box images' apt)+ "deb.debian.org", "security.debian.org",+ // Install-time downloads (prisma, playwright, puppeteer)+ "binaries.prisma.sh", "cdn.playwright.dev", "playwright.download.prss.microsoft.com", "playwright.azureedge.net",+ "playwright-akamai.azureedge.net", "playwright-verizon.azureedge.net", "storage.googleapis.com",}// The proxy's port inside the commands' namespace (0: no farm egress) and that namespace (-1: none).@@ -51,13 +65,24 @@ var (egressNS = -1)+// offlineLine: what a refused call says (the proxy's 403 body, the shims).+func offlineLine(host string) string {+ return "omnirush: " + host + " is not reachable: this session is offline, so mock the service (package installs from the registries still work)"+}++// offlineBin: the shims' folder, first on the commands' PATH (/opt/omnirush is left out of snapshots).+var offlineBin = "/opt/omnirush/offline/bin"++// unshareNet makes the calling thread's network namespace (a variable: tests make it fail).+var unshareNet = func() error { return syscall.Unshare(syscall.CLONE_NEWNET) }+// setns(2): not in package syscall (the box helpers are built for amd64 and arm64).var sysSetns = map[string]uintptr{"amd64": 308, "arm64": 268}[runtime.GOARCH]func allowedHost(host string) bool {host = strings.TrimSuffix(strings.ToLower(host), ".")for _, a := range farmAllow {- if host == a || strings.HasPrefix(a, "*.") && strings.HasSuffix(host, a[1:]) {+ if host == a {return true}}@@ -78,13 +103,16 @@ func startEgress(mode string) error {go func() {// Never unlocked: this thread's namespace changes, so the runtime drops it at the end.runtime.LockOSThread()- ns := -1- if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil {- log.Printf("egress: proxy only (no network namespace: %v)", err)- } else if err := loopbackUp(); err != nil {+ if err := unshareNet(); err != nil {+ ch <- made{err: fmt.Errorf("this sandbox cannot keep the session offline (no network namespace: %w)", err)}+ return+ }+ if err := loopbackUp(); err != nil {ch <- made{err: fmt.Errorf("loopback: %w", err)}return- } else if ns, err = syscall.Open("/proc/thread-self/ns/net", syscall.O_RDONLY|syscall.O_CLOEXEC, 0); err != nil {+ }+ ns, err := syscall.Open("/proc/thread-self/ns/net", syscall.O_RDONLY|syscall.O_CLOEXEC, 0)+ if err != nil {ch <- made{err: err}return}@@ -95,10 +123,13 @@ func startEgress(mode string) error {if m.err != nil {return m.err}+ if err := writeShims(offlineBin); err != nil {+ return fmt.Errorf("shims: %w", err)+ }egressNS = m.nsegressPort.Store(int64(m.ln.Addr().(*net.TCPAddr).Port))go (&http.Server{Handler: http.HandlerFunc(proxy), ReadHeaderTimeout: 30 * time.Second}).Serve(m.ln)- log.Printf("egress: farm proxy on 127.0.0.1:%d (namespace=%v)", egressPort.Load(), egressNS >= 0)+ log.Printf("egress: farm proxy on 127.0.0.1:%d, commands in their own network", egressPort.Load())return nil}@@ -161,7 +192,21 @@ func blocked(w http.ResponseWriter, host string) {w.Header().Set("Content-Type", "text/plain; charset=utf-8")w.Header().Set("X-Omnirush-Blocked", host)w.WriteHeader(http.StatusForbidden)- fmt.Fprintf(w, "omnirush: %s is blocked in this environment (no internet access here; only package registries are reachable)\n", host)+ fmt.Fprintln(w, offlineLine(host))+}++// hopHeaders: one connection's own headers, never passed on (RFC 9110 7.6.1), with those Connection names.+var hopHeaders = []string{"Connection", "Proxy-Connection", "Keep-Alive", "Proxy-Authorization", "Proxy-Authenticate", "Te", "Trailer", "Transfer-Encoding", "Upgrade"}++func dropHop(h http.Header) {+ for _, v := range h.Values("Connection") {+ for _, name := range strings.Split(v, ",") {+ h.Del(strings.TrimSpace(name))+ }+ }+ for _, name := range hopHeaders {+ h.Del(name)+ }}var direct = &http.Transport{Proxy: nil, DialContext: (&net.Dialer{Timeout: 15 * time.Second}).DialContext, ResponseHeaderTimeout: 60 * time.Second}@@ -174,7 +219,7 @@ func proxy(w http.ResponseWriter, r *http.Request) {if r.Method == http.MethodConnect {if port != "443" || !allowedHost(host) {log.Printf("egress: blocked CONNECT %s", r.Host)- blocked(w, r.Host)+ blocked(w, host)return}upstream, err := net.DialTimeout("tcp", r.Host, 15*time.Second)@@ -197,18 +242,18 @@ func proxy(w http.ResponseWriter, r *http.Request) {// A plain http:// request through the proxy (apt, some pip mirrors).if r.URL.Scheme != "http" || (port != "" && port != "80") || !allowedHost(host) {log.Printf("egress: blocked %s %s", r.Method, r.URL.Redacted())- blocked(w, r.Host)+ blocked(w, host)return}r.RequestURI = ""- r.Header.Del("Proxy-Connection")- r.Header.Del("Proxy-Authorization")+ dropHop(r.Header)res, err := direct.RoundTrip(r)if err != nil {http.Error(w, "omnirush: "+err.Error(), http.StatusBadGateway)return}defer res.Body.Close()+ dropHop(res.Header)for k, vs := range res.Header {for _, v := range vs {w.Header().Add(k, v)@@ -225,3 +270,99 @@ func netProc() string {}return "/proc/thread-self/net/"}++// writeShims puts git, curl and wget into dir: a call to a remote that is not a farm host (nor+// this box's loopback) prints offlineLine and fails; every other call runs the real program.+func writeShims(dir string) error {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ return err+ }+ lib := strings.NewReplacer("@DIR@", dir, "@ALLOW@", strings.Join(farmAllow, " "), "@LINE@", offlineLine("$1")).Replace(shimLib)+ for name, body := range map[string]string{"git": shimGit, "curl": shimFetch, "wget": shimFetch} {+ code := "7"+ if name == "wget" {+ code = "4"+ }+ text := "#!/bin/bash\n# OmniRush offline shim (farm runs; boxd egress.go).\n" + lib + strings.NewReplacer("@TOOL@", name, "@CODE@", code).Replace(body)+ tmp := filepath.Join(dir, "."+name+".tmp")+ if err := os.WriteFile(tmp, []byte(text), 0o755); err != nil {+ return err+ }+ if err := os.Rename(tmp, filepath.Join(dir, name)); err != nil {+ return err+ }+ }+ return nil+}++const shimLib = `ALLOW="@ALLOW@"+SHIMS=":@DIR@:"+without_shims() { local p=":$PATH:"; p=${p//"$SHIMS"/:}; p=${p#:}; printf '%s' "${p%:}"; }+real() { PATH=$(without_shims); export PATH; exec "$@"; }+refuse() { echo "@LINE@" >&2; exit "$2"; }+# host_of URL: the host of scheme://[user@]host[:port]/... or [user@]host:path (scp-like); "" for a local path.+host_of() {+ local u=$1 h+ case "$u" in+ file://*) return ;;+ *://*) h=${u#*://}; h=${h%%/*}; h=${h%%\?*}; h=${h##*@} ;;+ *:*) h=${u%%:*}; case "$h" in */*|"") return ;; esac; h=${h##*@} ;;+ *) return ;;+ esac+ case "$h" in \[*) h=${h#[}; h=${h%%]*} ;; *) h=${h%%:*} ;; esac+ printf '%s' "${h,,}"+}+reachable() {+ case "$1" in ""|localhost|*.localhost|127.*|::1|0.0.0.0|omnirush-box) return 0 ;; esac+ local a; for a in $ALLOW; do [ "$1" = "$a" ] && return 0; done+ return 1+}+`++const shimFetch = `for a in "$@"; do+ case "$a" in --url=*) a=${a#--url=} ;; esac+ case "${a,,}" in http://*|https://*|ftp://*|ftps://*) h=$(host_of "$a"); reachable "$h" || refuse "$h" @CODE@ ;; esac+done+real @TOOL@ "$@"+`++const shimGit = `args=("$@"); i=0+while [ $i -lt ${#args[@]} ]; do+ case "${args[$i]}" in+ -C|-c|--git-dir|--work-tree|--namespace|--config-env) i=$((i + 2)) ;;+ -*) i=$((i + 1)) ;;+ *) break ;;+ esac+done+sub=${args[$i]}; pre=("${args[@]:0:$i}"); rest=("${args[@]:$((i + 1))}")+gitc() { (PATH=$(without_shims); git "${pre[@]}" "$@" 2>/dev/null); }+check() { local h; h=$(host_of "$1"); reachable "$h" || refuse "$h" 128; }+case "$sub" in+ clone|fetch|pull|push|ls-remote|submodule)+ # The repository: any scheme://... argument, and the first plain argument (a URL, a+ # [user@]host:path, or a remote's name); later ones are refspecs or folders.+ first=; j=0+ while [ $j -lt ${#rest[@]} ]; do+ a=${rest[$j]}; j=$((j + 1))+ case "$a" in+ *://*) check "$a"; [ -z "$first" ] && first=$a; continue ;;+ --depth|-b|--branch|-o|--origin|-j|--jobs|--reference|--reference-if-able|--template|-u|--upload-pack|--receive-pack|--exec|--filter|--server-option|-c|--config|--separate-git-dir|--shallow-since|--shallow-exclude|--recurse-submodules-default) j=$((j + 1)); continue ;;+ -*) continue ;;+ esac+ [ -n "$first" ] && continue+ first=$a+ if [ -n "$(host_of "$a")" ]; then check "$a"; else url=$(gitc config --get "remote.$a.url"); [ -n "$url" ] && check "$url"; fi+ done+ if [ "$sub" = submodule ]; then+ case " ${rest[*]} " in *" update "*)+ top=$(gitc rev-parse --show-toplevel)+ [ -n "$top" ] && [ -f "$top/.gitmodules" ] && while read -r _ url; do check "$url"; done < <(gitc config -f "$top/.gitmodules" --get-regexp '^submodule\..*\.url$') ;;+ esac+ elif [ -z "$first" ] && [ "$sub" != clone ]; then+ # No remote named: the branch's own, else origin.+ br=$(gitc symbolic-ref --short -q HEAD); rem=$(gitc config --get "branch.$br.remote"); url=$(gitc config --get "remote.${rem:-origin}.url")+ [ -n "$url" ] && check "$url"+ fi ;;+esac+real git "$@"+`diff --git a/apps/desktop/box/go/cmd/boxd/egress_test.go b/apps/desktop/box/go/cmd/boxd/egress_test.goindex f6ff3763..75d8998d 100644--- a/apps/desktop/box/go/cmd/boxd/egress_test.go+++ b/apps/desktop/box/go/cmd/boxd/egress_test.go@@ -4,10 +4,15 @@ package mainimport ("bufio"+ "errors""io""net""net/http"+ "os"+ "os/exec"+ "path/filepath""strings"+ "syscall""testing""time")@@ -18,6 +23,8 @@ func TestAllowedHost(t *testing.T) {"proxy.golang.org": true, "repo.packagist.org": true,"api.github.com": false, "github.com": false, "raw.githubusercontent.com": false, "evil.registry.npmjs.org.attacker.io": false,"x.fly.dev": false, "api.crossref.org": false, "127.0.0.1": false, "": false,+ "static.rust-lang.org": true, "releases.astral.sh": true, "storage.googleapis.com": true, "plugins.gradle.org": true, "packagist.org": true,+ "codeload.github.com": false, "objects.githubusercontent.com": false, "downloads.python.org": false, "omnirush.ai": false, "x.storage.googleapis.com": false,} {if got := allowedHost(host); got != want {t.Errorf("allowedHost(%q) = %v, want %v", host, got, want)@@ -56,7 +63,7 @@ func TestProxyRefusesFast(t *testing.T) {}body, _ := io.ReadAll(io.LimitReader(res.Body, 4096))c.Close()- if res.StatusCode != 403 || !strings.Contains(string(body), "is blocked in this environment") {+ if res.StatusCode != 403 || !strings.Contains(string(body), "is not reachable: this session is offline, so mock the service (package installs from the registries still work)") || strings.Contains(string(body), ":443") {t.Errorf("%q: %d %q", req, res.StatusCode, body)}if time.Since(start) > time.Second {@@ -74,10 +81,98 @@ func TestEgressEnvOnlyUnderFarm(t *testing.T) {}egressPort.Store(4321)t.Cleanup(func() { egressPort.Store(0) })- env := strings.Join(commandEnv(cfg, map[string]string{"HTTPS_PROXY": "http://elsewhere"}), "\n")+ env := strings.Join(commandEnv(cfg, map[string]string{"HTTPS_PROXY": "http://elsewhere"}), "\n") + "\n"for _, want := range []string{"HTTPS_PROXY=http://127.0.0.1:4321", "https_proxy=http://127.0.0.1:4321", "NO_PROXY=localhost,127.0.0.1,::1", "npm_config_https_proxy=http://127.0.0.1:4321"} {if !strings.Contains(env, want+"\n") {t.Errorf("farm env lacks %s", want)}}}++func TestFarmRefusesToStartWithoutNamespace(t *testing.T) {+ old := unshareNet+ unshareNet = func() error { return syscall.EPERM }+ t.Cleanup(func() { unshareNet = old })+ err := startEgress("farm")+ if err == nil || !strings.Contains(err.Error(), "cannot keep the session offline") {+ t.Fatalf("startEgress with no namespace = %v, want a refusal", err)+ }+ if egressPort.Load() != 0 || egressNS >= 0 {+ t.Fatal("a refused start left the proxy or namespace set")+ }+}++func TestDropHop(t *testing.T) {+ h := http.Header{}+ for _, k := range []string{"Connection", "Keep-Alive", "Te", "Trailer", "Transfer-Encoding", "Upgrade", "Proxy-Connection", "X-Custom", "Accept"} {+ h.Set(k, "x")+ }+ h.Set("Connection", "close, X-Custom")+ dropHop(h)+ if len(h) != 1 || h.Get("Accept") != "x" {+ t.Fatalf("after dropHop: %v", h)+ }+}++// The shims, run with fake curl/wget and the real git behind them.+func TestShims(t *testing.T) {+ gitBin, err := exec.LookPath("git")+ if err != nil {+ t.Skip("no git")+ }+ dir, fake, repo := t.TempDir(), t.TempDir(), t.TempDir()+ for _, name := range []string{"curl", "wget"} {+ os.WriteFile(filepath.Join(fake, name), []byte("#!/bin/sh\necho REAL "+name+" \"$@\"\n"), 0o755)+ }+ os.Symlink(gitBin, filepath.Join(fake, "git"))+ if err := writeShims(dir); err != nil {+ t.Fatal(err)+ }+ env := append(os.Environ(), "PATH="+dir+":"+fake+":/usr/bin:/bin", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_TERMINAL_PROMPT=0")+ run := func(args ...string) (string, int) {+ cmd := exec.Command("/bin/sh", append([]string{"-c", `exec "$@"`, "sh"}, args...)...) // found on env's PATH+ cmd.Env, cmd.Dir = env, repo+ out, err := cmd.CombinedOutput()+ code := 0+ var ee *exec.ExitError+ if errors.As(err, &ee) {+ code = ee.ExitCode()+ }+ return string(out), code+ }+ run("git", "init", "-q", "-b", "main")+ run("git", "-c", "user.email=a@b", "-c", "user.name=a", "commit", "-q", "--allow-empty", "-m", "x")+ run("git", "remote", "add", "origin", "https://github.com/octocat/Hello-World.git")+ const line = "is not reachable: this session is offline, so mock the service"+ for _, c := range []struct {+ args []string+ refused string+ code int+ }{+ {[]string{"curl", "-sS", "https://api.github.com/zen"}, "api.github.com", 7},+ {[]string{"curl", "-H", "Referer: https://x.org", "http://127.0.0.1:8080/"}, "", 0},+ {[]string{"curl", "https://registry.npmjs.org/left-pad"}, "", 0},+ {[]string{"curl", "--url=https://[email protected]:8443/x"}, "example.com", 7},+ {[]string{"wget", "-q", "https://raw.githubusercontent.com/a/b"}, "raw.githubusercontent.com", 4},+ {[]string{"wget", "http://localhost:3000/"}, "", 0},+ {[]string{"git", "clone", "--depth", "1", "https://github.com/octocat/Hello-World.git"}, "github.com", 128},+ {[]string{"git", "clone", "[email protected]:octocat/Hello-World.git"}, "github.com", 128},+ {[]string{"git", "-C", repo, "fetch"}, "github.com", 128},+ {[]string{"git", "pull", "origin", "main:main"}, "github.com", 128},+ {[]string{"git", "push"}, "github.com", 128},+ {[]string{"git", "ls-remote", "https://gitlab.com/a/b"}, "gitlab.com", 128},+ {[]string{"git", "submodule", "add", "https://github.com/a/b"}, "github.com", 128},+ {[]string{"git", "status", "--short"}, "", 0},+ {[]string{"git", "log", "--oneline", "-1"}, "", 0},+ {[]string{"git", "clone", "-q", repo, filepath.Join(t.TempDir(), "copy")}, "", 0},+ } {+ out, code := run(c.args...)+ if c.refused != "" {+ if code != c.code || !strings.Contains(out, "omnirush: "+c.refused+" "+line) {+ t.Errorf("%v: exit %d %q, want a refusal for %s", c.args, code, out, c.refused)+ }+ } else if code != 0 || strings.Contains(out, line) {+ t.Errorf("%v: exit %d %q, want the real program", c.args, code, out)+ }+ }+}diff --git a/apps/desktop/box/go/cmd/boxd/main.go b/apps/desktop/box/go/cmd/boxd/main.goindex cf1527bc..10065e5d 100644--- a/apps/desktop/box/go/cmd/boxd/main.go+++ b/apps/desktop/box/go/cmd/boxd/main.go@@ -557,6 +557,9 @@ func commandEnv(cfg config, extra map[string]string) []string {if cfg.pathPre != "" {set("PATH", cfg.pathPre+":"+env["PATH"])}+ if egressPort.Load() > 0 {+ set("PATH", offlineBin+":"+env["PATH"])+ }out := make([]string, 0, len(order))for _, k := range order {if v, ok := env[k]; ok {diff --git a/apps/server/src/box/backends/index.ts b/apps/server/src/box/backends/index.tsindex 3360cfd7..876430c5 100644--- a/apps/server/src/box/backends/index.ts+++ b/apps/server/src/box/backends/index.ts@@ -27,7 +27,7 @@ import path from "node:path";import { runCommand, type RunCommand } from "../run.js";import { CACHE_FAIL_MS, CACHE_OK_MS, candidates, isWsl, probe as probeContainer, probeWsl, wslLauncher, type BackendAlternative, type DetectOptions, type RuntimeFailure, type RuntimeInfo, type RuntimeResult, type RuntimeTried } from "../runtime.js";import { appleDriver, probeApple } from "./apple.js";-import { bwrapDriver, probeBwrap } from "./bwrap.js";+import { boxEgress, bwrapDriver, probeBwrap } from "./bwrap.js";import { containerDriver } from "./container.js";import { limaDriver, probeLima } from "./lima.js";import type { BoxDriver } from "./types.js";@@ -58,6 +58,13 @@ export const OPT_IN: Partial<Record<NodeJS.Platform, string[]>> = { darwin: ["ap*/export const REQUIRED_FIRST: Partial<Record<NodeJS.Platform, string[]>> = { darwin: ["lima"] };+/**+ * Farm runs (bwrap.ts boxEgress): only the backends whose boxd gets BOXD_EGRESS and runs where it+ * can make the commands' network (boxrun's boxes; wslc when its container allows it), in this+ * order: the WSL distro, which always can, before wslc. boxd refuses to start where it cannot. CLI: the same.+ */+export const EGRESS_BACKENDS = ["bwrap", "lima", "wsl", "wslc"];+/** What the backend setting takes (and what uploads record as sandbox.backend). */export const BACKENDS = ["bwrap", "lima", "apple", "wslc", "wsl", "orbstack", "colima", "docker-desktop", "rancher", "docker", "podman", "wsl-engine"] as const;export type BackendId = (typeof BACKENDS)[number];@@ -231,7 +238,8 @@ export async function detectBackend({ boxHome, env = process.env, platform = proconst named = runtimeBackend(legacyRuntime, platform);if (named && wanted === "auto") { wanted = normalizeBackend(named); legacyRuntime = ""; }const allowList = Array.isArray(allow) ? allow.map(normalizeBackend).filter((id): id is BackendId | "auto" | "native" => Boolean(id)) : null;- const key = JSON.stringify([2, platform, wanted, allowList, ...(preferShadows ? ["shadows"] : []), ...(required ? ["required"] : []), legacyRuntime, env.DOCKER_HOST || "", env.PATH || env.Path || "", env.OMNIRUSH_BOX_BWRAP || ""]);+ const farm = Boolean(boxEgress(env));+ const key = JSON.stringify([2, platform, wanted, allowList, ...(preferShadows ? ["shadows"] : []), ...(required ? ["required"] : []), ...(farm ? ["farm"] : []), legacyRuntime, env.DOCKER_HOST || "", env.PATH || env.Path || "", env.OMNIRUSH_BOX_BWRAP || ""]);if (boxHome && !fresh && !all) {const cached = readCache(boxHome, now, key);if (cached) return { ...cached, cached: true };@@ -260,6 +268,11 @@ export async function detectBackend({ boxHome, env = process.env, platform = proorder = order.filter((id) => allowList.some((allowed) => allowed === id));why += `; the server allows ${allowList.join(", ")}`;}+ if (farm) {+ for (const id of order) if (!EGRESS_BACKENDS.includes(id)) skipped.push({ backend: id, name: id, ok: false, reason: "cannot keep a farm session offline" });+ order = EGRESS_BACKENDS.filter((id) => order.includes(id));+ why += "; farm mode: the backends that keep the session offline";+ }const limit = timeoutMs ? { timeoutMs } : {};let containers: Probed[] | null = null;const containerList = async () => (containers ??= await probeContainers({ platform, env, home, exists, run, wsl, timeoutMs }));diff --git a/apps/server/src/box/backends/lima.ts b/apps/server/src/box/backends/lima.tsindex f7f7acbe..b5075cf1 100644--- a/apps/server/src/box/backends/lima.ts+++ b/apps/server/src/box/backends/lima.ts@@ -48,7 +48,7 @@ import { YOUNG_IMAGE_MS, removableImage, removeTree, staleEntries } from "../retimport { runCommand, type RunCommand, type RunOptions, type RunResult } from "../run.js";import type { RuntimeResult } from "../runtime.js";import { macosMajor } from "./apple.js";-import { IDLE_MINUTES, newMeta, upArgs, type BoxMeta } from "./bwrap.js";+import { IDLE_MINUTES, boxEgress, newMeta, upArgs, type BoxMeta } from "./bwrap.js";import { boxshExec, num, parseOut, str } from "./shared.js";import type { BoxDriver, ListedBox, OpenContext, Opened, PresentImage, Removed, SpawnLike } from "./types.js";import { download, type DownloadOptions } from "./wsl.js";@@ -1135,7 +1135,7 @@ async function openWithLease(ctx: OpenContext & LimaOpenExtras, runtime: LimaRunconst args = upArgs({box: boxPath(key), store: STORE, image: meta.image, boxd: `${runtime.helpers}/boxd`, portFile: path.join(runFolder, "boxd.port"),root, croot, runFolder, shims, pkglog, token: meta.token, idleMinutes: idle, listen: `127.0.0.1:${port}`, platform: "darwin",- shadows, shadowStore: shadows ? `${SHADOW_STORES}/${key}` : null,+ shadows, shadowStore: shadows ? `${SHADOW_STORES}/${key}` : null, egress: boxEgress(env),});releaseAllOnExit();let kept = await startKeeper(runtime, args, { env, ...(spawnImpl ? { spawnImpl } : {}) });diff --git a/apps/server/src/box/box-backends.test.ts b/apps/server/src/box/box-backends.test.tsindex 85fe2666..85785d4c 100644--- a/apps/server/src/box/box-backends.test.ts+++ b/apps/server/src/box/box-backends.test.ts@@ -95,6 +95,24 @@ function linuxRun(bwrapAnswer: unknown, { podman = true }: { podman?: boolean }}describe("box backends: Linux", () => {+ test("farm runs: only backends that keep the box offline; Podman/Docker are skipped, never a silent fallback", async () => {+ const home = tmp();+ const env = { PATH: "/usr/bin", OMNIRUSH_BOX_BIN_DIR: helperBin(), OMNIRUSH_FARM: "1" };+ const farm = await detectBackend({ boxHome: home, platform: "linux", home, env, exists: set(boxrunPath({ env }), "/usr/bin/podman"), run: linuxRun(BWRAP_AA).run, fresh: true, all: true, wsl: false });+ expect(farm.ok).toBe(false);+ expect(farm.alternatives?.find((a) => a.backend === "podman")?.reason).toBe("cannot keep a farm session offline");+ const asked = await detectBackend({ boxHome: home, platform: "linux", home, env, exists: set(boxrunPath({ env }), "/usr/bin/podman"), run: linuxRun(BWRAP_OK).run, fresh: true, asked: "podman", wsl: false });+ expect(asked.ok).toBe(false);+ const ok = await detectBackend({ boxHome: home, platform: "linux", home, env, exists: set(boxrunPath({ env }), "/usr/bin/podman"), run: linuxRun(BWRAP_OK).run, fresh: true, wsl: false });+ expect(ok).toMatchObject({ ok: true, backend: "bwrap" });+ if (ok.ok) expect(ok.why).toMatch(/farm mode/);+ // boxsh's `wslc exec` fallback runs outside boxd's network: off in farm runs, kept otherwise.+ const runtime = { name: "wslc", backend: "wslc", bin: "wslc.exe" };+ const base = { key: "k", name: "omnirush-box-k", root: home, croot: home, runtime, home, runFolder: home, run: linuxRun(BWRAP_OK).run, log: () => {}, platform: "win32" as const };+ expect(new Box({ ...base, env: {} }).execFallback()).toBe(true);+ expect(new Box({ ...base, env: { OMNIRUSH_FARM: "1" } }).execFallback()).toBe(false);+ });+test("bubblewrap first when its probe starts a namespace", async () => {const home = tmp();const env = { PATH: "/usr/bin", OMNIRUSH_BOX_BIN_DIR: helperBin() };diff --git a/apps/server/src/box/box.ts b/apps/server/src/box/box.tsindex a3d9184e..6d8ac4c5 100644--- a/apps/server/src/box/box.ts+++ b/apps/server/src/box/box.ts@@ -35,6 +35,7 @@ import * as client from "./client.js";import type { BoxEndpoint, BoxStat } from "./client.js";import { DEPS_MAX_BYTES, FILE_MAX_BYTES, HOME_IN_BOX, RECORD_SCHEMA, RUN_DIR, SHIMS_DIR, TAR_MAX_BYTES, boxHome, boxKey, containerName, containerRoot, firstLine, readJson, readRecord, recordFile, runDir, writeJson, type BoxInstallLog, type BoxLog, type BoxRecord, type BoxRuntime } from "./common.js";import { driverFor } from "./backends/index.js";+import { boxEgress } from "./backends/bwrap.js";import type { ListedBox, SpawnLike } from "./backends/types.js";import { detectStack, imageFor, type BoxImage, type ImagePins } from "./images.js";import { runCommand, type RunCommand, type RunOptions } from "./run.js";@@ -251,7 +252,7 @@ export async function openBox({ root, runtime, env = process.env, platform = proif (!identity) await new Promise((resolve) => setTimeout(resolve, 50));}}- if (!identity) return box.fail("the sandbox helper did not answer", onState);+ if (!identity) return box.fail(`the sandbox helper did not answer${boxEgress(env) ? " (farm mode: it does not start where the box cannot be kept offline)" : ""}`, onState);box.identity = identity;if (shims) await box.installShims().catch((error) => log("warn", "box wrappers not installed", { error: String(error?.message || error) }));else if (pkglog) {@@ -414,12 +415,17 @@ export class Box {this.imageId = imageId;}+ execFallback(): boolean {+ return Boolean(driverFor(this.runtime).execFallback) && !boxEgress(this.env);+ }+/** The record boxsh reads (boxes/<key>.json). */writeRecord(): void {- const fallback = driverFor(this.runtime).execFallback;+ const fallback = this.execFallback();const record: BoxRecord = {v: 1, key: this.key, root: this.root, croot: this.croot, container: this.name, backend: this.runtime.backend ?? this.runtime.name ?? "",- // boxsh's fallback when boxd does not answer: `<runtime> exec` (container engines and wslc only).+ // boxsh's fallback when boxd does not answer: `<runtime> exec` (container engines and wslc only; never+ // in farm runs, where it would run the command outside boxd's offline network).runtime: fallback ? this.runtime.bin ?? "" : "", runtime_args: fallback ? this.runtime.prefix ?? [] : [],host: this.endpoint?.host ?? "127.0.0.1", port: this.endpoint?.port ?? 0, token: this.endpoint?.token ?? "",state: this.state, error: this.error ?? "", uid: this.uid ?? 0, gid: this.gid ?? 0, home: HOME_IN_BOX, shell: "/bin/bash",diff --git a/apps/server/src/box/plugin-lib.ts b/apps/server/src/box/plugin-lib.tsindex 3ac89e16..94cf2325 100644--- a/apps/server/src/box/plugin-lib.ts+++ b/apps/server/src/box/plugin-lib.ts@@ -78,6 +78,9 @@ export function toolPaths(tool: string, args: Record<string, unknown> = {}): str}// `shadows`: the record's shadows_note (macOS/Windows hosts: the box's own node_modules, .venv, ...), one more line.+/** The one line a farm run's system prompt gets (its box is offline: boxd egress.go). CLI: the same. */+export const OFFLINE_NOTE = "This session is offline: the shell cannot reach the internet, except package installs (npm/pnpm/yarn, pip/uv, cargo, go, composer). Mock external services and APIs instead of calling them.";+export const BOX_NOTE = (root: string, uid = 0, croot = root, shadows: unknown = null): string => [`Sandbox: shell commands run in a Linux (Debian) container, ${uid === 0 ? "as root" : "as a user with passwordless sudo"}, with HOME=/root.`,croot && croot !== rootdiff --git a/apps/server/src/opencode-plugins/omnirush-box-next.test.ts b/apps/server/src/opencode-plugins/omnirush-box-next.test.tsindex a96588f0..16ce63a6 100644--- a/apps/server/src/opencode-plugins/omnirush-box-next.test.ts+++ b/apps/server/src/opencode-plugins/omnirush-box-next.test.ts@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";import path from "node:path";import { BOX_HEADER } from "../model-modes/model-modes.mjs";-import { keyOf } from "../box/plugin-lib.js";+import { BOX_NOTE, OFFLINE_NOTE, keyOf } from "../box/plugin-lib.js";import plugin from "./omnirush-box-next.js";type Hook = (event: any) => Promise<void>;@@ -66,6 +66,30 @@ test("a box chat's shell calls carry its box key and chat, its requests say box,await expect(hooks.get("tool:execute.before")!({ tool: "read", id: "call_2", sessionID: "ses_a", input: { filePath: "/etc/hostname" } })).rejects.toThrow(/outside the project folder/);});+test("farm runs: the prompt gets the offline line only (no box note); other runs never get it", async () => {+ const { root } = project(true);+ const hooks = await engine(root);+ const saved = process.env.OMNIRUSH_FARM;+ try {+ process.env.OMNIRUSH_FARM = "1";+ const farm = { sessionID: "ses_f", system: ["Platform: darwin"] as unknown[] };+ await hooks.get("context")!(farm);+ expect(farm.system).toEqual(["Platform: linux", { type: "text", text: OFFLINE_NOTE }]);+ expect(OFFLINE_NOTE).toBe("This session is offline: the shell cannot reach the internet, except package installs (npm/pnpm/yarn, pip/uv, cargo, go, composer). Mock external services and APIs instead of calling them.");+ for (const off of [undefined, "0"]) {+ if (off === undefined) delete process.env.OMNIRUSH_FARM;+ else process.env.OMNIRUSH_FARM = off;+ const normal = { sessionID: "ses_n", system: ["Platform: darwin"] as unknown[] };+ await hooks.get("context")!(normal);+ expect(normal.system).toEqual(["Platform: linux", { type: "text", text: BOX_NOTE(root, 0, root, undefined) }]);+ expect(JSON.stringify(normal.system)).not.toContain("offline");+ }+ } finally {+ if (saved === undefined) delete process.env.OMNIRUSH_FARM;+ else process.env.OMNIRUSH_FARM = saved;+ }+});+test("a project whose box is off is left alone: no box key, no box header, no note", async () => {const { root } = project(false);const hooks = await engine(root);diff --git a/apps/server/src/opencode-plugins/omnirush-box.ts b/apps/server/src/opencode-plugins/omnirush-box.tsindex 8cd0393d..4fbb80cc 100644--- a/apps/server/src/opencode-plugins/omnirush-box.ts+++ b/apps/server/src/opencode-plugins/omnirush-box.ts@@ -24,7 +24,7 @@import path from "node:path";import { BOX_HEADER } from "../model-modes/model-modes.mjs";-import { BOX_NOTE, desktopProjects, engineDirs, FILE_TOOLS, keyOf, record, toolPaths, within } from "../box/plugin-lib.js";+import { BOX_NOTE, OFFLINE_NOTE, desktopProjects, engineDirs, FILE_TOOLS, keyOf, record, toolPaths, within } from "../box/plugin-lib.js";/** The engine client's one call used here: a chat's parent (a sub-agent's chat has one). */type SessionReader = { session: { get: (options: { path: { id: string } }) => Promise<{ data?: { parentID?: string } | null } | undefined> } };@@ -89,8 +89,12 @@ export const OmniRushBox = async ({ directory, client }: { directory?: string; cconst line = output.system[i];if (typeof line === "string") output.system[i] = line.replace(/^(\s*Platform:\s*)(darwin|win32|linux)\s*$/m, "$1linux");}- // Stock mode (stock-mode.mjs, the CLI's opencode-box-plugin.js): the system prompt stays stock apart from its environment lines.- if (process.env.OMNIRUSH_FARM === "1") return;+ // Stock mode (stock-mode.mjs, the CLI's opencode-box-plugin.js): the system prompt stays stock apart from its environment lines,+ // and the one line that says the box is offline (farm runs' boxes are: boxd egress.go).+ if (process.env.OMNIRUSH_FARM === "1") {+ output.system.push(OFFLINE_NOTE);+ return;+ }output.system.push(BOX_NOTE(root, Number(rec.uid) || 0, typeof rec.croot === "string" ? rec.croot : root, rec.shadows_note));},};