Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bot box: on a My Cloud a box keeps only its own engine account's sign-in (#7406)
Milind Sonib5a3331280ae
diff --git a/docs/bot-box.md b/docs/bot-box.mdindex b151489b30..b01de9b1f3 100644--- a/docs/bot-box.md+++ b/docs/bot-box.md@@ -10,7 +10,7 @@ its database, its settings, other bots' folders and other turns' processes are n| Inside the box | What it is ||---|---|| `/usr`, `/etc`, `/opt`, the server's own code folder, read-only | The image: engine CLIs, node, python, git, the bots' browser |-| `HOME`, read-write | The engines' own logins and settings (`~/.claude`, `~/.codex`, `~/.grok`). On a Team Cloud this is the turn's audience's engine home instead, with the team's engine sign-in files bound into it, and the server's HOME is not there at all ([team-cloud.md](team-cloud.md#engine-homes)) |+| `HOME`, read-write | What bots and engines keep there: settings, tools, caches, git config. Of the engines' sign-in files (`~/.claude/.credentials.json`, `~/.codex/auth.json`, `~/.grok/auth.json`, the rest of `ENGINE_FOLDERS` in `server/engine-homes/layout.ts`) only the one of the engine account the process runs is there, bound over itself so a refresh writes in place; every other engine's and account's is an empty read-only file; every folder between HOME and those files is bound over itself, so a bot cannot rename one away; and a process that names no engine (a shell step, an MCP server) has none (`server/bot-box/sign-in-masks.ts`). The edge's certificate folder (`~/.omb-edge`) is an empty private folder. On a Team Cloud this is the turn's audience's engine home instead, with the team's engine sign-in files bound into it, and the server's HOME is not there at all ([team-cloud.md](team-cloud.md#engine-homes)) || the data folder (`~/.openmausbot`), **an empty private folder** | `messages.db`, `config.json`, logins, the server's sockets, every other bot's folders are not there || put back inside it: the turn's working folder and the bot's own folder (`workspaces/<bot>`), read-write | What the turn works on, and the bot's memory and skills. On a Team Cloud a turn that is not the team's has the bot's own folder read-only, and its own memory layer read-write ([team-cloud.md](team-cloud.md#the-audience-rule)) || put back: this turn's permission socket (the engine's question and approval helper reaches the server through it), and, read-only, the conversation's own hook token folder (the hook helper's bearer, renewed each turn) and the files its command line names (MCP config, system prompt) | What the driver made for this one process |@@ -182,8 +182,14 @@ checks it guards.- **Local VM (Docker) computer use.** The computer MCP talks to the Local VM over the host's Docker socket. The box does not expose that socket (mounting it would be root-equivalent on the host), so with the bot box on a Local VM turn fails early with a clear message instead of "MCP server exited". Use this computer, a Cloud computer, or turn the box off for Local VM work.-- The engines' subscription logins (`~/.claude`, `~/.codex`) are in the box, because the engine needs them. API keys- stay in the environment until the credential broker (T0b) replaces them with per-turn tokens.+- The engine's own subscription login is in its box, because the engine runs there and refreshes it; any program the+ bot runs in that box can read it. API keys stay in the environment until the credential broker (T0b) replaces them+ with per-turn tokens.+- Sign-in masks are fixed when a box starts. A sign-in file made after that (an engine signed in for the first time), or+ one a process outside any box replaces by renaming a new file over it, is readable in a box that was already running+ until that box's process ends. Engines whose sign-in is not in `ENGINE_FOLDERS` keep theirs in HOME, readable from+ every box. On a Team Cloud every audience's engine home holds a copy+ of every engine's team sign-in, so a box there reads all of them.- The box runs as the server's own user inside a user namespace; a separate Linux user per bot needs a privilegedspawn service (T0c notes).- On a Team Cloud each Chrome of the bots' browsers runs in a box of its own (`BotBox.browserBox`, written into the@@ -228,7 +234,7 @@ or files, the base URL is the broker, a call with the token reaches the upstream| Layer | Where | What it stops | What it does not stop ||---|---|---|---|-| Mount namespace (bubblewrap) | every boxed process | reading the server's data folder, other bots' folders, other turns' files in `/tmp`, `/.fly`; writing anywhere but its own folders | reading HOME's engine logins (the engine's own identity); a path a driver puts back on purpose |+| Mount namespace (bubblewrap) | every boxed process | reading the server's data folder, other bots' folders, other turns' files in `/tmp`, `/.fly`, other engines' and accounts' sign-ins in HOME; writing anywhere but its own folders | reading the engine's own login in HOME (its identity) and sign-ins of engines outside `ENGINE_FOLDERS`; a path a driver puts back on purpose || PID namespace | every boxed process | seeing, reading the environment of, or signalling another turn's or the server's processes | nothing inside the same box || Network namespace + the two gates | every boxed process with its own network | reaching this machine's other listeners, the local network, link-local, metadata, Fly's private network; any route out except the egress gate; any server route except `/api/internal/*` | what the harness routes allow with a valid per-turn bearer; a public destination || Environment allow-list | every boxed process | `OMB_CLOUD_*`, the server's placement, workspace credentials, any `OMB_*` setting a boxed process does not read, any unlisted name | the engines' own settings |diff --git a/server/bot-box/box.ts b/server/bot-box/box.tsindex c296dc060d..b28c882b52 100644--- a/server/bot-box/box.ts+++ b/server/bot-box/box.ts@@ -22,6 +22,7 @@ import { procHidepid } from "./hidepid.ts";import { DENIED_SYSCALLS, seccompBytes, seccompSupported } from "./seccomp.ts";import { RELAY_SOCKET_NAME, TEAM_FOLDER_KEPT, boxUploadsConversation, boxUploadsDir, teamFolderOf, under, bwrapArgs, inBoxSocket, planBox, taskWorkspaceIds, type BoxAudience, type BoxBridge, type BoxPlan, type BoxRequest, type BoxSetup } from "./plan.ts";import { openBoxRelay, type BoxRelay } from "./relay.ts";+import { signInMasks } from "./sign-in-masks.ts";import { CACHE_ROOT_SWITCH, ensureToolCacheRoot, toolCacheEnvironment, toolCacheRoot, toolCachesOn } from "./tool-caches.ts";/** The loopback port inside a box that reaches the egress gate. The harness gate sits at the server's own port. */@@ -153,7 +154,8 @@ export class BoxRunner {const request: BoxRequest = { ...given, ...(lent.length ? { rw: [...(given.rw ?? []), ...lent] } : {}), ...(audience ? { audience } : {}) };const extraFds: number[] = [];const seccomp = this.options.seccompFile && !this.options.setup.mutate?.has("no-seccomp") ? this.options.seccompFile : null;- const plan = planBox({ ...this.options.setup, seccompFd: seccomp ? BOX_SECCOMP_FD : undefined }, request);+ const signIns = request.home ? undefined : signInMasks({ home: this.options.setup.home, dataDir: this.options.setup.dataDir, env: request.env, engine: request.engine });+ const plan = planBox({ ...this.options.setup, seccompFd: seccomp ? BOX_SECCOMP_FD : undefined }, request, signIns);const mutate = this.options.setup.mutate;const env = mutate?.has("env-all")? Object.fromEntries(Object.entries(request.env).filter((entry): entry is [string, string] => entry[1] !== undefined))diff --git a/server/bot-box/plan.ts b/server/bot-box/plan.tsindex 8b2a8b9700..11904c4716 100644--- a/server/bot-box/plan.ts+++ b/server/bot-box/plan.ts@@ -6,7 +6,8 @@// - its HOME read-write (the engine's own login and settings live there), with the server's data folder replaced by an// empty private folder, so messages.db, config.json, logins, other bots' folders and the server's sockets are not there;// on a Team Cloud that HOME is the audience's engine home instead (server/engine-homes), with only the team's engine-// sign-ins bound into it, so no other audience's transcripts are there;+// sign-ins bound into it, so no other audience's transcripts are there; in the server's HOME every engine sign-in but+// the one of the engine account the process runs is masked, as are the folders only the server reads (sign-in-masks.ts);// - put back inside that empty folder: this turn's working folder, the bot's own folder (workspaces/<bot>) and what the// caller names (the turn's permission socket, a read-only file the command line points at); and, read-only, the// bot's own SOUL.md (bots/<bot>/SOUL.md, which it may read but never write) and the engines OpenMausBot installed@@ -26,10 +27,11 @@ import { isLayerId } from "../audience.ts";export type BoxNet = "isolated" | "shared";-/** One line of the plan. `bind` is read-write, `ro` read-only; `tmpfs` an empty private folder; `symlink` a link. */+/** One line of the plan. `bind` is read-write, `ro` read-only; `tmpfs` an empty private folder; `mask` an empty read-only+ * file over an existing one; `symlink` a link. */export type Mount =| { kind: "ro" | "bind"; source: string; target: string; optional?: boolean }- | { kind: "tmpfs" | "proc" | "dev" | "dir"; target: string }+ | { kind: "tmpfs" | "proc" | "dev" | "dir" | "mask"; target: string }| { kind: "symlink"; link: string; target: string };export interface BoxBridge { port: number; socket: string; name: string }@@ -95,6 +97,21 @@ export interface BoxRequest {conversationBot?: string;/** On a Team Cloud: what the conversation's audience gives the box of the bot's team things (BoxAudience). */audience?: BoxAudience;+ /** The driver kind of the engine this process runs, whose sign-in in the server's HOME it keeps (SignInMasks). */+ engine?: string;+}++/** What of the engines' sign-ins in the server's HOME a box keeps (sign-in-masks.ts), for a box that has that HOME. */+export interface SignInMasks {+ /** The folders between HOME and those files, parents first, bound over themselves read-write. */+ folders: readonly string[];+ /** The spawn's own sign-in files, bound over themselves read-write: a refresh then writes in place instead of renaming a+ * new file over the old one, which would lift that file's mask in every other running box. */+ own: readonly string[];+ /** Other engines' and accounts' sign-in files, each replaced by an empty read-only file. */+ masked: readonly string[];+ /** Folders only the server reads, replaced by an empty private one. */+ hidden: readonly string[];}/** On a Team Cloud, what one conversation's boxes get of what is the team's (docs/team-cloud.md, "The audience rule"):@@ -204,7 +221,7 @@ function assertReadOnlySource(source: string): void {}}-export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {+export function planBox(setup: BoxSetup, request: BoxRequest, signIns?: SignInMasks): BoxPlan {const mutate = setup.mutate ?? new Set<BoxMutation>();const dataDir = resolve(setup.dataDir), home = resolve(setup.home);const net: BoxNet = mutate.has("share-net") ? "shared" : request.net ?? "isolated";@@ -238,6 +255,8 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {// An engine home lives in the data folder, so it goes back after that.const ownHome = request.home ? resolve(request.home) : null;if (!ownHome) rw(home);+ // Before the data folder's line, so one of these holding the data folder never shows it.+ if (!ownHome) for (const folder of signIns?.folders ?? []) if (under(folder, home) && folder !== home) mounts.push({ kind: "bind", source: folder, target: folder, optional: true });const dataInsideHome = under(dataDir, home);if (!mutate.has("bind-data")) {if (dataInsideHome) mounts.push({ kind: "tmpfs", target: dataDir });@@ -349,6 +368,14 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {if (teamFiles.write) mounts.push({ kind: "ro", source: join(resolve(teamFiles.source), TEAM_FILES_LIBRARY), target: join(TEAM_FILES_IN_BOX, TEAM_FILES_LIBRARY), optional: true });}+ // Security: last, so no line above puts another engine's or account's sign-in back. Only in the server's HOME.+ if (!ownHome && signIns) {+ const inHome = (path: string) => under(path, home) && !under(path, dataDir);+ for (const file of signIns.own) if (inHome(file)) mounts.push({ kind: "bind", source: file, target: file, optional: true });+ for (const file of signIns.masked) if (inHome(file)) mounts.push({ kind: "mask", target: file });+ for (const folder of signIns.hidden) if (inHome(folder)) mounts.push({ kind: "tmpfs", target: folder });+ }+const options = ["--unshare-user", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup-try", "--die-with-parent", "--hostname", BOX_HOSTNAME];if (!mutate.has("share-pid")) options.push("--unshare-pid");if (setup.seccompFd !== undefined && !mutate.has("no-seccomp")) options.push("--seccomp", String(setup.seccompFd));@@ -382,6 +409,7 @@ export function bwrapArgs(plan: BoxPlan): string[] {case "proc": args.push("--proc", mount.target); break;case "dev": args.push("--dev", mount.target); break;case "dir": args.push("--dir", mount.target); break;+ case "mask": args.push("--ro-bind", "/dev/null", mount.target); break;case "symlink": args.push("--symlink", mount.target, mount.link); break;}}diff --git a/server/bot-box/sign-in-masks.linux.test.ts b/server/bot-box/sign-in-masks.linux.test.tsnew file mode 100644index 0000000000..fdee32d3c9--- /dev/null+++ b/server/bot-box/sign-in-masks.linux.test.ts@@ -0,0 +1,84 @@+// The sign-in masks in a real box, where one can run: Linux with an unprivileged bubblewrap (a Cloud home, the Fly test+// machine). Elsewhere the suite says so and skips, like the box's own self-check.+import { spawnSync } from "node:child_process";+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { detectBox } from "./detect.ts";+import { bwrapArgs, planBox, type BoxRequest } from "./plan.ts";+import { signInMasks } from "./sign-in-masks.ts";++const detection = detectBox({ env: { ...process.env, OMB_BOT_BOX: "1" } });+const available = detection.box === "bwrap" && detection.tools !== null;+const root = realpathSync(mkdtempSync(join(tmpdir(), "omb-sign-in-box-")));+afterAll(() => rmSync(root, { recursive: true, force: true }));++const home = join(root, "home"), dataDir = join(home, ".openmausbot");+const cwd = join(dataDir, "task-workspaces", "bot-a", "t-1");+const claude = join(home, ".claude", ".credentials.json"), codex = join(home, ".codex", "auth.json");+const put = (path: string, text: string) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); };++function runInBox(engine: string, script: string): string {+ const request: BoxRequest = { command: "/bin/sh", args: [], cwd, env: { HOME: home, PATH: "/usr/bin:/bin" }, engine };+ const plan = planBox({ dataDir, home, codeRoots: [], engineRoots: [], bridges: [] }, request, signInMasks({ home, dataDir, env: request.env, engine }));+ const ran = spawnSync(detection.tools!.bwrap, [...bwrapArgs(plan), "--", "/bin/sh", "-c", script], { env: { HOME: home, PATH: "/usr/bin:/bin" }, encoding: "utf8", timeout: 30_000 });+ if (ran.error || ran.signal || ran.status !== 0) throw new Error(`the box did not run: ${ran.error?.message ?? ran.signal ?? ran.status}: ${ran.stderr}`);+ return `${ran.stdout}${ran.stderr}`;+}++describe.skipIf(!available)(`sign-in masks in a real box (${available ? "bubblewrap works here" : `skipped: ${detection.reason}`})`, () => {+ beforeAll(() => {+ put(claude, '{"claudeAiOauth":{"accessToken":"claude-secret"}}');+ put(codex, '{"tokens":{"access_token":"codex-1"}}');+ put(join(home, ".omb-edge", "caddy", "site.key"), "edge-secret");+ mkdirSync(cwd, { recursive: true });+ mkdirSync(join(dataDir, "workspaces", "bot-a"), { recursive: true });+ });++ it("a Codex bot's shell reads and refreshes its own login, and never Claude's or the edge's keys", () => {+ const before = readdirSync(home).sort();+ const output = runInBox("codex", [+ `cat "${claude}"; echo " CLAUDE-END"`,+ `grep -r edge-secret "${home}/.omb-edge" 2>/dev/null || echo EDGE-UNREADABLE`,+ `printf x > "${claude}" 2>/dev/null || echo MASK-NOT-WRITABLE`,+ `mv "${claude}" "${home}/stolen" 2>/dev/null || echo MASK-NOT-MOVABLE`,+ `printf x > "${home}/.claude/.next" && mv "${home}/.claude/.next" "${claude}" 2>/dev/null || echo MASK-NOT-REPLACEABLE`,+ `cat "${codex}"; echo`,+ `mv "${home}/.codex/auth.json" "${home}/.codex/moved" 2>/dev/null || echo OWN-RENAME-REFUSED`,+ `printf '%s' '{"tokens":{"access_token":"codex-2"}}' > "${codex}" && echo WROTE-IN-PLACE`,+ ].join("\n"));+ expect(output).not.toContain("claude-secret");+ expect(output).toContain(" CLAUDE-END");+ expect(output).toContain("EDGE-UNREADABLE");+ expect(output).toContain("MASK-NOT-WRITABLE");+ expect(output).toContain("MASK-NOT-MOVABLE");+ expect(output).toContain("MASK-NOT-REPLACEABLE");+ expect(output).toContain("codex-1");+ expect(output).toContain("OWN-RENAME-REFUSED");+ expect(output).toContain("WROTE-IN-PLACE");+ expect(readFileSync(codex, "utf8")).toContain("codex-2");+ expect(readFileSync(claude, "utf8")).toContain("claude-secret");+ expect(readdirSync(home).sort()).toEqual(before);+ }, 60_000);++ it("a bot cannot rename a sign-in's folder away so the next box reads it at another path", () => {+ const first = runInBox("codex", [+ `mv "${home}/.claude" "${home}/moved-claude" 2>/dev/null || echo FOLDER-NOT-MOVABLE`,+ `rm -rf "${home}/.claude" 2>/dev/null; ls "${claude}" >/dev/null 2>&1 && echo STILL-THERE`,+ ].join("\n"));+ expect(first).toContain("FOLDER-NOT-MOVABLE");+ expect(first).toContain("STILL-THERE");+ const second = runInBox("codex", `cat "${home}/moved-claude/.credentials.json" 2>/dev/null || echo NOT-MOVED; cat "${claude}"; echo " END"`);+ expect(second).toContain("NOT-MOVED");+ expect(second).not.toContain("claude-secret");+ expect(readFileSync(claude, "utf8")).toContain("claude-secret");+ }, 60_000);++ it("leaves no empty sign-in file behind for an engine that never signed in here", () => {+ runInBox("claudeAgent", "true");+ expect(readdirSync(home)).not.toContain(".grok");+ expect(readdirSync(home)).not.toContain(".gemini");+ }, 60_000);+});diff --git a/server/bot-box/sign-in-masks.test.ts b/server/bot-box/sign-in-masks.test.tsnew file mode 100644index 0000000000..9fb9f9cf07--- /dev/null+++ b/server/bot-box/sign-in-masks.test.ts@@ -0,0 +1,213 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterAll, describe, expect, it } from "vitest";++import { edgeCertificateStorage } from "../cloud-home-start.ts";+import { BUILT_IN_DRIVERS } from "../drivers/builtIn.ts";+import { chatgptAccountHome } from "../drivers/codex-account-home.ts";+import { linkSharedCodexHome } from "../drivers/codex-shared-home.ts";+import { ENGINE_FOLDERS, audienceHome, homedSpawn } from "../engine-homes/layout.ts";+import { BoxRunner } from "./box.ts";+import { boxEnvironment } from "./env.ts";+import { bwrapArgs, planBox, visibleInBox, type BoxRequest, type BoxSetup } from "./plan.ts";+import { signInMasks } from "./sign-in-masks.ts";++// Under the checkout, like a Cloud's /data: the box keeps an engine folder under /tmp its own private one, so a fixture+// data folder there would never have its Codex homes put back.+const checkoutUnderTmp = ["/tmp", "/var/tmp", realpathSync(tmpdir())].some((base) => realpathSync(process.cwd()).startsWith(`${base}/`));+const root = realpathSync(mkdtempSync(join(process.cwd(), ".omb-test-sign-in-masks-")));+afterAll(() => rmSync(root, { recursive: true, force: true }));++const put = (path: string, text = "x") => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); };++/** A My Cloud volume as engines leave it: every engine signed in once, the edge's certificate, and what bots made in HOME. */+function volume(name: string) {+ const home = join(root, name), dataDir = join(home, ".openmausbot");+ const signIns = {+ claude: join(home, ".claude", ".credentials.json"),+ codex: join(home, ".codex", "auth.json"),+ codexConfig: join(home, ".codex", "config.toml"),+ grok: join(home, ".grok", "auth.json"),+ gemini: join(home, ".gemini", "oauth_creds.json"),+ opencode: join(home, ".local", "share", "opencode", "auth.json"),+ pi: join(home, ".pi", "agent", "auth.json"),+ muse: join(home, ".config", "muse", "auth.json"),+ };+ for (const file of Object.values(signIns)) put(file, `{"token":"${file}"}`);+ const edge = join(edgeCertificateStorage(home), "certificates", "site.key");+ const botFiles = [join(home, ".gitconfig"), join(home, ".ssh", "id_ed25519"), join(home, ".local", "bin", "tool"), join(home, ".claude", "skills", "mine", "SKILL.md")];+ for (const file of [edge, ...botFiles]) put(file);+ const cwd = join(dataDir, "task-workspaces", "bot-a", "thread-1");+ for (const folder of [cwd, join(dataDir, "workspaces", "bot-a")]) mkdirSync(folder, { recursive: true });+ put(join(dataDir, "messages.db"));+ const setup: BoxSetup = { dataDir, home, codeRoots: [], engineRoots: [], bridges: [] };+ const plan = (request: Omit<BoxRequest, "command" | "args" | "cwd"> & { cwd?: string }) => {+ const full: BoxRequest = { command: "engine", args: [], cwd, ...request };+ return planBox(setup, full, full.home ? undefined : signInMasks({ home, dataDir, env: full.env, engine: full.engine }));+ };+ return { home, dataDir, signIns, edge, botFiles, cwd, setup, plan };+}++describe.skipIf(checkoutUnderTmp)("a bot box on a My Cloud keeps only its own engine account's sign-in", () => {+ const cloud = volume("my-cloud");+ const { signIns, home, dataDir } = cloud;++ it("a Claude bot on the default account keeps its login and no other engine's, nor the data folder or the edge's keys", () => {+ const plan = cloud.plan({ env: { HOME: home }, engine: "claudeAgent" });+ expect(visibleInBox(plan, signIns.claude)).toBe("rw");+ for (const other of [signIns.codex, signIns.codexConfig, signIns.grok, signIns.gemini, signIns.opencode, signIns.pi]) expect(visibleInBox(plan, other), other).toBe("none");+ expect(visibleInBox(plan, join(dataDir, "messages.db"))).toBe("none");+ expect(visibleInBox(plan, cloud.edge)).toBe("none");+ });++ it("a Codex bot on the default account keeps that login through MausBot's own Codex home, and no other engine's", () => {+ const own = join(dataDir, "providers", "codex-own", "h1", "codex");+ expect(linkSharedCodexHome(join(home, ".codex"), own, "person")).toBe(true);+ const env = { HOME: home, CODEX_HOME: own };+ const plan = cloud.plan({ env, engine: "codex" });+ expect(visibleInBox(plan, join(own, "auth.json"))).toBe("rw");+ expect(visibleInBox(plan, signIns.codex), "the link's target, which the engine reads and refreshes").toBe("rw");+ expect(visibleInBox(plan, signIns.codexConfig)).toBe("rw");+ for (const other of [signIns.claude, signIns.grok, signIns.gemini]) expect(visibleInBox(plan, other), other).toBe("none");+ });++ it("a Codex bot on an added ChatGPT account keeps only that account's login, never the default account's", () => {+ const work = chatgptAccountHome("chatgpt-work", dataDir), spare = chatgptAccountHome("chatgpt-spare", dataDir);+ for (const account of [work, spare]) {+ linkSharedCodexHome(join(home, ".codex"), account, "own");+ put(join(account, "auth.json"), `{"account":"${account}"}`);+ }+ const env = boxEnvironment({ HOME: home, CODEX_HOME: work, OMB_DATA_DIR: dataDir });+ expect(env).toEqual({ HOME: home, CODEX_HOME: work });+ const plan = cloud.plan({ env, engine: "codex" });+ expect(visibleInBox(plan, join(work, "auth.json"))).toBe("rw");+ expect(visibleInBox(plan, signIns.codex), "the default account's login").toBe("none");+ expect(visibleInBox(plan, join(spare, "auth.json")), "another added account's login").toBe("none");+ expect(visibleInBox(plan, signIns.codexConfig), "the person's Codex setup, linked into the account's home").toBe("rw");+ expect(visibleInBox(plan, signIns.claude)).toBe("none");+ });++ it("a process of no signed-in engine (a shell step, an MCP server) keeps no sign-in at all", () => {+ for (const plan of [cloud.plan({ env: { HOME: home } }), cloud.plan({ env: { HOME: home }, engine: "cursorAgent" })]) {+ for (const file of Object.values(signIns)) expect(visibleInBox(plan, file), file).toBe("none");+ }+ });++ it("follows a link only to the same engine's file in HOME, never to another engine's sign-in a bot planted", () => {+ const planted = volume("planted-cloud");+ rmSync(planted.signIns.pi);+ symlinkSync(planted.signIns.codex, planted.signIns.pi);+ const own = join(planted.dataDir, "providers", "codex-own", "h2", "codex");+ mkdirSync(own, { recursive: true });+ symlinkSync(planted.signIns.claude, join(own, "auth.json"));+ const pi = planted.plan({ env: { HOME: planted.home }, engine: "piAgent" });+ expect(visibleInBox(pi, planted.signIns.codex)).toBe("none");+ const codex = planted.plan({ env: { HOME: planted.home, CODEX_HOME: own }, engine: "codex" });+ expect(visibleInBox(codex, planted.signIns.claude)).toBe("none");+ });++ it("keeps an engine's own login reached through a linked folder, and masks under HOME as the box has it when HOME is a link", () => {+ const linked = volume("linked-cloud");+ const real = join(linked.home, "dotfiles", "config");+ mkdirSync(dirname(real), { recursive: true });+ renameSync(join(linked.home, ".config"), real);+ symlinkSync(real, join(linked.home, ".config"));+ const muse = linked.plan({ env: { HOME: linked.home }, engine: "museCode" });+ expect(visibleInBox(muse, join(real, "muse", "auth.json"))).toBe("rw");+ expect(visibleInBox(linked.plan({ env: { HOME: linked.home }, engine: "claudeAgent" }), join(real, "muse", "auth.json"))).toBe("none");++ const alias = join(root, "home-link");+ symlinkSync(cloud.home, alias);+ const masks = signInMasks({ home: alias, dataDir: join(alias, ".openmausbot"), env: { HOME: alias }, engine: "claudeAgent" });+ expect(masks.masked).toContain(join(alias, ".codex", "auth.json"));+ expect(masks.hidden).toEqual([join(alias, ".omb-edge")]);+ const plan = planBox({ ...cloud.setup, home: alias, dataDir: join(alias, ".openmausbot") }, { command: "claude", args: [], env: { HOME: alias }, engine: "claudeAgent" }, masks);+ expect(visibleInBox(plan, join(alias, ".codex", "auth.json"))).toBe("none");+ expect(visibleInBox(plan, join(alias, ".omb-edge", "caddy", "certificates", "site.key"))).toBe("none");+ expect(visibleInBox(plan, join(alias, ".claude", ".credentials.json"))).toBe("rw");+ });++ it("makes every folder between HOME and a sign-in a mount point, before the data folder's line, so none can be renamed away", () => {+ const plan = cloud.plan({ env: { HOME: home }, engine: "claudeAgent" });+ const binds = plan.mounts.flatMap((mount, index) => (mount.kind === "bind" && mount.source === mount.target ? [[mount.target, index] as const] : []));+ const at = new Map(binds);+ for (const folder of [".claude", ".codex", ".local", ".local/share", ".local/share/opencode", ".config", ".config/muse", ".pi", ".pi/agent"]) expect(at.has(join(home, folder)), folder).toBe(true);+ expect(at.get(join(home, ".local"))!).toBeLessThan(at.get(join(home, ".local", "share"))!);+ const dataLine = plan.mounts.findIndex((mount) => mount.kind === "tmpfs" && mount.target === dataDir);+ expect(at.get(join(home, ".claude"))!).toBeLessThan(dataLine);+ expect(visibleInBox(plan, join(home, ".local", "share", "other-tool", "state"))).toBe("rw");+ });++ it("a Muse bot keeps its login in HOME even where the spawn names another config folder, as its sign-in check does", () => {+ const plan = cloud.plan({ env: { HOME: home, XDG_CONFIG_HOME: join(root, "elsewhere") }, engine: "museCode" });+ expect(visibleInBox(plan, signIns.muse)).toBe("rw");+ expect(visibleInBox(plan, signIns.claude)).toBe("none");+ });++ it("masks stay last, so a path a driver puts back read-write never shows another engine's sign-in", () => {+ const plan = cloud.plan({ env: { HOME: home, CODEX_HOME: join(home, ".codex") }, engine: "claudeAgent", rw: [join(home, ".codex")], ro: [signIns.grok] });+ expect(visibleInBox(plan, signIns.codex)).toBe("none");+ expect(visibleInBox(plan, signIns.grok)).toBe("none");+ });++ it("keeps what bots made in HOME and their own folders where they were", () => {+ const plan = cloud.plan({ env: { HOME: home }, engine: "claudeAgent" });+ for (const file of cloud.botFiles) expect(visibleInBox(plan, file), file).toBe("rw");+ expect(visibleInBox(plan, cloud.cwd)).toBe("rw");+ expect(visibleInBox(plan, join(dataDir, "workspaces", "bot-a", "MEMORY.md"))).toBe("rw");+ });++ it("masks only files that are there, so the box never makes an empty sign-in on the server's disk", () => {+ const bare = volume("bare-cloud");+ rmSync(join(bare.home, ".grok"), { recursive: true });+ rmSync(join(bare.home, ".omb-edge"), { recursive: true });+ const args = bwrapArgs(bare.plan({ env: { HOME: bare.home }, engine: "claudeAgent" }));+ expect(args.join(" ")).not.toContain(join(bare.home, ".grok"));+ expect(args.join(" ")).not.toContain(join(bare.home, ".omb-edge"));+ expect(args.join(" ")).toContain(`--ro-bind /dev/null ${bare.signIns.codex}`);+ expect(existsSync(join(bare.home, ".grok"))).toBe(false);+ });++ it("the box runner masks for a spawn in the server's HOME and leaves a Team Cloud audience's home as it plans it", () => {+ const runner = new BoxRunner({ bwrap: "/usr/bin/bwrap", bridge: { socat: null, bridgeScript: "/bridge.js", node: "/node" }, setup: cloud.setup, denyEnv: new Set() });+ const mine = runner.wrap({ command: "claude", args: [], cwd: cloud.cwd, env: { HOME: home }, engine: "claudeAgent" });+ expect(visibleInBox(mine.plan, signIns.codex)).toBe("none");+ expect(visibleInBox(mine.plan, signIns.claude)).toBe("rw");++ const audience = audienceHome(dataDir, "team");+ const homed = homedSpawn({ HOME: home }, { dataDir, serverHome: home, home: audience });+ const team: BoxRequest = { command: "claude", args: [], cwd: cloud.cwd, env: homed.env, home: homed.home, shared: homed.shared };+ const teamPlan = runner.wrap({ ...team, engine: "claudeAgent" }).plan;+ expect(teamPlan).toEqual(planBox(cloud.setup, team));+ expect(teamPlan.mounts.some((mount) => mount.kind === "mask")).toBe(false);+ });++ it("names every engine by a driver that exists, and the edge's certificate folder as the server's alone", () => {+ const kinds = new Set(BUILT_IN_DRIVERS.map((driver) => driver.driverKind));+ for (const folder of ENGINE_FOLDERS) for (const kind of folder.drivers) expect(kinds.has(kind), kind).toBe(true);+ expect(signInMasks({ home, dataDir, env: { HOME: home } }).hidden).toEqual([join(home, ".omb-edge")]);+ expect(readdirSync(home)).toContain(".omb-edge");+ });++ it("every boxed spawn of an engine that signs in in HOME names its engine, or its bots would lose their login", () => {+ const files = ["claude.ts", "claude-keepwarm.ts", "codex.ts", "pi.ts", "muse-code.ts", "acp/core.ts", "acp/browser-auth.ts", "acp/opencode-probe.ts", "acp/opencode-go.ts", "acp/deepseek.ts"];+ let checked = 0;+ for (const file of files) {+ const source = readFileSync(join(import.meta.dirname, "..", "drivers", file), "utf8");+ for (const match of source.matchAll(/\b(?:spawnCli|execCliBoxed)\(/g)) {+ let depth = 0, end = match.index;+ for (; end < source.length; end++) {+ if (source[end] === "(") depth++;+ else if (source[end] === ")" && --depth === 0) break;+ }+ const call = source.slice(match.index, end);+ if (!/"bot"|\bowner\)|box:/.test(call)) continue;+ checked++;+ expect(call, `${file}: ${call.slice(0, 80)}`).toMatch(/\bengine[:,]/);+ }+ }+ expect(checked).toBeGreaterThanOrEqual(12);+ expect(readFileSync(join(import.meta.dirname, "..", "drivers", "claude-keepwarm.ts"), "utf8")).toMatch(/box: \{ ro: \[dir\], engine: "claudeAgent" \}/);+ });+});diff --git a/server/bot-box/sign-in-masks.ts b/server/bot-box/sign-in-masks.tsnew file mode 100644index 0000000000..a5efd0c6cd--- /dev/null+++ b/server/bot-box/sign-in-masks.ts@@ -0,0 +1,70 @@+// Which engine sign-ins in the server's HOME a bot box keeps. A box that has the server's HOME (a My Cloud; on a Team Cloud+// a turn's box has its audience's engine home instead) keeps only the sign-in of the engine account its process runs:+// every other engine's and every other account's sign-in file there is masked, and so are the folders only the server+// reads. Security: a spawn that names no engine keeps none.+import { realpathSync, statSync } from "node:fs";+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";++import { ENGINE_FOLDERS } from "../engine-homes/layout.ts";+import { under, type SignInMasks } from "./plan.ts";++/** Folders in the server's HOME only the server reads: the edge's TLS certificate and ACME account. */+export const SERVER_ONLY_HOME_FOLDERS = [".omb-edge"] as const;++export interface SignInFiles {+ realpath(path: string): string | null;+ isFile(path: string): boolean;+ isDirectory(path: string): boolean;+}++const files: SignInFiles = {+ realpath: (path) => { try { return realpathSync(path); } catch { return null; } },+ isFile: (path) => { try { return statSync(path).isFile(); } catch { return false; } },+ isDirectory: (path) => { try { return statSync(path).isDirectory(); } catch { return false; } },+};++/** Only paths that exist now: bubblewrap makes a missing mount target, which in a read-write HOME would leave an empty+ * sign-in file on the server's own disk. Real paths, so a link into HOME is masked where it points; returned under HOME+ * as the box has it. */+export function signInMasks(input: { home: string; dataDir: string; env: Record<string, string | undefined>; engine?: string | null }, fs: SignInFiles = files): SignInMasks {+ const home = fs.realpath(input.home) ?? resolve(input.home), dataDir = fs.realpath(input.dataDir) ?? resolve(input.dataDir);+ const spawnHome = input.env.HOME && isAbsolute(input.env.HOME) ? input.env.HOME : input.home;+ const lexical = (path: string) => under(resolve(path), resolve(input.home)) ? join(home, relative(resolve(input.home), resolve(path))) : resolve(path);+ const inHome = (path: string) => under(path, home) && !under(path, dataDir);+ const defaults = ENGINE_FOLDERS.flatMap((folder) => folder.shared.map((name) => join(home, folder.home, name)));+ const ownFiles = new Set<string>(), aliases = new Set<string>();+ for (const folder of ENGINE_FOLDERS) {+ if (!input.engine || !folder.drivers.includes(input.engine)) continue;+ const named = folder.env ? input.env[folder.env] : undefined;+ const base = named && isAbsolute(named) ? named : join(spawnHome, folder.home);+ for (const name of folder.shared) {+ const path = join(base, name), real = fs.realpath(path), fallback = join(home, folder.home, name);+ // Security: the folders are a bot's to write, so a link is followed only to this same file in HOME (MausBot's own+ // engine folder linking the person's login) or through a linked folder, never to another engine's sign-in.+ const throughFolder = real !== null && real === join(fs.realpath(dirname(path)) ?? dirname(path), basename(path)) && inHome(real) && !defaults.includes(real);+ if (real && (real === lexical(path) || real === fallback || throughFolder)) { ownFiles.add(real); aliases.add(lexical(path)); }+ // The driver's own sign-in check also takes the HOME default where the folder is a shared XDG one.+ if (folder.env?.startsWith("XDG_") && fs.realpath(fallback) === fallback) ownFiles.add(fallback);+ }+ }+ const own = [...ownFiles].filter((path) => inHome(path) && fs.isFile(path));+ const masked: string[] = [];+ for (const alias of defaults) {+ const real = fs.realpath(alias);+ if (!real || !inHome(real) || !fs.isFile(real)) continue;+ aliases.add(alias);+ if (!ownFiles.has(real) && !masked.includes(real)) masked.push(real);+ }+ const hidden = SERVER_ONLY_HOME_FOLDERS.map((name) => fs.realpath(join(home, name))).filter((path): path is string => path !== null && inHome(path) && fs.isDirectory(path));+ // Security: every folder between HOME and a sign-in, and between HOME and each name it is reached by, is a mount point+ // too, so a bot cannot rename one away and leave the file at a path the next box does not mask.+ const folders = new Set<string>();+ for (const file of [...own, ...masked, ...[...aliases].filter(inHome)]) {+ for (let folder = dirname(file); folder !== home && under(folder, home); folder = dirname(folder)) if (fs.isDirectory(folder)) folders.add(folder);+ }+ const inBox = (path: string) => join(resolve(input.home), relative(home, path));+ return {+ folders: [...folders].sort((a, b) => a.split(sep).length - b.split(sep).length || a.localeCompare(b)).map(inBox),+ own: own.map(inBox), masked: masked.map(inBox), hidden: hidden.map(inBox),+ };+}diff --git a/server/drivers/acp/browser-auth.ts b/server/drivers/acp/browser-auth.tsindex a5b8f33847..1b28ab6ae3 100644--- a/server/drivers/acp/browser-auth.ts+++ b/server/drivers/acp/browser-auth.ts@@ -42,6 +42,8 @@ export interface AcpBrowserSignInSpec {export interface AcpBrowserAuthOptions {cli: string;+ /** The driver kind, whose sign-in in the server's HOME the boxed sign-in may write. */+ engine?: string;/** The engine's own session spawn args, so the sign-in runs with a turn's environment. */sessionArgs?: (env: Env) => readonly string[];cwd?: string;@@ -132,7 +134,7 @@ export class AcpBrowserAuth {const extra = (this.spec.args ?? []).map((arg) => typeof arg === "function" ? arg(env) : arg).filter((arg): arg is string => arg !== undefined);const sessionArgs = this.options.sessionArgs ? this.options.sessionArgs(env) : [];const argv = [this.options.cli, ...extra, ...sessionArgs];- child = spawnCli(argv[0], argv.slice(1), { cwd: this.options.cwd, env, stdio: ["pipe", "pipe", "pipe"] }, "bot");+ child = spawnCli(argv[0], argv.slice(1), { cwd: this.options.cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { engine: this.options.engine } }, "bot");} catch (error) {spawnFail(error instanceof Error && typeof (error as { code?: unknown }).code === "string"? String((error as { code?: unknown }).code) : undefined);diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex c0393b079e..eadc000fb1 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -372,7 +372,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>}const startup = startupRefresh({ enabled: support.modelListStandsIn === true, room: roomForReadBeside, pending: startupModelRefresh, saved: () => startupSaved, catalog: () => catalog.models, normalize: support.normalizeSessionSelection });const deviceSignIn = support.deviceSignIn ? new DeviceAuthController(support.deviceSignIn, { cli: config.cli, environment: () => childEnv(), onAuthenticated: refreshModels }) : null;- const browserSignIn = support.browserSignIn ? new AcpBrowserAuth(support.browserSignIn, { cli: config.cli, environment: () => childEnv(), onAuthenticated: refreshModels }) : null;+ const browserSignIn = support.browserSignIn ? new AcpBrowserAuth(support.browserSignIn, { cli: config.cli, engine: DRIVER_KIND, environment: () => childEnv(), onAuthenticated: refreshModels }) : null;const listeners = new Set<RuntimeEventListener>();let disposing = false;const requireRunning = () => {@@ -539,7 +539,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>hostKey: string | null): AcpHost => {const running = sharedHost(hostKey, threadId, cwd);if (running) return running;- const child = spawnCli(launch.command, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv: instanceEnvNames(input.environment, env), botThreads: hostKey !== null, ro: launch.ro } }, "bot");+ const child = spawnCli(launch.command, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv: instanceEnvNames(input.environment, env), botThreads: hostKey !== null, ro: launch.ro, engine: DRIVER_KIND } }, "bot");const host = new AcpHost(child, hostKey, { source: SOURCE, logMessage: nativeLogMessage, unrouted: refuse, promptCompletion: support.promptCompletion });hosts.add(host); signIn.watch(host); if (support.stderrFailure) watchStderrFailure(host, support.stderrFailure);child.once("close", () => hosts.delete(host));@@ -1448,7 +1448,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>const spawnEnv = launch.env ?? env;return await runAcpOneShot({displayName: support.displayName,- spawn: (...args) => { const child = spawnCli(...args); support.processStarted?.(child, instanceId); return child; }, kill: killCliTree, box: { allowEnv: instanceEnvNames(input.environment, spawnEnv), ro: launch.ro },+ spawn: (...args) => { const child = spawnCli(...args); support.processStarted?.(child, instanceId); return child; }, kill: killCliTree, box: { allowEnv: instanceEnvNames(input.environment, spawnEnv), ro: launch.ro, engine: DRIVER_KIND },command: launch.command,argv: [...(launch.args ?? []), ...support.spawnArgs(turnConfig, turn)],env: spawnEnv,diff --git a/server/drivers/acp/deepseek.ts b/server/drivers/acp/deepseek.tsindex b315ba7e55..d5e2d50b1e 100644--- a/server/drivers/acp/deepseek.ts+++ b/server/drivers/acp/deepseek.ts@@ -201,7 +201,7 @@ export function fetchDeepSeekCatalog(try {// Security: while the bot box is on, dsh runs in it, as a bot's turn does: it reads ~/.dsh, which a bot can write.const resolved = resolveCli(cli, ["--profile", "acp"], env as NodeJS.ProcessEnv);- child = spawnCli(resolved.command, resolved.args, { stdio: ["pipe", "pipe", "ignore"], env: { ...env, ...resolved.env }, box: { allowEnv } });+ child = spawnCli(resolved.command, resolved.args, { stdio: ["pipe", "pipe", "ignore"], env: { ...env, ...resolved.env }, box: { allowEnv, engine: "deepseekAgent" } });} catch (error) {return reject(error instanceof Error ? error : new Error(String(error)));}diff --git a/server/drivers/acp/opencode-go.ts b/server/drivers/acp/opencode-go.tsindex d1bdd221b7..6668f7f774 100644--- a/server/drivers/acp/opencode-go.ts+++ b/server/drivers/acp/opencode-go.ts@@ -196,7 +196,7 @@ function runOpenCodeModelsVerbose(execCliBoxed(cli,["models", "--verbose"],- { timeout: 20_000, maxBuffer: 8 * 1024 * 1024, env: environment, box: { allowEnv } },+ { timeout: 20_000, maxBuffer: 8 * 1024 * 1024, env: environment, box: { allowEnv, engine: "opencodeGo" } },(error, stdout, stderr) => {if (error) {reject(Object.assign(new Error(stderr?.trim() || error.message, { cause: error }), {@@ -218,7 +218,7 @@ const MODELS_REFRESH_TIMEOUT_MS = 75_000;function refreshOpenCodeModelCache(cli: string, environment: Record<string, string | undefined>, allowEnv: readonly string[]): Promise<boolean> {return new Promise((resolve) => {- execCliBoxed(cli, ["models", "--refresh"], { timeout: MODELS_REFRESH_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, env: environment, box: { allowEnv } }, (error) => resolve(!error));+ execCliBoxed(cli, ["models", "--refresh"], { timeout: MODELS_REFRESH_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, env: environment, box: { allowEnv, engine: "opencodeGo" } }, (error) => resolve(!error));});}diff --git a/server/drivers/acp/opencode-probe.ts b/server/drivers/acp/opencode-probe.tsindex 165c21045f..e090135773 100644--- a/server/drivers/acp/opencode-probe.ts+++ b/server/drivers/acp/opencode-probe.ts@@ -173,7 +173,7 @@ export async function probeOpenCodeSession(return new Promise((resolve, reject) => {let child: ReturnType<typeof spawnCli>;try {- child = spawnCli(cli, ["acp"], { cwd, env: environment, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv } });+ child = spawnCli(cli, ["acp"], { cwd, env: environment, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv, engine: "opencodeGo" } });} catch (error) {reject(error);return;diff --git a/server/drivers/claude-keepwarm.ts b/server/drivers/claude-keepwarm.tsindex aad8f28a10..08539ab19a 100644--- a/server/drivers/claude-keepwarm.ts+++ b/server/drivers/claude-keepwarm.ts@@ -123,7 +123,7 @@ export function parseKeepWarmResult(stdout: string, stderr: string, code: number* by owner: a fork is not the bot's engine, so nothing tracks it as one. `dir` holds the fork's private files; the deny* hook in it is named only inside the settings file, so the folder is put in the box, read-only. */export function forkSpawnOptions(contract: Pick<KeepWarmContract, "cwd">, env: NodeJS.ProcessEnv, dir: string): CliSpawnOptions {- return { cwd: contract.cwd, env, stdio: ["pipe", "pipe", "pipe"], engineHome: true, botWork: true, box: { ro: [dir] } };+ return { cwd: contract.cwd, env, stdio: ["pipe", "pipe", "pipe"], engineHome: true, botWork: true, box: { ro: [dir], engine: "claudeAgent" } };}/** Never throws. The credentialed MCP config, settings and prompt live in a 0700 temp dir removed at exit. */diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 740d6956be..3123089f45 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -1294,7 +1294,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {if (spare && (taken() || ownHttp)) { cleanupUnownedLaunch(); return { turnId: "" }; }let child: ReturnType<typeof spawnCli>;try {- child = spawnCli(cliToLaunch(config.cli, launchCli), args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { ...(broker ? { rw: [broker.socketPath] } : {}), ...(hookTokenPath ? { ro: [dirname(hookTokenPath)] } : {}) } }, "bot");+ child = spawnCli(cliToLaunch(config.cli, launchCli), args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { engine: DRIVER_KIND, ...(broker ? { rw: [broker.socketPath] } : {}), ...(hookTokenPath ? { ro: [dirname(hookTokenPath)] } : {}) } }, "bot");} catch (error) {cleanupUnownedLaunch();throw error;diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex 3d0a2cb068..2f946185e8 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -1459,7 +1459,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)const plain = { command: "python3", args: ["todo.py"], env: {} };await instance.adapter.sendTurn({ threadId: "t-box-no-env", text: "go", integrations: { custom: { plain } } });await recorder.until((event) => event.type === "turn.completed" && event.threadId === "t-box-no-env");- expect(appServer()).not.toHaveProperty("box");+ expect(appServer()?.box).toEqual({ engine: "codex" });} finally {spawnSpy.mockRestore();}@@ -1701,7 +1701,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)expect(await recorder.until((event) => event.type === "turn.completed" && event.threadId === "plan-box")).toMatchObject({ ok: true });const appServer = spawns.find(([, args]) => args.includes("app-server"))?.[2];expect(appServer?.env?.OMB_CODEX_AUTH_SOCKET).toBeTruthy();- expect(appServer?.box).toEqual({ rw: [appServer!.env!.OMB_CODEX_AUTH_SOCKET] });+ expect(appServer?.box).toEqual({ engine: "codex", rw: [appServer!.env!.OMB_CODEX_AUTH_SOCKET] });} finally {spawnSpy.mockRestore();}diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 6c6be62c5d..25a41b96b0 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -551,7 +551,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {const connection = reused?.connection ?? new CodexConnection(spawnHoldingSlot(releaseSlot, () => spawnCli(...codexLaunch(config.cli, appServerArgs), {cwd: turn.cwd ?? homedir(),env,- stdio: ["pipe", "pipe", "pipe"], ...(authBridge ? { box: { ...customBox.box, rw: [authBridge.socketPath] } } : customBox),+ stdio: ["pipe", "pipe", "pipe"], box: { ...customBox.box, engine: DRIVER_KIND, ...(authBridge ? { rw: [authBridge.socketPath] } : {}) },}, "bot")));const child = connection.child;diff --git a/server/drivers/muse-code.ts b/server/drivers/muse-code.tsindex 5219f8ce9b..3e9d8c1d35 100644--- a/server/drivers/muse-code.ts+++ b/server/drivers/muse-code.ts@@ -293,7 +293,7 @@ export const MuseCodeDriver: ProviderDriver<MuseConfig> = {const { command, args: argv } = launch(args);const env = childEnv();// Security: the model list runs in the bot box too while it is on: Muse reads its settings from a HOME a bot can write.- const child = spawnCli(command, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv: instanceEnvNames(input.environment, env) } }, owner);+ const child = spawnCli(command, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv: instanceEnvNames(input.environment, env), engine: DRIVER_KIND } }, owner);let spawnError: NodeJS.ErrnoException | undefined;child.once("error", (error) => { spawnError = error; });const exited = new Promise<void>((resolve) => child.once("close", () => resolve()));diff --git a/server/drivers/pi-session-spawn.test.ts b/server/drivers/pi-session-spawn.test.tsindex 0725f834b9..aec0ce77b3 100644--- a/server/drivers/pi-session-spawn.test.ts+++ b/server/drivers/pi-session-spawn.test.ts@@ -44,7 +44,7 @@ describe("Pi session spawn setup", () => {const started = recorder.events.find((event) => event.type === "session.started" && event.turnId === turnId);if (started?.type !== "session.started" || !started.sessionId) throw new Error("missing session file");const call = spawned.mock.calls.slice(before).find(([, args]) => args.includes("--session-dir"))!;- expect(call[2]!.box).toEqual({ rw: [dir, expect.stringContaining("omb-pi-mcp-")] });+ expect(call[2]!.box).toEqual({ rw: [dir, expect.stringContaining("omb-pi-mcp-")], engine: "piAgent" });const setup = { dataDir: DATA_DIR, home: join(DATA_DIR, ".."), codeRoots: [], engineRoots: [], bridges: [] };const request = { command: cli, args: call[1], env: {}, audience: { teamReadOnly: audience !== "team" } };expect(visibleInBox(planBox(setup, request), dir)).toBe("none");diff --git a/server/drivers/pi.ts b/server/drivers/pi.tsindex f6f24a2b78..e97552ecad 100644--- a/server/drivers/pi.ts+++ b/server/drivers/pi.ts@@ -197,7 +197,7 @@ export async function fetchPiModels(env: Record<string, string | undefined>,allowEnv: readonly string[] = [],): Promise<ModelCatalog> {- const child = spawnCli(cli, PI_ARGS, { stdio: ["pipe", "pipe", "pipe"], env, box: { allowEnv } });+ const child = spawnCli(cli, PI_ARGS, { stdio: ["pipe", "pipe", "pipe"], env, box: { allowEnv, engine: DRIVER_KIND } });return new Promise((resolve) => {let done = false;const fallbackDefault = readPiDefaultModel(env);@@ -237,7 +237,7 @@ export async function updatePiModelCatalog(allowEnv: readonly string[] = [],): Promise<boolean> {return new Promise((resolve) => {- execCliBoxed(cli, PI_MODEL_UPDATE_ARGS, { env, timeout: 60_000, maxBuffer: 1024 * 1024, box: { allowEnv } }, (error) => resolve(!error));+ execCliBoxed(cli, PI_MODEL_UPDATE_ARGS, { env, timeout: 60_000, maxBuffer: 1024 * 1024, box: { allowEnv, engine: DRIVER_KIND } }, (error) => resolve(!error));});}@@ -422,7 +422,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {return spawnCli(config.cli, childArgs, {stdio: ["pipe", "pipe", "pipe"],cwd: turn.cwd,- box: { rw: [sessionDir, mcpTempDir] },+ box: { rw: [sessionDir, mcpTempDir], engine: DRIVER_KIND },env: piEnvironment({ ...turnEnv, OMB_MCP_CONFIG: join(mcpTempDir, "mcp.json") }),}, "bot");} catch (err) {diff --git a/server/engine-homes/layout.ts b/server/engine-homes/layout.tsindex 13ade75133..3a0c2b8eec 100644--- a/server/engine-homes/layout.ts+++ b/server/engine-homes/layout.ts@@ -45,6 +45,8 @@ export interface EngineFolder {env?: string;home: string;shared: readonly string[];+ /** The driver kinds whose engine signs in here; a bot box of any other engine never reads these files. */+ drivers: readonly string[];}/** kimi-code 2.4.1 (resolveKimiCodeOAuthKey) names a kimi.ai sign-in after its region's OAuth host and API address. */@@ -53,16 +55,16 @@ const KIMI_AI_SIGN_IN = `credentials/kimi-code-env-${createHash("sha256")/** File names as each engine's sign-in keeps them (the drivers' own sign-in checks read the same ones). */export const ENGINE_FOLDERS: readonly EngineFolder[] = [- { env: "CLAUDE_CONFIG_DIR", home: ".claude", shared: [".credentials.json"] },- { env: "CODEX_HOME", home: ".codex", shared: ["auth.json", "config.toml"] },- { env: "GROK_HOME", home: ".grok", shared: ["auth.json", "config.toml"] },- { env: "KIMI_CODE_HOME", home: ".kimi-code", shared: ["credentials/kimi-code.json", KIMI_AI_SIGN_IN, "config.toml"] },- { env: "DSH_HOME", home: ".dsh", shared: [".credentials.yaml", ".env"] },- { env: "FACTORY_HOME_OVERRIDE", home: "", shared: [".factory/auth.v2.file", ".factory/auth.v2.keyring", ".factory/settings.json"] },- { env: "XDG_CONFIG_HOME", home: ".config", shared: ["muse/auth.json"] },- { env: "XDG_DATA_HOME", home: ".local/share", shared: ["opencode/auth.json"] },- { home: ".gemini", shared: ["oauth_creds.json", "google_accounts.json", "settings.json"] },- { env: "PI_CODING_AGENT_DIR", home: ".pi/agent", shared: ["auth.json"] },+ { env: "CLAUDE_CONFIG_DIR", home: ".claude", shared: [".credentials.json"], drivers: ["claudeAgent"] },+ { env: "CODEX_HOME", home: ".codex", shared: ["auth.json", "config.toml"], drivers: ["codex"] },+ { env: "GROK_HOME", home: ".grok", shared: ["auth.json", "config.toml"], drivers: ["grokAgent"] },+ { env: "KIMI_CODE_HOME", home: ".kimi-code", shared: ["credentials/kimi-code.json", KIMI_AI_SIGN_IN, "config.toml"], drivers: ["kimiAgent"] },+ { env: "DSH_HOME", home: ".dsh", shared: [".credentials.yaml", ".env"], drivers: ["deepseekAgent"] },+ { env: "FACTORY_HOME_OVERRIDE", home: "", shared: [".factory/auth.v2.file", ".factory/auth.v2.keyring", ".factory/settings.json"], drivers: ["droidAgent"] },+ { env: "XDG_CONFIG_HOME", home: ".config", shared: ["muse/auth.json"], drivers: ["museCode"] },+ { env: "XDG_DATA_HOME", home: ".local/share", shared: ["opencode/auth.json"], drivers: ["opencodeGo"] },+ { home: ".gemini", shared: ["oauth_creds.json", "google_accounts.json", "settings.json"], drivers: ["geminiAgent"] },+ { env: "PI_CODING_AGENT_DIR", home: ".pi/agent", shared: ["auth.json"], drivers: ["piAgent"] },];/** Folder variables that move with HOME besides those above. */diff --git a/server/procs.ts b/server/procs.tsindex 4807d1f2ef..af22df4db1 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -331,7 +331,7 @@ export type CliOwner = "bot" | "openmausbot";/** The bot box (server/bot-box): a `bot` spawn runs in it where it is on; `box` asks for one for another owner, with more* paths or the host's network, and `false` keeps a spawn out of it. */export interface BoxSpawnOptions {- box?: boolean | Pick<BoxRequest, "rw" | "ro" | "net" | "botId" | "botThreads" | "allowEnv" | "relay" | "configured">;+ box?: boolean | Pick<BoxRequest, "rw" | "ro" | "net" | "botId" | "botThreads" | "allowEnv" | "relay" | "configured" | "engine">;/** On a Team Cloud, runs in its conversation's engine home though it is not a bot's engine (a keep-warm ping). */engineHome?: boolean;/** A bot's own work that is not its engine (its browser, a helper engine): memory runs out on it first, as on a `bot`