A desktop coding agent with free access to frontier models.
TypeScript
feat: sandbox install log, wsl engines and cleanup from the cli
ogsamrat3afd1a5ffd76
diff --git a/apps/desktop/box/go/cmd/boxd/main.go b/apps/desktop/box/go/cmd/boxd/main.goindex cd97936a..542693af 100644--- a/apps/desktop/box/go/cmd/boxd/main.go+++ b/apps/desktop/box/go/cmd/boxd/main.go@@ -246,7 +246,7 @@ func prepareUser(cfg config, first bool) {})}if _, err := os.Stat("/etc/sudoers.d"); err == nil {- rule := "omnirush ALL=(ALL) NOPASSWD:ALL\nDefaults:omnirush !secure_path\nDefaults:omnirush !requiretty\nDefaults:omnirush env_keep += \"PATH PYTHONPATH NODE_OPTIONS HOME OMNIRUSH_HOOKS OMNIRUSH_LEDGER OMNIRUSH_STATE_DIR OMNIRUSH_TURN OMNIRUSH_CALL\"\n"+ rule := "omnirush ALL=(ALL) NOPASSWD:ALL\nDefaults:omnirush !secure_path\nDefaults:omnirush !requiretty\nDefaults:omnirush env_keep += \"PATH PYTHONPATH NODE_OPTIONS HOME OMNIRUSH_*\"\n"_ = os.WriteFile("/etc/sudoers.d/omnirush", []byte(rule), 0o440)}}diff --git a/apps/desktop/box/go/cmd/boxsh/main.go b/apps/desktop/box/go/cmd/boxsh/main.goindex 0e48c5e1..c5774730 100644--- a/apps/desktop/box/go/cmd/boxsh/main.go+++ b/apps/desktop/box/go/cmd/boxsh/main.go@@ -38,6 +38,8 @@ type Record struct {CRoot string `json:"croot"`Container string `json:"container"`Runtime string `json:"runtime"`+ // RuntimeArgs come before the runtime's own (`-e docker` through wsl.exe).+ RuntimeArgs []string `json:"runtime_args"`Host string `json:"host"`Port int `json:"port"`Token string `json:"token"`@@ -226,6 +228,15 @@ func mapPath(p string, rec *Record) string {return p}+// windowsToBox: C:\x\y -> /c/x/y (how the launcher mounts a Windows folder in the box).+func windowsToBox(p string) string {+ if len(p) >= 2 && p[1] == ':' {+ rest := strings.ReplaceAll(p[2:], `\`, "/")+ return "/" + strings.ToLower(p[:1]) + "/" + strings.TrimPrefix(rest, "/")+ }+ return strings.ReplaceAll(p, `\`, "/")+}+// unmapPath maps a path inside the box back to the host (Windows cygpath).func unmapPath(p string, rec *Record) string {croot := strings.TrimSuffix(rec.CRoot, "/")@@ -255,7 +266,7 @@ var passExact = map[string]bool{"TERM": true, "COLORTERM": true, "NO_COLOR": true, "FORCE_COLOR": true, "CLICOLOR": true, "CLICOLOR_FORCE": true,"TZ": true, "CI": true, "HTTP_PROXY": true, "HTTPS_PROXY": true, "NO_PROXY": true, "http_proxy": true,"https_proxy": true, "no_proxy": true, "OMNIRUSH_TURN": true, "OMNIRUSH_CALL": true, "OMNIRUSH_SESSION": true,- "OMNIRUSH_LEDGER_OFF": true, "PAGER": true, "GIT_PAGER": true, "GIT_TERMINAL_PROMPT": true, "DEBIAN_FRONTEND": true,+ "OMNIRUSH_LEDGER_OFF": true, "OMNIRUSH_PKGLOG_DIR": true, "PAGER": true, "GIT_PAGER": true, "GIT_TERMINAL_PROMPT": true, "DEBIAN_FRONTEND": true,}// forwardEnv keeps only what describes the terminal and the turn: the host's@@ -275,6 +286,9 @@ func forwardEnv(environ []string) map[string]string {}k, v := kv[:i], kv[i+1:]if passExact[k] || extra[k] {+ if k == "OMNIRUSH_PKGLOG_DIR" && runtime.GOOS == "windows" {+ v = windowsToBox(v)+ }out[k] = v}}@@ -407,7 +421,7 @@ func runtimeExec(rec *Record, req proto.Request) int {if bin == "" {bin = "docker"}- args := []string{"exec", "-i", "-w", req.Cwd}+ args := append(append([]string(nil), rec.RuntimeArgs...), "exec", "-i", "-w", req.Cwd)if rec.UID != 0 {args = append(args, "-u", fmt.Sprintf("%d:%d", rec.UID, rec.GID))}@@ -452,7 +466,7 @@ func native(args []string) {fmt.Fprintf(os.Stderr, "omnirush: could not run %s: %v\n", shell, err)os.Exit(127)}- cmd := exec.Command(shell, args...)+ cmd := exec.Command(shell, windowsArgs(shell, args)...)cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderrif err := cmd.Run(); err != nil {var ee *exec.ExitError@@ -465,17 +479,28 @@ func native(args []string) {os.Exit(0)}+// windowsArgs: cmd.exe takes /c, the others (Git Bash, pwsh, powershell) take -c.+func windowsArgs(shell string, args []string) []string {+ base := shell[strings.LastIndexAny(shell, `\/`)+1:]+ if strings.EqualFold(base, "cmd.exe") || strings.EqualFold(base, "cmd") {+ out := append([]string(nil), args...)+ for i, a := range out {+ if a == "-c" || a == "-lc" {+ out[i] = "/c"+ }+ }+ return out+ }+ return args+}+func realShell() string {if v := os.Getenv("OMNIRUSH_BOX_REAL_SHELL"); v != "" {return v}self, _ := os.Executable()selfDir := filepath.Dir(self)- names := []string{"bash", "sh"}- if runtime.GOOS == "windows" {- names = []string{"bash.exe", "pwsh.exe", "powershell.exe", "cmd.exe"}- }- for _, name := range names {+ find := func(name string) string {for _, dir := range filepath.SplitList(os.Getenv("PATH")) {if dir == "" || filepath.Clean(dir) == filepath.Clean(selfDir) {continue@@ -485,10 +510,31 @@ func realShell() string {return cand}}+ return ""}- if runtime.GOOS == "windows" {- return "cmd.exe"+ if runtime.GOOS != "windows" {+ for _, name := range []string{"bash", "sh"} {+ if p := find(name); p != "" {+ return p+ }+ }+ return "/bin/sh"+ }+ // The engine's own order on Windows: Git Bash (next to git.exe), then+ // PowerShell, then cmd. Never System32\bash.exe: that is the WSL launcher.+ if git := find("git.exe"); git != "" {+ gitBash := filepath.Join(filepath.Dir(git), "..", "bin", "bash.exe")+ if st, err := os.Stat(gitBash); err == nil && !st.IsDir() {+ return filepath.Clean(gitBash)+ }+ }+ for _, name := range []string{"pwsh.exe", "powershell.exe"} {+ if p := find(name); p != "" {+ return p+ }}- return "/bin/sh"+ if sys := os.Getenv("ComSpec"); sys != "" {+ return sys+ }+ return "cmd.exe"}-diff --git a/apps/desktop/box/go/cmd/boxsh/main_test.go b/apps/desktop/box/go/cmd/boxsh/main_test.goindex 7bb02c3d..6ca6ec37 100644--- a/apps/desktop/box/go/cmd/boxsh/main_test.go+++ b/apps/desktop/box/go/cmd/boxsh/main_test.go@@ -57,3 +57,18 @@ func TestForwardEnv(t *testing.T) {t.Fatalf("%v", got)}}++func TestWindowsArgs(t *testing.T) {+ if got := windowsArgs(`C:\Windows\System32\cmd.exe`, []string{"-c", "dir"}); !reflect.DeepEqual(got, []string{"/c", "dir"}) {+ t.Fatal(got)+ }+ if got := windowsArgs(`C:\Program Files\Git\bin\bash.exe`, []string{"-c", "ls"}); !reflect.DeepEqual(got, []string{"-c", "ls"}) {+ t.Fatal(got)+ }+}++func TestWindowsToBox(t *testing.T) {+ if got := windowsToBox(`C:\Users\Sam\.omnirush\pkglog\raw\12-ab`); got != "/c/Users/Sam/.omnirush/pkglog/raw/12-ab" {+ t.Fatal(got)+ }+}diff --git a/apps/server/src/box/box.test.ts b/apps/server/src/box/box.test.tsindex 9756296c..058baace 100644--- a/apps/server/src/box/box.test.ts+++ b/apps/server/src/box/box.test.ts@@ -3,12 +3,12 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";-import { boxKey, containerName, containerRoot, createArgs, credentialPath, filterChanges, helperPath, installShell, parseDiff, parseSize, setToolsRoot, singleFileTar } from "./box.js";+import { boxKey, containerName, containerRoot, createArgs, credentialPath, filterChanges, helperPath, installShell, parseDiff, parseSize, rt, setToolsRoot, singleFileTar, wslPath } from "./box.js";import { readBoxSettings } from "./desktop.js";import { detectStack, imageFor } from "./images.js";-import { engineConfig, mapToBox, rememberServerDefault, resolveMode, serverDefault } from "./launch.js";+import { engineConfig, gcInBackground, mapToBox, rememberServerDefault, resolveMode, serverDefault } from "./launch.js";import { DESKTOP_PROJECTS_FILE } from "./plugin-lib.js";-import { candidates, detectRuntime, explainFailure, probe, type RunCommand } from "./runtime.js";+import { candidates, detectRuntime, explainFailure, probe, probeWsl, wslLauncher, type RunCommand } from "./runtime.js";import { BoxService, type BoxWorkspace } from "./service.js";import { OmniRushBox } from "../opencode-plugins/omnirush-box.js";@@ -106,6 +106,11 @@ describe("box core", () => {expect(kept.map((entry) => entry.path)).toEqual(["/usr", "/usr/local/bin/tool", "/root/.cache/ms-playwright/chromium"]);expect(credentialPath("/home/u/.aws/credentials")).toBe(true);expect(credentialPath("/usr/lib/x.so")).toBe(false);+ // Package data, not a key: certifi's bundle has to survive a rebuild (`import requests`).+ expect(credentialPath("/root/.local/lib/python3.11/site-packages/certifi/cacert.pem")).toBe(false);+ expect(credentialPath("/root/project/node_modules/x/test/key.pem")).toBe(false);+ expect(credentialPath("/root/.ssh/id_ed25519")).toBe(true);+ expect(credentialPath("/root/server.key")).toBe(true);});test("tar header and size parsing", () => {@@ -259,3 +264,86 @@ describe("box service", () => {expect(await boxes.status(workspace)).toMatchObject({ on: false, state: "off" });});});++describe("box on Windows: a WSL engine (detected, never installed)", () => {+ const WSL = "C:\\Windows\\System32\\wsl.exe";+ const winEnv = { Path: "C:\\Windows\\System32", SystemRoot: "C:\\Windows", ProgramFiles: "C:\\Program Files", LOCALAPPDATA: "C:\\Users\\sam\\AppData\\Local" };+ const has = (...files: string[]) => (file: string) => files.includes(file);++ test("Docker Desktop is used when it is there (the WSL engine is not even asked)", async () => {+ const asked: string[] = [];+ const run: RunCommand = async (bin, args) => { asked.push([bin, ...args].join(" ")); return { code: 0, stdout: JSON.stringify({ ServerVersion: "27.3.1", OSType: "linux", Architecture: "x86_64", OperatingSystem: "Docker Desktop" }), stderr: "" }; };+ const found = await detectRuntime({ platform: "win32", home: "C:\\Users\\sam", env: winEnv, exists: has("C:\\Program Files\\Docker\\Docker\\resources\\bin\\docker.exe", WSL), run, fresh: true });+ expect(found).toMatchObject({ ok: true, flavor: "desktop" });+ expect(asked.some((line) => line.startsWith(WSL))).toBe(false);+ });++ test("without Docker Desktop: Docker in the default WSL distro, through wsl.exe", async () => {+ expect(wslLauncher({ env: winEnv, exists: has(WSL) })).toBe(WSL);+ expect(wslLauncher({ env: winEnv, exists: () => false })).toBeNull();+ const run: RunCommand = async (bin, args) => (bin === WSL && args.join(" ") === "-e docker info --format {{json .}}"+ ? { code: 0, stdout: JSON.stringify({ ServerVersion: "28.1.1", OSType: "linux", Architecture: "x86_64", OperatingSystem: "Ubuntu 24.04.1 LTS", SecurityOptions: [] }), stderr: "" }+ : { code: -1, stdout: "", stderr: "", error: "ENOENT" });+ const found = await detectRuntime({ platform: "win32", home: "C:\\Users\\sam", env: winEnv, exists: has(WSL), run, fresh: true });+ expect(found).toMatchObject({ ok: true, bin: WSL, prefix: ["-e", "docker"], flavor: "wsl", wsl: true, vm: true });+ });++ test("no distribution, or no engine in it, is a one-line reason; OMNIRUSH_BOX_WSL=0 never asks; Podman works too", async () => {+ const noDistro = await probeWsl(WSL, { run: async () => ({ code: 1, stdout: "", stderr: "Windows Subsystem for Linux has no installed distributions.\u0000" }) });+ expect(noDistro.ok).toBe(false);+ if (!noDistro.ok) expect(noDistro.reason).toContain("no Linux distribution");+ const noEngine = await probeWsl(WSL, { run: async () => ({ code: 127, stdout: "", stderr: "/bin/bash: line 1: docker: command not found" }) });+ if (!noEngine.ok) expect(noEngine.reason).toContain("no Docker or Podman engine");+ expect(noEngine.ok).toBe(false);+ const off = await detectRuntime({ platform: "win32", home: "C:\\Users\\sam", env: { ...winEnv, OMNIRUSH_BOX_WSL: "0" }, exists: has(WSL), run: async () => { throw new Error("not asked"); }, fresh: true });+ expect(off.ok).toBe(false);+ const podman = await probeWsl(WSL, { run: async (_bin, args) => (args[1] === "podman" ? { code: 0, stdout: JSON.stringify({ host: { arch: "amd64", security: { rootless: true } }, version: { Version: "4.9.3" } }), stderr: "" } : { code: 127, stdout: "", stderr: "docker: not found" }) });+ expect(podman).toMatchObject({ ok: true, name: "podman", prefix: ["-e", "podman"], rootless: true });+ });++ test("Windows folders mount through /mnt/<drive>; the prefix goes on every call", async () => {+ expect(wslPath("C:\\Users\\Sam\\proj")).toBe("/mnt/c/Users/Sam/proj");+ const args = createArgs({ name: "n", key: "k", root: "C:\\Users\\Sam\\proj", croot: "/c/Users/Sam/proj", image: "img", runtime: { name: "docker", bin: "wsl.exe", wsl: true, vm: true, prefix: ["-e", "docker"] }, run: "C:\\Users\\Sam\\.omnirush\\box\\projects\\k", shims: null, pkglog: { root: "C:\\Users\\Sam\\state\\pkglog", bin: "C:\\Users\\Sam\\state\\pkglog\\bin-1", py: "C:\\Users\\Sam\\state\\pkglog\\py-1" }, token: "t", user: { uid: 0, gid: 0 }, env: {}, platform: "win32" });+ expect(args).toContain("type=bind,source=/mnt/c/Users/Sam/proj,target=/c/Users/Sam/proj");+ expect(args).toContain("type=bind,source=/mnt/c/Users/Sam/.omnirush/box/projects/k,target=/run/omnirush");+ expect(args).toContain("type=bind,source=/mnt/c/Users/Sam/state/pkglog,target=/c/Users/Sam/state/pkglog");+ const calls: string[][] = [];+ await rt({ name: "docker", bin: WSL, prefix: ["-e", "docker"] }, async (bin, a) => { calls.push([bin, ...a]); return { code: 0, stdout: "", stderr: "" }; })(["ps"]);+ expect(calls).toEqual([[WSL, "-e", "docker", "ps"]]);+ });+});++describe("box install log and upkeep", () => {+ test("a new box mounts the install log's folder at the same path", () => {+ const args = createArgs({ name: "n", key: "k", root: "/p", croot: "/p", image: "img", runtime: { name: "docker", bin: "docker", vm: false }, run: "/h/projects/k", shims: null, pkglog: { root: "/s/pkglog", bin: "/s/pkglog/bin-1", py: "/s/pkglog/py-1" }, token: "t", user: { uid: 0, gid: 0 }, env: {} });+ expect(args).toContain("type=bind,source=/s/pkglog,target=/s/pkglog");+ });++ test("the daily cleanup runs at most once a day, in the background", async () => {+ const home = await temp("gc");+ let runs = 0;+ const gc = async () => { runs += 1; return []; };+ expect(gcInBackground({ name: "docker", bin: "docker" }, home, { now: 1_000_000_000, gc })).not.toBeNull();+ expect(gcInBackground({ name: "docker", bin: "docker" }, home, { now: 1_000_000_000 + 3_600_000, gc })).toBeNull();+ expect(gcInBackground({ name: "docker", bin: "docker" }, home, { now: 1_000_000_000 + 25 * 3_600_000, gc })).not.toBeNull();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(runs).toBe(2);+ });++ test("the plugin points box calls at the box's install log folder and names the folder inside on Windows-like roots", async () => {+ const home = await temp("boxhome");+ const root = await temp("project");+ process.env.OMNIRUSH_BOX_HOME = home;+ const key = boxKey(root);+ await mkdir(join(home, "boxes"), { recursive: true });+ await writeFile(join(home, "boxes", `${key}.json`), JSON.stringify({ state: "ready", uid: 0, croot: "/c/proj" }));+ await writeFile(join(home, DESKTOP_PROJECTS_FILE), JSON.stringify({ keys: [key], pkglog_dir: "/state/pkglog/raw/1-box-ab" }));+ const hooks = await OmniRushBox({ directory: root });+ const env: Record<string, string> = {};+ await hooks["shell.env"]({ callID: "c1" }, { env });+ expect(env).toMatchObject({ OMNIRUSH_BOX_KEY: key, OMNIRUSH_PKGLOG_DIR: "/state/pkglog/raw/1-box-ab" });+ const system: string[] = [];+ await hooks["experimental.chat.system.transform"]({}, { system });+ expect(system[0]).toContain(`${root} is /c/proj inside the container`);+ });+});diff --git a/apps/server/src/box/box.ts b/apps/server/src/box/box.tsindex 26070b3a..8d343e56 100644--- a/apps/server/src/box/box.ts+++ b/apps/server/src/box/box.ts@@ -102,7 +102,7 @@ function readJson<T = Record<string, unknown>>(file: string): T | null {/** The record boxsh reads (boxes/<key>.json). */export type BoxRecord = {- v: 1; key: string; root: string; croot: string; container: string; runtime: string;+ v: 1; key: string; root: string; croot: string; container: string; runtime: string; runtime_args: string[];host: string; port: number; token: string; state: string; error: string; uid: number; gid: number;home: string; shell: string; path_prefix: string; env_file: string; updated: number; pid: number;};@@ -203,10 +203,24 @@ export function singleFileTar(name: string, data: Buffer, mode = 0o755): Buffer// --- the runtime CLI -------------------------------------------------------------export type BoxRuntime = Pick<RuntimeInfo, "name" | "bin"> & Partial<Pick<RuntimeInfo, "version" | "flavor" | "rootless" | "arch" | "vm">>;+export type BoxRuntime = Pick<RuntimeInfo, "name" | "bin"> & Partial<Pick<RuntimeInfo, "version" | "flavor" | "rootless" | "arch" | "vm" | "prefix" | "wsl">>;-function rt(runtime: BoxRuntime, run: RunCommand = runCommand) {- return (args: string[], opts: RunOptions = {}) => run(runtime.bin, args, { timeoutMs: 60_000, ...opts });+/** Runs the runtime's CLI (`wsl.exe -e docker ...` for a WSL engine). */+export function rt(runtime: BoxRuntime, run: RunCommand = runCommand) {+ const prefix = Array.isArray(runtime.prefix) ? runtime.prefix : [];+ return (args: string[], opts: RunOptions = {}) => run(runtime.bin, [...prefix, ...args], { timeoutMs: 60_000, ...opts });+}++/** A Windows path as a WSL engine mounts it: C:\x\y -> /mnt/c/x/y. */+export function wslPath(p: string): string {+ const match = /^([a-zA-Z]):[\\/]?(.*)$/.exec(String(p));+ if (!match) return String(p).replace(/\\/g, "/");+ return `/mnt/${match[1]!.toLowerCase()}/${match[2]!.replace(/\\/g, "/")}`.replace(/\/+$/, "");+}++/** Where the runtime finds a folder of this machine (a WSL engine sees Windows drives under /mnt). */+function source(runtime: BoxRuntime, p: string): string {+ return runtime.wsl ? wslPath(p) : p;}/** Whether `image` is present locally; its id and repo digest when it is. */@@ -235,7 +249,7 @@ export async function pullImage(runtime: BoxRuntime, image: string, { run = runCreturn { ok: false, error: said.slice(0, 300) };}-type ContainerInfo = { id: string; running: boolean; image: string; labels: Record<string, string>; env: string[] };+type ContainerInfo = { id: string; running: boolean; image: string; labels: Record<string, string>; env: string[]; mounts: string[] };async function inspectContainer(runtime: BoxRuntime, name: string, run: RunCommand): Promise<ContainerInfo | null> {const res = await rt(runtime, run)(["container", "inspect", name, "--format", "{{json .}}"], { timeoutMs: 20_000 });@@ -248,6 +262,7 @@ async function inspectContainer(runtime: BoxRuntime, name: string, run: RunCommaimage: String(info.Image || ""),labels: info.Config?.Labels ?? {},env: Array.isArray(info.Config?.Env) ? info.Config.Env : [],+ mounts: Array.isArray(info.Mounts) ? info.Mounts.map((mount: { Destination?: unknown }) => String(mount.Destination ?? "")) : [],};} catch {return null;@@ -293,13 +308,19 @@ export function commandUser(runtime: BoxRuntime, { platform = process.platform,* Nothing else of this machine goes in: no home folder, no credentials, no* docker socket.*/-export function createArgs({ name, key, root, croot, image, runtime, run: runFolder, shims, token, user, env = process.env }: { name: string; key: string; root: string; croot: string; image: string; runtime: BoxRuntime; run: string; shims: string | null; token: string; user: { uid: number; gid: number }; env?: Env; platform?: NodeJS.Platform }): string[] {+/** The install log (phase 1): its folder, the wrappers' folder and the pip hook's, all on this machine. */+export type BoxInstallLog = { root: string; bin: string; py: string };++export function createArgs({ name, key, root, croot, image, runtime, run: runFolder, shims, pkglog = null, token, user, env = process.env, platform = process.platform }: { name: string; key: string; root: string; croot: string; image: string; runtime: BoxRuntime; run: string; shims: string | null; pkglog?: BoxInstallLog | null; token: string; user: { uid: number; gid: number }; env?: Env; platform?: NodeJS.Platform }): string[] {return ["create", "--name", name, "--hostname", "omnirush-box", "--init","--label", `${LABEL}=1`, "--label", `${LABEL}.key=${key}`, "--label", `${LABEL}.root=${root}`, "--label", `${LABEL}.version=1`,- "--mount", `type=bind,source=${root},target=${croot}`,- "--mount", `type=bind,source=${runFolder},target=${RUN_DIR}`,- ...(shims ? ["--mount", `type=bind,source=${shims},target=${SHIMS_DIR}-src,readonly`] : []),+ "--mount", `type=bind,source=${source(runtime, root)},target=${croot}`,+ "--mount", `type=bind,source=${source(runtime, runFolder)},target=${RUN_DIR}`,+ ...(shims ? ["--mount", `type=bind,source=${source(runtime, shims)},target=${SHIMS_DIR}-src,readonly`] : []),+ // The install log's folder (phase 1: its wrappers, pip hook and the per-run folders the+ // wrappers note calls in), at the path the launcher reads it at.+ ...(pkglog ? ["--mount", `type=bind,source=${source(runtime, pkglog.root)},target=${containerRoot(pkglog.root, platform)}`] : []),"-p", `127.0.0.1::${BOX_PORT}`,"-e", `BOXD_TOKEN=${token}`, "-e", `BOXD_UID=${user.uid}`, "-e", `BOXD_GID=${user.gid}`,"-e", `BOXD_HOME=${HOME_IN_BOX}`, "-e", `BOXD_ROOT=${croot}`, "-e", `BOXD_ENV_FILE=${RUN_DIR}/env`,@@ -344,15 +365,18 @@ function within(child: string, parent: string): boolean {return child === parent || child.startsWith(parent.endsWith("/") ? parent : `${parent}/`);}+/** Package trees: their .pem/.key files are package data (certifi's cacert.pem), never a user's key. */+const PACKAGE_SEGMENT = /(?:^|\/)(?:site-packages|dist-packages|node_modules|gems|pkg\/mod|\.rustup|\.cargo|\.m2|\.gradle|\.npm|\.cache|\.local\/lib|\.local\/share|go|\.bun|\.pyenv|\.nvm|\.venv|venv)(?:\/|$)/;+/** A credential under a home folder (the box's own, or a user's). */export function credentialPath(entry: string): boolean {const home = /^(?:\/root|\/home\/[^/]+)\/(.*)$/.exec(entry);- if (!home) return CREDENTIAL_FILE.test(entry) && /^\/(?:root|home)\//.test(entry);+ if (!home) return false;const rel = home[1]!;const first = rel.split("/")[0]!;if (CREDENTIAL_NAMES.has(first)) return true;if (CREDENTIAL_SUBPATHS.some((prefix) => within(rel, prefix))) return true;- return CREDENTIAL_FILE.test(rel);+ return CREDENTIAL_FILE.test(rel) && !PACKAGE_SEGMENT.test(path.posix.dirname(rel));}export type DiffEntry = { kind: string; path: string };@@ -459,7 +483,7 @@ type OnState = (state: BoxState, error: string | null) => void;* same). Throws only for programming errors; a box that cannot start is a* Box with state "failed" and `error`.*/-export async function openBox({ root, runtime, env = process.env, platform = process.platform, home = boxHome(env), run = runCommand, log = () => {}, shims = null, pull = true, image: asked = null, onState = () => {} }: { root: string; runtime: BoxRuntime; env?: Env; platform?: NodeJS.Platform; home?: string; run?: RunCommand; log?: BoxLog; shims?: string | null; pull?: boolean; image?: BoxImage | null; onState?: OnState }): Promise<Box> {+export async function openBox({ root, runtime, env = process.env, platform = process.platform, home = boxHome(env), run = runCommand, log = () => {}, shims = null, pkglog = null, pull = true, image: asked = null, onState = () => {} }: { root: string; runtime: BoxRuntime; env?: Env; platform?: NodeJS.Platform; home?: string; run?: RunCommand; log?: BoxLog; shims?: string | null; pkglog?: BoxInstallLog | null; pull?: boolean; image?: BoxImage | null; onState?: OnState }): Promise<Box> {const projectRoot = path.resolve(root);const key = boxKey(projectRoot, { platform });const name = containerName(key, env);@@ -490,7 +514,7 @@ export async function openBox({ root, runtime, env = process.env, platform = proif (!boxd) return box.fail(`the sandbox helper is missing (linux-${goarch}/boxd)`, onState);const token = randomBytes(24).toString("hex");const user = commandUser(runtime, { platform });- const created = await rt(runtime, run)(createArgs({ name, key, root: projectRoot, croot, image: chosen.pull, runtime, run: runFolder, shims, token, user, env, platform }), { timeoutMs: 120_000 });+ const created = await rt(runtime, run)(createArgs({ name, key, root: projectRoot, croot, image: chosen.pull, runtime, run: runFolder, shims, pkglog, token, user, env, platform }), { timeoutMs: 120_000 });if (created.code !== 0) return box.fail(`could not create the sandbox: ${firstLine(created.stderr)}`, onState);const copied = await rt(runtime, run)(["cp", "-", `${name}:/`], { timeoutMs: 60_000, input: singleFileTar("opt/omnirush/bin/boxd", readFileSync(boxd)) });if (copied.code !== 0) {@@ -522,6 +546,10 @@ export async function openBox({ root, runtime, env = process.env, platform = proif (!identity) return box.fail("the sandbox helper did not answer", 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) {+ if (info.mounts.includes(containerRoot(pkglog.root, platform))) box.useInstallLog(pkglog);+ else log("info", "box made before the install log: its wrappers are not in this box (Reset sandbox adds them)", { key });+ }box.setState("ready", null, onState);return box;} catch (error) {@@ -645,7 +673,7 @@ export class Box {/** The record boxsh reads (boxes/<key>.json). */writeRecord(): void {const record: BoxRecord = {- v: 1, key: this.key, root: this.root, croot: this.croot, container: this.name, runtime: this.runtime?.bin ?? "",+ v: 1, key: this.key, root: this.root, croot: this.croot, container: this.name, runtime: this.runtime?.bin ?? "", runtime_args: 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",path_prefix: this.pathPrefix, env_file: `${RUN_DIR}/env`, updated: Date.now(), pid: process.pid,@@ -677,7 +705,7 @@ export class Box {/** The package-manager wrappers, installed inside (their install.sh), and the env they need. */async installShims(): Promise<void> {- const res = await client.exec(this.endpoint!, ["/bin/sh", `${SHIMS_DIR}-src/install.sh`, SHIMS_DIR, `${RUN_DIR}/ledger.jsonl`, `${RUN_DIR}/state`], { timeoutMs: 30_000 });+ const res = await client.exec(this.endpoint!, ["/bin/sh", `${SHIMS_DIR}-src/install.sh`, SHIMS_DIR, `${RUN_DIR}/ledger.jsonl`, `${RUN_DIR}/state`], { timeoutMs: 30_000, root: true });if (res.code !== 0) throw new Error(firstLine(res.stderr) || `install.sh exited ${res.code}`);const lines: string[] = [];for (const raw of res.stdout.split("\n")) {@@ -695,6 +723,19 @@ export class Box {this.writeRecord();}+ /**+ * The install log's wrappers (phase 1) in front of the box's PATH and its+ * pip hook on PYTHONPATH; the per-run folder they note calls in comes with+ * each call (OMNIRUSH_PKGLOG_DIR, forwarded by boxsh).+ */+ useInstallLog(pkglog: BoxInstallLog): void {+ const inBox = (p: string) => containerRoot(p, this.platform);+ this.pathPrefix = inBox(pkglog.bin);+ const lines = [`BOXD_PATH_PREFIX=${this.pathPrefix}`, `PYTHONPATH=${inBox(pkglog.py)}`];+ writeFileSync(path.join(this.runFolder, "env"), `${lines.join("\n")}\n`, { mode: 0o644 });+ this.writeRecord();+ }+/** The prompt number the package-manager wrappers write into their lines. */setTurn(turn: number): void {try { writeFileSync(path.join(this.runFolder, "state", "turn"), `${turn}\n`); } catch { /* best effort */ }@@ -798,8 +839,21 @@ export class Box {}const before = chain.signatures ?? {};const isDep = (p: string) => p.startsWith(`${this.croot}/`);+ // In the parent but not changed now: really gone (removed), or back at+ // the image's state, which the rebuild only has if this layer carries it.+ const left = Object.keys(before).filter((p) => !(p in now));+ const gone: string[] = [];+ if (left.length) {+ for (const entry of await client.stat(endpoint, left)) {+ if (entry.type === "missing") gone.push(entry.path);+ else if (entry.type !== "other") {+ now[entry.path] = signature(entry);+ sized.set(entry.path, entry);+ }+ }+ }const candidates = Object.keys(now).filter((p) => before[p] !== now[p]).sort();- const removed = topmost(Object.keys(before).filter((p) => !(p in now)));+ const removed = topmost(gone);// Caps: whole files past FILE_MAX left out; dependency folders up to depsMax; the tar up to tarMax.const skipped: Array<{ path: string; size: number; reason: string }> = [];let depBytes = 0;diff --git a/apps/server/src/box/client.ts b/apps/server/src/box/client.tsindex 5b138890..db17e747 100644--- a/apps/server/src/box/client.ts+++ b/apps/server/src/box/client.ts@@ -14,7 +14,7 @@ export const PROTO_VERSION = 1;const T = { stdout: 0x6f, stderr: 0x65, exit: 0x78, data: 0x64, fail: 0x45, stdinEof: 0x63, signal: 0x73 };export type BoxEndpoint = { host?: string; port: number; token: string };-export type BoxRequest = { op: string; argv?: string[]; cwd?: string; env?: Record<string, string>; paths?: string[]; wait?: number };+export type BoxRequest = { op: string; argv?: string[]; cwd?: string; env?: Record<string, string>; paths?: string[]; wait?: number; root?: boolean };export type BoxExit = { code: number; ms?: number };export type BoxReply = { exit: BoxExit; stdout: string; stderr: string; data: Buffer };export type BoxStat = { path: string; type: string; mode?: number; size?: number; uid?: number; gid?: number; link?: string; mtime_ns?: number | string; ctime_ns?: number | string };@@ -100,8 +100,8 @@ export async function ping(box: BoxEndpoint, { timeoutMs = 2_000 }: { timeoutMs?export type ExecResult = { code: number; stdout: string; stderr: string; ms?: number };/** Run a command in the box: { code, stdout, stderr, ms }. */-export async function exec(box: BoxEndpoint, argv: string[], { cwd, env, timeoutMs = 60_000 }: { cwd?: string; env?: Record<string, string>; timeoutMs?: number } = {}): Promise<ExecResult> {- const result = await request(box, { op: "exec", argv, ...(cwd ? { cwd } : {}), ...(env ? { env } : {}) }, { timeoutMs });+export async function exec(box: BoxEndpoint, argv: string[], { cwd, env, root = false, timeoutMs = 60_000 }: { cwd?: string; env?: Record<string, string>; root?: boolean; timeoutMs?: number } = {}): Promise<ExecResult> {+ const result = await request(box, { op: "exec", argv, ...(cwd ? { cwd } : {}), ...(env ? { env } : {}), ...(root ? { root: true } : {}) }, { timeoutMs });return { code: result.exit.code, stdout: result.stdout, stderr: result.stderr, ms: result.exit.ms };}diff --git a/apps/server/src/box/desktop.ts b/apps/server/src/box/desktop.tsindex 3465c1c1..9df4504c 100644--- a/apps/server/src/box/desktop.ts+++ b/apps/server/src/box/desktop.ts@@ -9,7 +9,7 @@ import { runtimeStorageDir } from "../runtime-db.js";import type { ServerConfig } from "../types.js";import type { BoxLog } from "./box.js";import type { ProjectBoxMode } from "./launch.js";-import { BoxService, nativeShell } from "./service.js";+import { BoxService } from "./service.js";export const BOX_SETTINGS_KEY = "localBox";@@ -32,9 +32,6 @@ export function boxServiceFor(config: ServerConfig, log?: BoxLog): BoxService {if (log) service.useLog(log);return service;}- // boxsh runs this shell for every call that is not for a box (Windows: Git for Windows' bash).- const shell = process.env.OMNIRUSH_BOX_REAL_SHELL ? null : nativeShell();- if (shell) process.env.OMNIRUSH_BOX_REAL_SHELL = shell;service = new BoxService({stateDir: runtimeStorageDir(config),readSettings: async (workspaceId) => readBoxSettings(await readOmniRushWorkspaceConfig(config, workspaceId)),diff --git a/apps/server/src/box/install-log.ts b/apps/server/src/box/install-log.tsnew file mode 100644index 00000000..92744cb3--- /dev/null+++ b/apps/server/src/box/install-log.ts@@ -0,0 +1,36 @@+/**+ * The install log (context/install-log.ts, phase 1) for chats in a Linux+ * sandbox (CLI: opencode-attach.ts around prepareInstallLog). The box gets+ * the POSIX wrappers and the pip hook from <state>/pkglog, mounted at the+ * same path (Windows: /c/...), and its wrappers note calls in a raw folder of+ * their own: box chats have their own capture context (session-uploader.ts+ * boxContext), which drains that folder only, so neither context takes the+ * other's calls.+ */+import { mkdir } from "node:fs/promises";+import { randomBytes } from "node:crypto";+import { dirname, join } from "node:path";++import { prepareInstallLog, type InstallLogPaths } from "../context/install-log.js";++export type BoxInstallLogPaths = { root: string; bin: string; py: string; raw: string };++/**+ * The box's wrappers (POSIX: this machine's own unless it is Windows) and its+ * raw folder beside this machine's. Null when the install log is off here.+ */+export async function prepareBoxInstallLog(stateDir: string, host: InstallLogPaths | null, platform: NodeJS.Platform = process.platform): Promise<BoxInstallLogPaths | null> {+ if (!host) return null;+ const root = join(stateDir, "pkglog");+ if (platform === "win32") {+ const posix = await prepareInstallLog({ stateDir, platform: "linux" });+ return posix ? { root, bin: posix.bin, py: posix.py, raw: posix.raw } : null;+ }+ try {+ const raw = join(dirname(host.raw), `${process.pid}-box-${randomBytes(4).toString("hex")}`);+ await mkdir(raw, { recursive: true });+ return { root, bin: host.bin, py: host.py, raw };+ } catch {+ return null;+ }+}diff --git a/apps/server/src/box/launch.ts b/apps/server/src/box/launch.tsindex c2918dbc..52afcfd1 100644--- a/apps/server/src/box/launch.ts+++ b/apps/server/src/box/launch.ts@@ -17,8 +17,8 @@ import { spawn, type ChildProcess } from "node:child_process";import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import path from "node:path";-import { boxKey, containerName, inspectImage, installShell, openBox, recordFile, savedTurns, type Box, type BoxLabel, type BoxLog, type BoxRuntime, type CheckpointSummary } from "./box.js";-import { detectStack, imageFor, type BoxImage } from "./images.js";+import { boxKey, containerName, gcBoxes, inspectImage, installShell, openBox, recordFile, rt, savedTurns, type Box, type BoxInstallLog, type BoxLabel, type BoxLog, type BoxRuntime, type CheckpointSummary } from "./box.js";+import { detectStack, imageFor, loadPins, type BoxImage } from "./images.js";import { detectRuntime, runCommand, type RunCommand, type RuntimeResult } from "./runtime.js";export const MODES = ["off", "offer", "on"] as const;@@ -96,7 +96,7 @@ export function pullInBackground(runtime: BoxRuntime, image: string, home: strinif (pid) { process.kill(pid, 0); return { started: false, pid }; }} catch { /* none running */ }mkdirSync(path.dirname(marker), { recursive: true });- const child = spawnImpl(runtime.bin, ["pull", image], { detached: true, stdio: "ignore", windowsHide: true });+ const child = spawnImpl(runtime.bin, [...(runtime.prefix ?? []), "pull", image], { detached: true, stdio: "ignore", windowsHide: true });child.unref?.();try { writeFileSync(marker, String(child.pid ?? "")); } catch { /* best effort */ }return { started: true, pid: child.pid };@@ -108,8 +108,12 @@ export type ReadyPlan = {box: { key: string; home: string; root: string; runtime: BoxRuntime };notice: null;shell: string;- /** Open the box (once); resolves the Box (state "ready" or "failed"). */- start: () => Promise<Box>;+ /**+ * Open the box (once); resolves the Box (state "ready" or "failed").+ * `pkglog`: the install log's folder (phase 1: { root, bin, py } with+ * POSIX wrappers), mounted into a new box and put on its PATH.+ */+ start: (options?: { pkglog?: BoxInstallLog | null }) => Promise<Box>;};export type NativePlan = { box: null; notice: string | null; runtime: RuntimeResult | null; image?: BoxImage; downloading?: boolean };export type BoxPlan = ReadyPlan | NativePlan;@@ -134,7 +138,7 @@ export async function planBox({ env = process.env, home, root, log = () => {}, rreturn { box: null, notice: `Sandbox off for now: ${error instanceof Error ? error.message : String(error)}.`, runtime };}// A box already made keeps its image (and its installs); a new one needs the image here.- const existing = await bounded(run(runtime.bin, ["container", "inspect", containerName(key, env), "--format", "{{.Id}}"], { timeoutMs: probeMs }), probeMs, { code: -1, stdout: "", stderr: "" });+ const existing = await bounded(rt(runtime, run)(["container", "inspect", containerName(key, env), "--format", "{{.Id}}"], { timeoutMs: probeMs }), probeMs, { code: -1, stdout: "", stderr: "" });if (existing.code !== 0) {const image = imageFor(detectStack(root), { env });const present = await bounded(inspectImage(runtime, image.pull, { run }), probeMs, null);@@ -143,18 +147,35 @@ export async function planBox({ env = process.env, home, root, log = () => {}, rreturn { box: null, notice: `Sandbox is downloading (${image.approxMb ? `about ${image.approxMb} MB, ` : ""}once); chats here run on this machine until it is ready.`, runtime, image, downloading: true };}}+ if (env.OMNIRUSH_BOX_GC !== "off") setTimeout(() => gcInBackground(runtime, home, { log }), 30_000).unref?.();let opening: Promise<Box> | null = null;return {box: { key, home, root, runtime },notice: null,shell,- start: () => {- opening ??= openBox({ root, runtime, env, home, log, pull: false, shims });+ start: ({ pkglog = null } = {}) => {+ opening ??= openBox({ root, runtime, env, home, log, pull: false, shims, pkglog });return opening;},};}+/**+ * Old boxes and images, at most once a day, in the background (never on the+ * start path): containers of folders that are gone or unused for 30 days,+ * box images that are neither current nor used. Labelled/named ones only.+ */+export function gcInBackground(runtime: BoxRuntime, home: string, { log = () => {}, now = Date.now(), everyMs = 24 * 3_600_000, gc = gcBoxes }: { log?: BoxLog; now?: number; everyMs?: number; gc?: typeof gcBoxes } = {}): Promise<Array<{ kind: string; name: string; reason: string }>> | null {+ const marker = path.join(home, "gc.json");+ try {+ if (now - Number(JSON.parse(readFileSync(marker, "utf8")).at) < everyMs) return null;+ } catch { /* never ran */ }+ try { mkdirSync(home, { recursive: true }); writeFileSync(marker, JSON.stringify({ at: now })); } catch { return null; }+ return gc(runtime, { home, pins: loadPins() })+ .then((removed) => { if (removed.length) log("info", "box gc", { removed: removed.map((item) => `${item.kind}:${item.name}`) }); return removed; })+ .catch((error) => { log("warn", "box gc failed", { error: String(error?.message || error) }); return []; });+}+/** The package-manager wrappers' source folder (phase 1), mounted read-only when present. */export function shimsDir(env: NodeJS.ProcessEnv = process.env): string | null {const asked = String(env.OMNIRUSH_BOX_SHIMS_DIR || "").trim();@@ -197,6 +218,8 @@ export type BoxRun = {key: string;container: string;runtimeBin: string;+ /** Arguments before the runtime's own (`-e docker` for a WSL engine). */+ runtimeArgs: string[];root: string;readonly native: boolean;readonly box: Box | null;@@ -215,12 +238,12 @@ export type BoxRun = {* "off"; the shell runs on this machine, its chats are not labelled); later* failures are logged and that turn has no checkpoint.*/-export function boxRun(plan: ReadyPlan, { log = () => {}, readyWaitMs = 30_000, onNative = () => {}, tmpRoot }: { log?: BoxLog; readyWaitMs?: number; onNative?: (reason: string) => void; tmpRoot?: string } = {}): BoxRun {+export function boxRun(plan: ReadyPlan, { log = () => {}, readyWaitMs = 30_000, onNative = () => {}, tmpRoot, pkglog = null }: { log?: BoxLog; readyWaitMs?: number; onNative?: (reason: string) => void; tmpRoot?: string; pkglog?: BoxInstallLog | null } = {}): BoxRun {const { key, home, runtime, root } = plan.box;let box: Box | null = null;let native = false;const checkpoints = new Map<string, number>();- const opening = plan.start().then((opened) => { box = opened; return opened; });+ const opening = plan.start({ pkglog }).then((opened) => { box = opened; return opened; });const goNative = (reason: string) => {if (native) return;native = true;@@ -240,6 +263,7 @@ export function boxRun(plan: ReadyPlan, { log = () => {}, readyWaitMs = 30_000,key,container: containerName(key),runtimeBin: runtime.bin,+ runtimeArgs: runtime.prefix ?? [],root,get native() { return native; },get box() { return box; },diff --git a/apps/server/src/box/plugin-lib.ts b/apps/server/src/box/plugin-lib.tsindex 674157be..73a44586 100644--- a/apps/server/src/box/plugin-lib.ts+++ b/apps/server/src/box/plugin-lib.ts@@ -21,7 +21,7 @@ export function keyOf(dir: string): string {return createHash("sha256").update(resolved).digest("hex").slice(0, 12);}-export function record(key: string): { state?: string; uid?: number } | null {+export function record(key: string): { state?: string; uid?: number; croot?: string } | null {try { return JSON.parse(readFileSync(path.join(boxHome(), "boxes", `${key}.json`), "utf8")); } catch { return null; }}@@ -33,12 +33,16 @@ export function record(key: string): { state?: string; uid?: number } | null {*/export const DESKTOP_PROJECTS_FILE = "desktop-projects.json";-export function desktopProjects(): Set<string> {+export function desktopProjects(): { keys: Set<string>; pkglogDir: string | null } {try {const value = JSON.parse(readFileSync(path.join(boxHome(), DESKTOP_PROJECTS_FILE), "utf8"));- return new Set(Array.isArray(value?.keys) ? value.keys.filter((key: unknown): key is string => typeof key === "string") : []);+ return {+ keys: new Set(Array.isArray(value?.keys) ? value.keys.filter((key: unknown): key is string => typeof key === "string") : []),+ // The install log's raw folder of box chats (box/install-log.ts): the wrappers in the box note calls there.+ pkglogDir: typeof value?.pkglog_dir === "string" && value.pkglog_dir ? value.pkglog_dir : null,+ };} catch {- return new Set();+ return { keys: new Set(), pkglogDir: null };}}@@ -70,9 +74,11 @@ export function toolPaths(tool: string, args: Record<string, unknown> = {}): strreturn [args.filePath, args.path, args.file_path].filter((value): value is string => typeof value === "string" && Boolean(value));}-export const BOX_NOTE = (root: string, uid = 0): string => [+export const BOX_NOTE = (root: string, uid = 0, croot = root): string => [`Sandbox: shell commands run in a Linux (Debian) container, ${uid === 0 ? "as root" : "as a user with passwordless sudo"}, with HOME=/root.`,- `The project folder ${root} is the same folder inside the container (same path); changes to it are visible on both sides.`,+ croot && croot !== root+ ? `The project folder ${root} is ${croot} inside the container (the same files); use ${croot} in shell commands. Changes are visible on both sides.`+ : `The project folder ${root} is the same folder inside the container (same path); changes to it are visible on both sides.`,"Files outside the project folder (/tmp, HOME, system folders) exist only inside the container: read and change them with shell commands, not with the file tools.","Install what the task needs with the usual package managers (apt-get, pip, npm, cargo, go, ...); installs persist in this project's container across sessions.",].join("\n");diff --git a/apps/server/src/box/runtime.ts b/apps/server/src/box/runtime.tsindex 237086f3..e18ad53d 100644--- a/apps/server/src/box/runtime.ts+++ b/apps/server/src/box/runtime.ts@@ -38,6 +38,9 @@ export type RuntimeInfo = {rootless: boolean;flavor: string;vm: boolean;+ /** A WSL engine: arguments before the runtime's own (["-e", "docker"] through wsl.exe). */+ prefix?: string[];+ wsl?: boolean;cached?: boolean;};export type RuntimeFailure = { ok: false; name?: string; bin?: string; reason: string; tried?: Array<{ name?: string; bin?: string; reason: string }>; cached?: boolean };@@ -251,6 +254,45 @@ export async function probe(candidate: RuntimeCandidate, { run = runCommand, env};}+/** wsl.exe, when Windows has it (System32). */+export function wslLauncher({ env = process.env, exists = existsSync }: { env?: Env; exists?: (file: string) => boolean } = {}): string | null {+ const root = env.SystemRoot || env.SYSTEMROOT || "C:\\Windows";+ const file = path.win32.join(root, "System32", "wsl.exe");+ return exists(file) ? file : null;+}++/**+ * Docker (then Podman) in the default WSL 2 distro: { ok, name, bin: wsl.exe,+ * prefix: ["-e", name], flavor: "wsl", wsl: true } or { ok: false, reason }.+ * No distro, no engine in it, or a distro without networking (nested+ * virtualization often has none) is a reason, never an install.+ */+export async function probeWsl(wslExe: string, { run = runCommand, env = process.env, timeoutMs = 12_000 }: { run?: RunCommand; env?: Env; timeoutMs?: number } = {}): Promise<RuntimeResult> {+ for (const name of ["docker", "podman"]) {+ const args = name === "podman" ? ["-e", "podman", "info", "--format", "json"] : ["-e", "docker", "info", "--format", "{{json .}}"];+ const res = await run(wslExe, args, { env, timeoutMs });+ const said = String(res.stderr || res.stdout || "").replace(/\u0000/g, "");+ if (res.code !== 0) {+ if (/no installed distributions|has no installed distributions|WSL_E_DEFAULT_DISTRO_NOT_FOUND|not installed/i.test(said)) {+ return { ok: false, name: "wsl", bin: wslExe, reason: "WSL has no Linux distribution (install one with Docker or Podman in it, or install Docker Desktop)" };+ }+ continue;+ }+ let info: Info;+ try { info = JSON.parse(res.stdout); } catch { continue; }+ if (name === "docker" && String(info.OSType ?? "linux") !== "linux") continue;+ return {+ ok: true, name, bin: wslExe, prefix: ["-e", name], wsl: true, flavor: "wsl",+ version: String(name === "podman" ? info.version?.Version ?? "" : info.ServerVersion ?? ""),+ os: "linux",+ arch: String(name === "podman" ? info.host?.arch ?? "" : info.Architecture ?? ""),+ rootless: name === "podman" ? Boolean(info.host?.security?.rootless) : /rootless/.test((Array.isArray(info.SecurityOptions) ? info.SecurityOptions : []).join(",")),+ vm: true,+ };+ }+ return { ok: false, name: "wsl", bin: wslExe, reason: "no Docker or Podman engine answers in the default WSL distribution" };+}+function cacheFile(boxHome: string): string {return path.join(boxHome, "runtime.json");}@@ -295,6 +337,16 @@ export async function detectRuntime({ boxHome, env = process.env, platform = proif (probed.ok) { result = probed; break; }tried.push(probed);}+ // Windows: a Docker or Podman engine inside an existing WSL 2 distro, used+ // through wsl.exe (never installed or started for the user).+ if (!result && platform === "win32" && env.OMNIRUSH_BOX_WSL !== "0") {+ const wslExe = wslLauncher({ env, exists });+ if (wslExe) {+ const probed = await probeWsl(wslExe, { run, env, ...(timeoutMs ? { timeoutMs } : {}) });+ if (probed.ok) result = probed;+ else tried.push(probed);+ }+ }if (!result) {const reason = tried.length? tried.map((entry) => entry.reason).join("; ")diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.tsindex 040fa267..65edcbca 100644--- a/apps/server/src/box/service.ts+++ b/apps/server/src/box/service.ts@@ -18,13 +18,13 @@** Not to be confused with the OpenWork worker sandbox (`sandboxBackend`).*/-import { existsSync } from "node:fs";import { mkdir, readFile, rename, writeFile } from "node:fs/promises";-import { delimiter, dirname, join } from "node:path";+import { join } from "node:path";import { boxHome, boxKey, boxSnapshotsDir, containerName, inspectImage, installShell, listBoxes, readRecord, resetBox, savedTurns, type BoxLabel, type BoxLog } from "./box.js";import { detectStack, imageFor } from "./images.js";import { boxRun, planBox, pulling, pullInBackground, resolveMode, serverDefault, shimsDir, type BoxRun, type ProjectBoxMode, type ServerBoxDefault } from "./launch.js";+import type { BoxInstallLogPaths } from "./install-log.js";import { DESKTOP_PROJECTS_FILE } from "./plugin-lib.js";import { detectRuntime, type RuntimeResult } from "./runtime.js";@@ -35,6 +35,8 @@ export type BoxCaptureInfo = {croot: string;container: string;runtimeBin: string;+ /** Arguments before the runtime's own (`-e docker` for a WSL engine). */+ runtimeArgs: string[];/** environment.sandbox of the chat's uploads. */label: BoxLabel;};@@ -82,17 +84,6 @@ export function boxRoot(workspace: BoxWorkspace): string {return workspace.directory?.trim() || workspace.path;}-/** The shell boxsh runs when a call is not for a box (Windows: Git for Windows' bash when it is there). */-export function nativeShell(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string | null {- if (platform !== "win32") return null;- for (const dir of String(env.PATH || env.Path || "").split(delimiter)) {- if (!dir || !existsSync(join(dir, "git.exe"))) continue;- const bash = join(dirname(dirname(dir)), "bin", "bash.exe");- if (existsSync(bash)) return bash;- }- return null;-}-export class BoxService {private readonly projects = new Map<string, Project>();private readonly turns = new Map<string, number>();@@ -100,6 +91,7 @@ export class BoxService {private readonly env: NodeJS.ProcessEnv;private log: BoxLog;private projectsWrite: Promise<void> = Promise.resolve();+ private installLog: BoxInstallLogPaths | null = null;constructor(private readonly options: BoxServiceOptions) {this.env = options.env ?? process.env;@@ -107,6 +99,15 @@ export class BoxService {this.log = options.log ?? (() => {});}+ /**+ * The install log of box chats (install-log.ts): new boxes mount its+ * folder and put its wrappers on PATH; the plugin points their calls at its+ * raw folder. Set at server start, before any box is planned.+ */+ useInstallLog(paths: BoxInstallLogPaths | null): void {+ this.installLog = paths;+ }+/** Logs go here from now on (the server's logger, once it exists). */useLog(log: BoxLog): void {this.log = log;@@ -179,6 +180,7 @@ export class BoxService {project.notice = null;project.run = boxRun(plan, {log: this.log,+ pkglog: this.installLog ? { root: this.installLog.root, bin: this.installLog.bin, py: this.installLog.py } : null,tmpRoot: join(this.home, "pending"),onNative: (reason) => {project.notice = `Sandbox off for now: ${reason}.`;@@ -204,7 +206,7 @@ export class BoxService {const keys = [...this.projects.entries()].filter(([, project]) => project.run && !project.run.native).map(([key]) => key).sort();const file = join(this.home, DESKTOP_PROJECTS_FILE);const write = async () => {- const content = `${JSON.stringify({ keys, updated: Date.now() })}\n`;+ const content = `${JSON.stringify({ keys, ...(this.installLog ? { pkglog_dir: this.installLog.raw } : {}), updated: Date.now() })}\n`;await mkdir(this.home, { recursive: true });const tmp = `${file}.${process.pid}.tmp`;await writeFile(tmp, content, { mode: 0o600 });@@ -238,6 +240,8 @@ export class BoxService {async status(workspace: BoxWorkspace, { fresh = false }: { fresh?: boolean } = {}): Promise<BoxStatus> {const { settings, server, on, source, offer } = await this.mode(workspace);+ // The server's "offer": shown once per folder (CLI: the tip, once per folder).+ if (offer && workspace.workspaceType === "local") await this.options.writeSettings(workspace.id, { offered: true }).catch(() => undefined);const root = boxRoot(workspace);const key = boxKey(root);const project = this.projects.get(key);@@ -340,7 +344,7 @@ export class BoxService {const label = run.label(sessionId);const box = run.box;if (!label || !box) return null;- return { key: run.key, root: run.root, croot: box.croot, container: box.container, runtimeBin: run.runtimeBin, label };+ return { key: run.key, root: run.root, croot: box.croot, container: box.container, runtimeBin: run.runtimeBin, runtimeArgs: run.runtimeArgs, label };}/** Whether chats ran in a box during this run (they get a `final` checkpoint at quit). */diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.tsindex 47131dad..3e0bb227 100644--- a/apps/server/src/capture-client.ts+++ b/apps/server/src/capture-client.ts@@ -402,6 +402,7 @@ class CaptureClient implements CaptureService {// Always: the chats this thread saw observed are known here even without a resolver.engineTarget: true,...(this.options.installLog ? { installLog: this.options.installLog } : {}),+ ...(this.options.boxInstallLog ? { boxInstallLog: this.options.boxInstallLog } : {}),sessionUploader: {upload: Boolean(sessionUploader.upload),uploadFile: Boolean(sessionUploader.uploadFile),diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.tsindex 974571c7..3bd00905 100644--- a/apps/server/src/capture-host.ts+++ b/apps/server/src/capture-host.ts@@ -100,6 +100,8 @@ export type CaptureHostOptions = {};/** The install log's raw folder and wrapper folder (install-log-host.ts), when the engines have them. */installLog?: { raw: string; bin: string } | null;+ /** The install log of chats in a Linux sandbox (box/install-log.ts): its own raw folder, POSIX wrappers. */+ boxInstallLog?: { raw: string; bin: string } | null;archive: Pick<SessionArchiverOptions, "request" | "refreshAccessToken" | "fetch" | "gatewayUrl" | "accessToken" | "folderGate"> & {/** Archiving is on for this device (OMNIRUSH_ARCHIVE_ENABLED) and an account is connected. */enabled: boolean;@@ -167,6 +169,7 @@ export class CaptureHost {// Capture context (context/); OMNIRUSH_CAPTURE_CONTEXT=0 turns it off.context: options.sessionUploader?.context ?? {},...(options.installLog ? { installLog: options.installLog } : {}),+ ...(options.boxInstallLog ? { boxInstallLog: options.boxInstallLog } : {}),...(options.onSessionClosed ? { onSessionClosed: options.onSessionClosed } : {}),// The touched-files archive hears of every path a session touches, here on the same thread.onPathTouched: (sessionId, path) => {@@ -222,7 +225,7 @@ export class CaptureHost {}this.boxChats.set(sessionId, box.container);if (!this.boxViews.has(box.container)) {- const view = sandboxFilesUsed({ container: box.container, manifest: { home: "/root", workspaces: [box.croot] }, cwd: box.root, hostHome: null, docker: box.runtimeBin, log: this.log });+ const view = sandboxFilesUsed({ container: box.container, manifest: { home: "/root", workspaces: [box.croot] }, cwd: box.root, hostHome: null, docker: box.runtimeBin, dockerArgs: box.runtimeArgs, log: this.log });if (view) this.boxViews.set(box.container, view);}}@@ -294,7 +297,7 @@ export class CaptureHost {// Capture v2: this turn's first tool call takes the folder's state (in the background).followToolStart({ observers: this.observers, archive: this.archive, sessionId, target });// Capture context: each tool call's start and end, for the network observer.- followContextToolEvents({ observers: this.observers, context: this.sessionUploader.context, sessionId, target });+ followContextToolEvents({ observers: this.observers, context: this.sessionUploader.contextOf(sessionId), sessionId, target });// Files used: each tool call's end, so its temp files are kept before a later call deletes them.followFilesUsedCalls({ observers: this.observers, archive: this.archive, sessionId, target });}diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.tsindex 3b7c5524..e620fba6 100644--- a/apps/server/src/capture-protocol.ts+++ b/apps/server/src/capture-protocol.ts@@ -87,6 +87,7 @@ export type CaptureWorkerInit = {sessionUploader: { upload: boolean; uploadFile: boolean; capabilities: boolean; refreshAccessToken: boolean; gatewayUrl?: string; accessToken?: string };/** The install log's folders (install-log-host.ts), when the engines have the wrappers. */installLog?: { raw: string; bin: string } | null;+ boxInstallLog?: { raw: string; bin: string } | null;archive: {enabled: boolean;excludedDirs: string[];diff --git a/apps/server/src/capture-worker.ts b/apps/server/src/capture-worker.tsindex 49ea7e8a..c5331c7d 100644--- a/apps/server/src/capture-worker.ts+++ b/apps/server/src/capture-worker.ts@@ -134,6 +134,7 @@ const host = new CaptureHost({}: {}),...(init.installLog ? { installLog: init.installLog } : {}),+ ...(init.boxInstallLog ? { boxInstallLog: init.boxInstallLog } : {}),sessionUploader: {...(init.sessionUploader.upload? {diff --git a/apps/server/src/opencode-plugins/omnirush-box.ts b/apps/server/src/opencode-plugins/omnirush-box.tsindex 5377a0d9..f8244f53 100644--- a/apps/server/src/opencode-plugins/omnirush-box.ts+++ b/apps/server/src/opencode-plugins/omnirush-box.ts@@ -29,16 +29,20 @@ export const OmniRushBox = async ({ directory }: { directory?: string }) => {const root = path.resolve(directory || process.cwd());const key = keyOf(root);const current = () => {- if (!desktopProjects().has(key)) return null;+ const listed = desktopProjects();+ if (!listed.keys.has(key)) return null;const rec = record(key);- return rec && rec.state !== "off" ? rec : null;+ return rec && rec.state !== "off" ? { ...rec, pkglogDir: listed.pkglogDir } : null;};const active = () => Boolean(current());const allowed = [root, ...engineDirs()];return {"shell.env": async (input: { callID?: string; sessionID?: string }, output: { env: Record<string, string> }) => {- if (!active()) return;+ const rec = current();+ if (!rec) return;output.env.OMNIRUSH_BOX_KEY = key;+ // Desktop: box chats note installs in their own raw folder (boxsh forwards it into the box).+ if (rec.pkglogDir) output.env.OMNIRUSH_PKGLOG_DIR = rec.pkglogDir;if (input.callID) output.env.OMNIRUSH_CALL = String(input.callID);if (input.sessionID) output.env.OMNIRUSH_SESSION = String(input.sessionID);},@@ -58,7 +62,7 @@ export const OmniRushBox = async ({ directory }: { directory?: string }) => {const line = output.system[i];if (typeof line === "string") output.system[i] = line.replace(/^(\s*Platform:\s*)(darwin|win32|linux)\s*$/m, "$1linux");}- output.system.push(BOX_NOTE(root, Number(rec.uid) || 0));+ output.system.push(BOX_NOTE(root, Number(rec.uid) || 0, typeof rec.croot === "string" ? rec.croot : root));},};};diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 2d03d795..f08de642 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -176,6 +176,7 @@ import {writeOmniRushWorkspaceConfig,} from "./omnirush-workspace-config-store.js";import { boxServiceFor } from "./box/desktop.js";+import { prepareBoxInstallLog } from "./box/install-log.js";import { rememberServerDefault } from "./box/launch.js";import { buildOmniRushRuntimeConfigObject, omnirushGatewayConfigured, omnirushRuntimeConfigFilePath, writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";import { assertMcpAllowed, mcpAllowed, mcpPolicyForConfig, MCP_DISABLED_MESSAGE } from "./mcp-policy.js";@@ -1102,9 +1103,13 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {});// The install log's wrappers (install-log-host.ts): ready before any engine starts.const installLogPaths = await prepareDesktopInstallLog(runtimeStorageDir(config)).catch(() => null);+ // The Linux sandbox's install log: the box mounts the wrappers; its calls go to a raw folder of their own (box/install-log.ts).+ const boxInstallLog = await prepareBoxInstallLog(runtimeStorageDir(config), installLogPaths).catch(() => null);+ boxServiceFor(config).useInstallLog(boxInstallLog);const capture = startCaptureService({stateDir: runtimeStorageDir(config),...(installLogPaths ? { installLog: { raw: installLogPaths.raw, bin: installLogPaths.bin } } : {}),+ ...(boxInstallLog ? { boxInstallLog: { raw: boxInstallLog.raw, bin: boxInstallLog.bin } } : {}),appVersion,// "opencode/1.18.32-r2": the bundled engine, as every upload names it (engine-identity.ts).engineVersion: BUNDLED_ENGINE_VERSION,diff --git a/apps/server/src/session-archive/files-used-sandbox.ts b/apps/server/src/session-archive/files-used-sandbox.tsindex 85a7bf42..2768d219 100644--- a/apps/server/src/session-archive/files-used-sandbox.ts+++ b/apps/server/src/session-archive/files-used-sandbox.ts@@ -172,7 +172,7 @@ export type ViewRunner = (request: unknown, maxOutputBytes: number) => Promise<R* failed, slow or oversized answer ends the process and the next request* starts another.*/-export function dockerExecRunner(container: string, docker = "docker", timeoutMs = STEP_TIMEOUT_MS): ViewRunner {+export function dockerExecRunner(container: string, docker = "docker", timeoutMs = STEP_TIMEOUT_MS, dockerArgs: readonly string[] = []): ViewRunner {type Live = { child: ChildProcessWithoutNullStreams; buffer: Buffer[]; size: number; waiting: ((line: Buffer | null) => void) | null };let live: Live | null = null;let tail: Promise<unknown> = Promise.resolve();@@ -198,7 +198,7 @@ export function dockerExecRunner(container: string, docker = "docker", timeoutMsconst start = (): Live | null => {let child: ChildProcessWithoutNullStreams;try {- child = spawn(docker, ["exec", "-i", container, "/usr/bin/python3", "-I", "-c", FILES_USED_VIEW_SCRIPT], { stdio: ["pipe", "pipe", "ignore"] as const, windowsHide: true }) as unknown as ChildProcessWithoutNullStreams;+ child = spawn(docker, [...dockerArgs, "exec", "-i", container, "/usr/bin/python3", "-I", "-c", FILES_USED_VIEW_SCRIPT], { stdio: ["pipe", "pipe", "ignore"] as const, windowsHide: true }) as unknown as ChildProcessWithoutNullStreams;} catch {return null;}@@ -333,6 +333,8 @@ export function sandboxFilesUsed(input: {cwd: string;hostHome: string | null;docker?: string;+ /** Arguments before docker's own (`-e docker` when docker is reached through wsl.exe). */+ dockerArgs?: readonly string[];log?: (level: "info" | "warn", message: string, attributes?: Record<string, unknown>) => void;}): FilesUsedSandbox | null {if (!input.container) return null;@@ -340,7 +342,7 @@ export function sandboxFilesUsed(input: {const home = typeof manifest.home === "string" && manifest.home.startsWith("/") ? manifest.home : "/home/omnirush";const workspaces = Array.isArray(manifest.workspaces) ? manifest.workspaces.filter((entry): entry is string => typeof entry === "string" && entry.startsWith("/")) : [];let warned = false;- const view = containerFilesUsedView(dockerExecRunner(input.container, input.docker || "docker"), (op) => {+ const view = containerFilesUsedView(dockerExecRunner(input.container, input.docker || "docker", STEP_TIMEOUT_MS, input.dockerArgs ?? []), (op) => {if (warned) return;warned = true;input.log?.("warn", "OmniRush files used: the sandbox could not be read; its files are listed, not kept", { op });diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.tsindex 88a99260..2d799b5e 100644--- a/apps/server/src/session-uploader.ts+++ b/apps/server/src/session-uploader.ts@@ -288,6 +288,12 @@ export type UploadEnvironment = {sandbox?: BoxLabel;};+/** A box chat's toolchain without this machine's `system` and `shell` blocks. */+function withoutHostBlocks(toolchain: UploadToolchain): UploadToolchain {+ const { system: _system, shell: _shell, ...rest } = toolchain;+ return rest;+}+/*** A chat in a box (an OmniRush box label, `kind: "omnirush-box"`): it ran* its commands on Linux in a container, so `os` is linux and the machine it@@ -796,6 +802,8 @@ type SessionUploaderOptions = {* (sampled per session). Absent: none.*/installLog?: { raw: string; bin?: string | null } | null;+ /** The install log of chats in a Linux sandbox (box/install-log.ts): the wrappers there note calls in this raw folder. */+ boxInstallLog?: { raw: string; bin?: string | null } | null;};export type TraceCapabilities = {@@ -4557,6 +4565,12 @@ export class SessionUploader {readonly metrics: UploadMetrics = freshMetrics();/** Capture context (context/), null when off. */readonly context: ContextCapture | null;+ /**+ * Capture context of chats in a Linux sandbox (box/): this machine's packages, services,+ * processes, network and package-manager config are not theirs; the install log (its+ * wrappers run in the box) and the rest are (CLI: the same sections for box runs).+ */+ readonly boxContext: ContextCapture | null;constructor(options: SessionUploaderOptions = {}) {this.uploadUrl = resolveUploadUrl(options.gatewayUrl ?? process.env.OMNIRUSH_GATEWAY_URL);@@ -4630,6 +4644,11 @@ export class SessionUploader {);void this.stateMigrated.then(() => this.cleanTempDir(60 * 60_000)).catch(() => undefined);this.context = !options.context || !this.enabled ? null : this.createContext(stateDir, options.context);+ this.boxContext = !options.context || !this.enabled ? null : this.createContext(stateDir, {+ ...options.context,+ sections: { ...options.context.sections, system_packages: false, services: false, pm_config: false, shell_aliases: false, processes: false },+ network: false,+ }, options.boxInstallLog ?? null);// Uploads spooled by a previous process are retried once this one is up.// Without an account they wait (up to the spool's age limit) for the// account to come back: only a user sign-out clears them (clearSpool()).@@ -4641,7 +4660,12 @@ export class SessionUploader {}/** Capture context wired to this uploader: its trace, its scrub, the project archive and the archive's exclusions. */- private createContext(stateDir: string | null, overrides: Partial<ContextOptions>): ContextCapture | null {+ /** The capture context a chat's events go to (a box chat's own, else this machine's). */+ contextOf(sessionId: string): ContextCapture | null {+ return this.boxes.has(sessionId) ? this.boxContext : this.context;+ }++ private createContext(stateDir: string | null, overrides: Partial<ContextOptions>, installLog: { raw: string; bin?: string | null } | null = this.installLogPaths): ContextCapture | null {// Off (OMNIRUSH_CAPTURE_CONTEXT=0): nothing is loaded or read.if (overrides.enabled === false || (overrides.enabled === undefined && !captureContextEnabled(overrides.env ?? process.env))) return null;let exclusion: ((absolute: string) => string | null) | null = null;@@ -4684,7 +4708,7 @@ export class SessionUploader {bundledSkillDirs: stateDir ? [join(stateDir, "skills")] : [],configFiles: stateDir ? [join(stateDir, "runtime-opencode-config.json")] : [],log: this.log,- ...(this.installLogPaths ? { installLog: { ...this.installLogPaths, gate: () => this.installLogGate(), appDirs: stateDir ? [stateDir] : [] } } : {}),+ ...(installLog ? { installLog: { ...installLog, gate: () => this.installLogGate(), appDirs: stateDir ? [stateDir] : [] } } : {}),...overrides,});return capture.enabled ? capture : null;@@ -4926,7 +4950,10 @@ export class SessionUploader {const environment = await this.environment();const box = this.boxes.get(sessionId) ?? null;const toolchains = box ? this.boxToolchains : this.toolchains;- const toolchain = toolchains ? await toolchains.get(root, waitMs).catch(() => null) : null;+ const probed = toolchains ? await toolchains.get(root, waitMs).catch(() => null) : null;+ // A box chat: the toolchain was probed in the box, but its `system` and `shell`+ // blocks are this machine's; the box's are its image (sandbox.image). CLI: the same.+ const toolchain = probed && box ? withoutHostBlocks(probed) : probed;const importedFrom = engine2ImportedFrom(sessionId);return { ...environment, ...boxEnvironment(environment, box?.label ?? null), ...(toolchain ? { toolchain } : {}), ...(box ? { sandbox: box.label } : {}), ...(importedFrom ? { imported_from: importedFrom } : {}) };}@@ -5032,8 +5059,8 @@ export class SessionUploader {// Capture context collects once the start snapshot is out.let startSnapshotDone: () => void = () => undefined;const startSnapshot = new Promise<void>((resolveStart) => (startSnapshotDone = resolveStart));- // A box chat: this machine's packages, services, processes and network are not the chat's.- if (!this.boxes.has(sessionId)) this.context?.sessionStarted(sessionId, root, startSnapshot);+ // A box chat: its own context (this machine's packages, services, processes and network are not the chat's).+ this.contextOf(sessionId)?.sessionStarted(sessionId, root, startSnapshot);this.enqueue(state, async () => {await state.ready;try {@@ -5539,7 +5566,7 @@ export class SessionUploader {this.appendTrace(state, "client.launch", clientLaunchData());}this.appendTrace(state, type, data);- if (type === "turn.messages" && isRecord(data)) this.context?.turnMessages(sessionId, data.messages);+ if (type === "turn.messages" && isRecord(data)) this.contextOf(sessionId)?.turnMessages(sessionId, data.messages);}/** Appends one trace event, keeping only the newest MAX_UPLOAD_TRACE_EVENTS. */@@ -5760,9 +5787,9 @@ export class SessionUploader {state.relevance.clear();state.turnWrittenPaths.clear();// After the turn's artifact baseline (set just below) is listed.- this.context?.turnStarted(sessionId, Promise.resolve().then(() => state.artifactBaseline));+ this.contextOf(sessionId)?.turnStarted(sessionId, Promise.resolve().then(() => state.artifactBaseline));} else {- this.context?.turnEnded(sessionId);+ this.contextOf(sessionId)?.turnEnded(sessionId);}// The artifact baseline must reflect the workspace as the turn begins, not// once the queued start snapshot has finished uploading.@@ -5902,10 +5929,10 @@ export class SessionUploader {this.recordTouchedPath(state, evidence.path, evidence.relevance);}// Capture context: the turn's last messages (its tool calls) arrive here, not as turn.messages.- if (isRecord(finalTrace)) this.context?.turnMessages(sessionId, finalTrace.messages, true);+ if (isRecord(finalTrace)) this.contextOf(sessionId)?.turnMessages(sessionId, finalTrace.messages, true);}state.finished = true;- this.context?.sessionEnded(sessionId);+ this.contextOf(sessionId)?.sessionEnded(sessionId);if (state.changeTimer) clearTimeout(state.changeTimer);if (state.deferTimer) clearTimeout(state.deferTimer);state.changeTimer = null;@@ -5917,7 +5944,7 @@ export class SessionUploader {this.enqueue(state, async () => {await state.ready;// Capture context still collecting (bounded wait) rides along with the last trace.- await this.context?.settled(sessionId);+ await this.contextOf(sessionId)?.settled(sessionId);if (state.trace.length > 0) pendingTrace.push(...state.trace.splice(0));await state.changeCaptureTail;if (finalTrace !== undefined) pendingTrace.push({ at: new Date().toISOString(), type: "session.completed", data: finalTrace });@@ -5946,7 +5973,7 @@ export class SessionUploader {this.recordTouchedPath(state, evidence.path, evidence.relevance);}// Capture context: the turn's last messages (its tool calls) arrive here, not as turn.messages.- if (isRecord(finalTrace)) this.context?.turnMessages(sessionId, finalTrace.messages, true);+ if (isRecord(finalTrace)) this.contextOf(sessionId)?.turnMessages(sessionId, finalTrace.messages, true);pendingTrace.push({ at: new Date().toISOString(), type: "turn.completed", data: finalTrace });}if (pendingTrace.length === 0) return;