Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team Cloud: a private chat's box can't write team files or read others' conversations (#6343)
Milind Sonia9d3b9ea2aea
diff --git a/docs/bot-box.md b/docs/bot-box.mdindex fab626b4dd..df770d51e9 100644--- a/docs/bot-box.md+++ b/docs/bot-box.md@@ -12,7 +12,7 @@ its database, its settings, other bots' folders and other turns' processes are n| `/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)) || 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 |+| 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 || private `/tmp`, `/var/tmp`, `/run`, `/dev`, `/proc` | Its own PID namespace: other turns' processes do not exist for it || `/sys/devices/system/cpu/possible` and `online`, read-only; nothing else of `/sys` | The machine's CPU count. Programs built with TCMalloc (Google's Antigravity runtime) stop themselves at start without it (exit 134) |diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex e15cfc4efc..ce7ca2bef7 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -443,6 +443,27 @@ work, `session_search` (memory of the layer and the team's; conversations the tuturn's layer folder back read-write for that conversation's boxes only (`botBox.lend`). Member layers are siblingfolders of the bot's own, never inside it, so no other turn of that bot can read them.+**In the bot box.** The box is where the rule holds against a bot with a shell (`server/host/team-box-scope.ts`, which+the Team Cloud host registers with the box; `BoxAudience` in `server/bot-box/plan.ts`). It learns each spawn's+conversation from its working folder or, for one that runs elsewhere (a room's turn), from the conversation its engine+home runs in, and:++- **A turn that is not the team's** (a member's private chat, a conversation shared with one person, a room) has the+ bot's own folder (`workspaces/<bot>`: the team's MEMORY.md, `memory/`, `skills/`) **read-only**, bound after every+ read-write line so nothing the turn is lent makes it writable. Its own layer stays read-write (`botBox.lend`), and so+ does its conversation folder. A write to the team's folder fails with *Read-only file system*; the turn goes on, and+ its system prompt says so beforehand (*"Your shared folder (…) holds Acme's notes and skills: in this conversation they+ are read-only…"*, `sharedNotesPrompt`). A room's turn works in the bot's own folder unless the room has a folder of+ its own: there it can still make files, and only MEMORY.md, `memory/` and `skills/` are read-only.+- **The team's chat** (the bot's main chat, a conversation nobody or a routine opened) writes the bot's own folder as+ before.+- **A process the bot's conversations share** (OpenCode's, `botThreads`) has only the conversation folders, and their+ uploads, whose audience its own may read: its own audience's read-write, the team's read-only, another person's or+ room's not at all. A conversation made after the process started is in no running box, so it gets a process of its+ own (the shared-process key carries the set, `sharedBoxScope`).+- What the server writes for a turn is not the box's: **Save to team memory** (below) and `skill_manage` go through the+ server and keep their own rules.+The same request to one bot from two requesters is answered once only where the same people see both conversations(`shareAnswer`, see `docs/runtime-contract.md`): two bots working for Mira get one answer, while Mira's private worknever gets the answer Ben's got, so each of them is answered on its own.@@ -1026,6 +1047,11 @@ opens the team's page on the Cloud site (`/cloud/team/<id>`), not a chat. Nothin- **Someone invited who never opened the team.** The machine first learns of a member at their first pairing, so untilthen they are in no People list, and nothing says they joined (`team.people`): the Admin sends no roster and no"joined" of its own.+- **The team's folder without a box, and outside a conversation.** Without the bot box a shell in any chat writes the+ bot's own folder and reads every conversation folder, as it reads engine homes (next). A bot's MCP server the server+ starts outside any conversation (a configured server's probe or its app connections) keeps the bot's own folder+ read-write. A room's turn that works in the bot's own folder can still add files beside the team's notes, which every+ turn of that bot can then read.- **Engine homes without a box, and engines outside the list.** Without the bot box (bubblewrap refused, or switchedoff) a shell reaches every file of the server's user, engine homes included; only the box keeps them apart. An enginewhose sign-in file is not named in `engine-homes/layout.ts` starts signed out in every audience's home. Enginesdiff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex 32c1ff7cb8..72f88ee34f 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -87,6 +87,7 @@ export const VITEST_SUBSETS = {"server/cloud-sync.e2e.test.ts","server/cloud-team-asker-owns.e2e.test.ts","server/cloud-team-away.e2e.test.ts",+ "server/cloud-team-box-audience.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-connections.e2e.test.ts","server/cloud-team-conversation-share.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex e6a08732bf..0ba47bb8a0 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -227,6 +227,7 @@ describe("CI outputs", () => {"server/cloud-sync.e2e.test.ts","server/cloud-team-asker-owns.e2e.test.ts","server/cloud-team-away.e2e.test.ts",+ "server/cloud-team-box-audience.e2e.test.ts","server/cloud-team-browser.e2e.test.ts","server/cloud-team-connections.e2e.test.ts","server/cloud-team-conversation-share.e2e.test.ts",diff --git a/server/bot-box/box.ts b/server/bot-box/box.tsindex 61be4bd766..20ec4039a3 100644--- a/server/bot-box/box.ts+++ b/server/bot-box/box.ts@@ -4,7 +4,7 @@// its arguments and its environment go through untouched, so every host that is not a Cloud home behaves as before.import { randomBytes } from "node:crypto";import { closeSync, existsSync, mkdirSync, openSync, rmSync, statSync, writeFileSync } from "node:fs";-import { dirname, join, resolve } from "node:path";+import { dirname, join, relative, resolve, sep } from "node:path";import { engineInstallRoots } from "../engine-roots.ts";import { homeProgramDirs, resetPathCache } from "../env-path.ts";@@ -19,7 +19,7 @@ import { openHarnessGate, type HarnessGate } from "./harness-gate.ts";import { distrustHomePrograms } from "./program-trust.ts";import { procHidepid } from "./hidepid.ts";import { DENIED_SYSCALLS, seccompBytes, seccompSupported } from "./seccomp.ts";-import { RELAY_SOCKET_NAME, boxUploadsDir, bwrapArgs, inBoxSocket, planBox, taskWorkspaceIds, type BoxBridge, type BoxPlan, type BoxRequest, type BoxSetup } from "./plan.ts";+import { RELAY_SOCKET_NAME, TEAM_FOLDER_KEPT, 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";/** The loopback port inside a box that reaches the egress gate. The harness gate sits at the server's own port. */@@ -47,6 +47,10 @@ export interface WrappedSpawn {extraFds: number[];}+/** On a Team Cloud, the audience side of a conversation's boxes (server/host/team-box-scope.ts): null for a conversation+ * it does not place. `sharedProcess`: the box is for a process the bot's conversations share (BoxRequest.botThreads). */+export type BoxAudienceScope = (input: { threadId: string; botId: string | null; sharedProcess: boolean }) => BoxAudience | null;+/** What the box runtime offers the broker's callers: mint a conversation-bound grant (an MCP server's headers). */export interface BoxBroker {port: number;@@ -74,9 +78,29 @@ export class BoxRunner {private readonly options: RunnerOptions;/** Paths a conversation's turns may write besides the bot's own folder (a member's or a room's memory layer on a Team Cloud). */private readonly lent = new Map<string, readonly string[]>();+ private audiences: BoxAudienceScope | null = null;constructor(options: RunnerOptions) { this.options = options; }+ /** A Team Cloud's audience rule for every box from now on; null takes it away. */+ scopeAudiences(scope: BoxAudienceScope | null): void { this.audiences = scope; }++ /** The conversation and bot a spawn is for: its conversation folder's, else the conversation it runs in (a Team+ * Cloud's engine homes say) with the bot whose own folder it works in or names. */+ private conversation(request: BoxRequest): { botId: string | null; threadId: string | null; folder: boolean } {+ const ids = request.cwd ? taskWorkspaceIds(request.cwd, this.options.setup.dataDir) : null;+ if (ids) return { ...ids, folder: true };+ const inWorkspaces = request.cwd ? relative(join(this.options.setup.dataDir, "workspaces"), resolve(request.cwd)).split(sep)[0] : undefined;+ const botId = request.botId ?? (inWorkspaces && /^[A-Za-z0-9_-]{1,128}$/.test(inWorkspaces) ? inWorkspaces : null);+ return { botId, threadId: request.threadId ?? null, folder: false };+ }++ /** What the audience rule gives this box, or null off a team (and for a spawn of no conversation). */+ audienceFor(request: BoxRequest): BoxAudience | null {+ const { botId, threadId, folder } = this.conversation(request);+ return this.audiences && threadId ? this.audiences({ threadId, botId, sharedProcess: Boolean(request.botThreads) && folder }) : null;+ }+get setup(): BoxSetup { return this.options.setup; }/** Lends `rw` paths to every box of this conversation until `lend` is called again with none. */@@ -90,13 +114,21 @@ export class BoxRunner {wrap(given: BoxRequest): WrappedSpawn {const ids = given.cwd ? taskWorkspaceIds(given.cwd, this.options.setup.dataDir) : null;- const lent = ids ? this.lentTo(ids.botId, ids.threadId) : [];+ const { botId, threadId } = this.conversation(given);+ const lent = botId && threadId ? this.lentTo(botId, threadId) : [];+ const audience = this.audienceFor(given);// Made before the box starts, so an upload a later turn adds shows up in a box that is still running.if (ids) try { mkdirSync(boxUploadsDir(this.options.setup.dataDir, ids.botId, ids.threadId), { recursive: true, mode: 0o700 }); } catch (error) {// The bind stays optional, but an upload named later would then be unreadable in this box: say so.console.error(`bot box: could not make the uploads folder, so uploads stay unreadable in this box: ${error instanceof Error ? error.message : String(error)}`);}- const request: BoxRequest = lent.length ? { ...given, rw: [...(given.rw ?? []), ...lent] } : given;+ // A room's turn in the bot's own folder: the team's notes and skills are bound read-only only where they exist, so+ // they are made first, or the turn could make them.+ const team = audience?.teamReadOnly && given.cwd ? teamFolderOf(botId, resolve(given.cwd), this.options.setup.dataDir) : null;+ if (team && under(resolve(given.cwd!), team) && existsSync(team)) {+ for (const name of TEAM_FOLDER_KEPT) if (name !== "MEMORY.md") try { mkdirSync(join(team, name), { recursive: true, mode: 0o700 }); } catch {}+ }+ 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);@@ -209,6 +241,7 @@ export class BotBox {private boxed = 0;private unbrokered = new Set<string>();private started: StartOptions | null = null;+ private audiences: BoxAudienceScope | null = null;/** Detects, and when the box is on opens the gates. Safe to call once; returns what it decided. */async start(options: StartOptions): Promise<BoxDetection> {@@ -240,6 +273,7 @@ export class BotBox {denyEnv: options.denyEnv, seccompFile: this.seccompFile,broker: { port: BOX_BROKER_PORT, mintForProcess: this.credentials.mintForProcess, revoke: this.credentials.revoke },});+ this.runner.scopeAudiences(this.audiences);distrustHomePrograms(options.home, [options.dataDir], ["workspaces", "task-workspaces", "engine-homes"].map((name) => join(options.dataDir, name)));resetPathCache();log(`bot box: on (bubblewrap, ${this.detection.tools.socat ? "socat" : "node"} bridges, credential broker, seccomp ${this.seccompFile ? "on" : "unsupported here"})`);@@ -288,6 +322,16 @@ export class BotBox {return { bwrap: this.detection.tools.bwrap, options: bwrapArgs({ ...plan, mounts }), seccomp };}+ /** On a Team Cloud: the audience rule for every box (server/host/team-box-scope.ts). Kept for a box started later. */+ scopeAudiences(scope: BoxAudienceScope | null): void { this.audiences = scope; this.runner?.scopeAudiences(scope); }++ /** What a process the bot's conversations share is boxed with, as a key: the conversations its box puts back on a+ * Team Cloud, so a conversation made after it started gets a process whose box has its folder. Null elsewhere. */+ sharedThreadsKey(request: Pick<BoxRequest, "cwd" | "threadId">): string | null {+ const threads = this.runner?.audienceFor({ command: "", args: [], env: {}, ...request, botThreads: true })?.threads;+ return threads ? JSON.stringify([threads.rw, threads.ro]) : null;+ }+/** More read-write folders for one conversation's boxes (a memory layer); nothing without a runner. */lend(botId: string, threadId: string, rw: readonly string[]): void { this.runner?.lend(botId, threadId, rw); }diff --git a/server/bot-box/plan.test.ts b/server/bot-box/plan.test.tsindex 13b0f909f0..2e2e401bd9 100644--- a/server/bot-box/plan.test.ts+++ b/server/bot-box/plan.test.ts@@ -2,7 +2,7 @@ import { join } from "node:path";import { describe, expect, it } from "vitest";import { engineInstallRoots } from "../engine-roots.ts";-import { BOX_MUTATIONS, CPU_LIST_FILES, argvPaths, bwrapArgs, planBox, taskWorkspaceIds, visibleInBox, type BoxMutation, type BoxSetup } from "./plan.ts";+import { BOX_MUTATIONS, CPU_LIST_FILES, argvPaths, bwrapArgs, planBox, taskWorkspaceIds, under, visibleInBox, type BoxAudience, type BoxMutation, type BoxRequest, type BoxSetup } from "./plan.ts";const home = "/data";const dataDir = "/data/.openmausbot";@@ -282,6 +282,66 @@ linuxBox("the box plan", () => {expect(flips["share-net"](turn(["share-pid"]))).toBe(false);});+ describe("on a Team Cloud, by the conversation's audience", () => {+ const team = join(dataDir, "workspaces", "bot-a"), miraLayer = join(dataDir, "workspaces", "bot-a--member-p_mira");+ const ask = (audience: BoxAudience, more: Partial<BoxRequest> = {}) => planBox(setup(), { command: "/usr/local/bin/claude", args: [], cwd, env: { HOME: home }, audience, ...more });+ const writesTeamThings = (plan: ReturnType<typeof ask>) => ["MEMORY.md", "memory/2026-11-17.md", "skills/report/SKILL.md", "notes.md"].map((file) => visibleInBox(plan, join(team, file)));++ it("the team's chat writes the bot's own folder, as on any other server", () => {+ const plan = ask({ teamReadOnly: false });+ expect(writesTeamThings(plan)).toEqual(["rw", "rw", "rw", "rw"]);+ expect(visibleInBox(plan, cwd)).toBe("rw");+ });++ it("a member's private chat reads the team's folder but writes only its own folder and its own layer", () => {+ const plan = ask({ teamReadOnly: true }, { rw: [miraLayer] });+ expect(writesTeamThings(plan)).toEqual(["ro", "ro", "ro", "ro"]);+ expect(visibleInBox(plan, join(miraLayer, "MEMORY.md"))).toBe("rw");+ expect(visibleInBox(plan, join(cwd, "draft.md"))).toBe("rw");+ expect(visibleInBox(plan, join(dataDir, "bots", "bot-a", "SOUL.md"))).toBe("ro");+ expect(plan.writable.filter((path) => under(path, team))).toEqual([]);+ // Read-only after every read-write line, so nothing the caller lends can make it writable again.+ const args = bwrapArgs(plan);+ const readOnly = args.findIndex((arg, i) => arg === "--ro-bind-try" && args[i + 1] === team && args[i + 2] === team);+ const lastWritable = args.reduce((last, arg, i) => (arg === "--bind" || arg === "--bind-try") && !args[i + 2]!.startsWith("/run/omb/") ? i : last, -1);+ expect(readOnly).toBeGreaterThan(lastWritable);+ expect(visibleInBox(ask({ teamReadOnly: true }, { rw: [team, join(team, "skills")] }), join(team, "skills", "x", "SKILL.md"))).toBe("ro");+ });++ it("a room's turn in the bot's own folder still makes files there, but the team's notes and skills stay read-only", () => {+ const plan = ask({ teamReadOnly: true }, { cwd: team, rw: [join(dataDir, "workspaces", "bot-a--room-g1")] });+ expect(writesTeamThings(plan)).toEqual(["ro", "ro", "ro", "rw"]);+ expect(visibleInBox(plan, join(dataDir, "workspaces", "bot-a--room-g1", "MEMORY.md"))).toBe("rw");+ expect(writesTeamThings(planBox(setup(), { command: "/usr/local/bin/claude", args: [], cwd: team, env: { HOME: home } }))).toEqual(["rw", "rw", "rw", "rw"]);+ });++ it("a turn in a project folder of its own changes nothing there", () => {+ const plan = ask({ teamReadOnly: true }, { cwd: "/data/projects/site" });+ expect(visibleInBox(plan, "/data/projects/site/index.html")).toBe("rw");+ expect(visibleInBox(plan, join(team, "MEMORY.md"))).toBe("none");+ expect(visibleInBox(ask({ teamReadOnly: true }, { cwd: "/data/projects/site", botId: "bot-a" }), join(team, "MEMORY.md"))).toBe("ro");+ });++ it("a process the bot's conversations share has only the conversations its audience may read", () => {+ const threads = (rw: string[], ro: string[]) => planBox(setup(), { command: "opencode", args: ["acp"], cwd, env: { HOME: home }, botThreads: true, audience: { teamReadOnly: ro.length > 0, threads: { rw, ro } } });+ const mira = threads(["thread-1", "thread-3"], ["thread-team"]);+ const at = (plan: ReturnType<typeof threads>, path: string) => visibleInBox(plan, join(dataDir, path));+ expect(at(mira, "task-workspaces/bot-a/thread-1/a.md")).toBe("rw");+ expect(at(mira, "task-workspaces/bot-a/thread-3/a.md")).toBe("rw");+ expect(at(mira, "task-workspaces/bot-a/thread-team/a.md")).toBe("ro");+ expect(at(mira, "box-uploads/bot-a/thread-team/photo.png")).toBe("ro");+ expect(at(mira, "box-uploads/bot-a/thread-3/photo.png")).toBe("ro");+ for (const ben of ["task-workspaces/bot-a/thread-ben/notes.md", "box-uploads/bot-a/thread-ben/photo.png", "task-workspaces/bot-b/thread-9/x"]) expect(at(mira, ben), ben).toBe("none");+ expect(at(mira, "workspaces/bot-a/MEMORY.md")).toBe("ro");+ const shared = threads(["thread-1", "thread-team"], []);+ expect(at(shared, "task-workspaces/bot-a/thread-team/a.md")).toBe("rw");+ expect(at(shared, "task-workspaces/bot-a/thread-ben/notes.md")).toBe("none");+ expect(at(shared, "workspaces/bot-a/MEMORY.md")).toBe("rw");+ // Ids that are not a conversation's are never put back.+ expect(at(threads(["thread-1", "../bot-b"], ["../../config"]), "task-workspaces/bot-b/thread-9/x")).toBe("none");+ });+ });+it("reads the bot and conversation off a task workspace, and absolute paths off the command line", () => {expect(taskWorkspaceIds(cwd, dataDir)).toEqual({ botId: "bot-a", threadId: "thread-1" });expect(taskWorkspaceIds("/data/projects/x", dataDir)).toBeNull();diff --git a/server/bot-box/plan.ts b/server/bot-box/plan.tsindex 270f55e60e..2095ab1794 100644--- a/server/bot-box/plan.ts+++ b/server/bot-box/plan.ts@@ -10,7 +10,9 @@// - 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-// there, whole, since npm's bin links point into the prefix by relative paths;+// there, whole, since npm's bin links point into the prefix by relative paths; on a Team Cloud a turn that is not the+// team's has the bot's own folder read-only and of a process its conversations share only those it may read+// (BoxAudience);// - a private /proc (its own PID namespace: other turns' processes do not exist for it), /dev, /tmp and /run;// - of /sys, only the machine's CPU list, read-only;// - a network namespace with loopback only. Two loopback ports inside are bridged to unix sockets bound in from outside:@@ -20,6 +22,8 @@import { statSync } from "node:fs";import { isAbsolute, join, relative, resolve, sep } from "node:path";+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. */@@ -82,8 +86,27 @@ export interface BoxRequest {/** A host unix socket the box dials out to, so the server can reach a port the engine listens on inside the box's own* network, such as a sign-in's callback. Only an isolated box has one. */relay?: string;+ /** The conversation this spawn runs for, when the caller knows it (a Team Cloud's engine homes do). */+ threadId?: string;+ /** On a Team Cloud: what the conversation's audience gives the box of the bot's team things (BoxAudience). */+ audience?: BoxAudience;+}++/** On a Team Cloud, what one conversation's boxes get of what is the team's (docs/team-cloud.md, "The audience rule"):+ * a turn writes only into its own audience, and reads only what everyone who sees its answer may see. */+export interface BoxAudience {+ /** The turn is not the team's: the bot's own folder (workspaces/<bot>, the team's notes and skills) is put back+ * read-only, after every read-write line. Where that folder is the turn's working folder (a room's), files can still+ * be made in it, and only the team's notes and skills there (MEMORY.md, memory/, skills/) are read-only. */+ teamReadOnly: boolean;+ /** With `botThreads`: the bot's conversations the shared process may see, in place of all of them. Its own audience's+ * read-write, the team's read-only; another person's never. */+ threads?: { rw: readonly string[]; ro: readonly string[] };}+/** What stays read-only in a bot's own folder that is a non-team turn's working folder. */+export const TEAM_FOLDER_KEPT = ["MEMORY.md", "memory", "skills"] as const;+export interface BoxPlan {mounts: Mount[];/** bubblewrap's own options, before `--` and the command. */@@ -198,11 +221,22 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {const ids = cwd ? taskWorkspaceIds(cwd, dataDir) : null;const botId = request.botId ?? ids?.botId ?? null;const threads = request.botThreads && ids ? ids.botId : null;- if (threads) rw(join(dataDir, "task-workspaces", threads));+ const scoped = threads ? request.audience?.threads ?? null : null;+ if (threads && !scoped) rw(join(dataDir, "task-workspaces", threads));+ for (const id of scoped?.rw ?? []) {+ if (!ID.test(id)) continue;+ const folder = join(dataDir, "task-workspaces", threads!, id);+ // A conversation whose folder is not made yet is skipped, as its turn makes it and starts a box of its own.+ mounts.push({ kind: "bind", source: folder, target: folder, optional: true });+ if (!writable.includes(folder)) writable.push(folder);+ }if (cwd && !covered(cwd)) rw(cwd);+ // Security: on a Team Cloud a turn that is not the team's never writes the team's folder (BoxAudience.teamReadOnly).+ const teamFolder = request.audience?.teamReadOnly ? teamFolderOf(botId, cwd, dataDir) : null;+ const workingInTeamFolder = teamFolder !== null && cwd !== null && under(cwd, teamFolder);if (botId && ID.test(botId)) {const own = join(dataDir, "workspaces", botId);- if (!covered(own)) rw(own);+ if (!covered(own) && own !== teamFolder) rw(own);}const ownFolders = botId && ID.test(botId) ? [join(dataDir, "workspaces", botId), join(dataDir, "task-workspaces", botId)] : [];if (mutate.has("bind-otherws")) {@@ -229,8 +263,18 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {}// The person's uploads for this conversation, after every read-write line: readable, but never writable or swappable.if (ids) {- const shown = threads ? join(dataDir, "box-uploads", threads) : boxUploadsDir(dataDir, ids.botId, ids.threadId);- mounts.push({ kind: "ro", source: shown, target: shown, optional: true });+ const shown = scoped ? [...scoped.rw, ...scoped.ro].filter((id) => ID.test(id)).map((id) => boxUploadsDir(dataDir, threads!, id))+ : [threads ? join(dataDir, "box-uploads", threads) : boxUploadsDir(dataDir, ids.botId, ids.threadId)];+ for (const folder of shown) mounts.push({ kind: "ro", source: folder, target: folder, optional: true });+ }+ // The team's conversations a non-team shared process may read, and the team's folder, after every read-write line too.+ for (const id of scoped?.ro ?? []) {+ if (ID.test(id)) mounts.push({ kind: "ro", source: join(dataDir, "task-workspaces", threads!, id), target: join(dataDir, "task-workspaces", threads!, id), optional: true });+ }+ if (teamFolder && workingInTeamFolder) {+ for (const name of TEAM_FOLDER_KEPT) mounts.push({ kind: "ro", source: join(teamFolder, name), target: join(teamFolder, name), optional: true });+ } else if (teamFolder) {+ mounts.push({ kind: "ro", source: teamFolder, target: teamFolder, optional: true });}const readOnly = new Set<string>();const inBotFolder = (path: string) => ["workspaces", "task-workspaces"].some((kind) => {@@ -268,6 +312,15 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {return { mounts, options, net, writable, botId };}+/** The bot's own folder (workspaces/<bot>) a turn has: its bot's, or the one its working folder is (a room's turn), never+ * a memory layer (a sibling folder, the turn's own). */+export function teamFolderOf(botId: string | null, cwd: string | null, dataDir: string): string | null {+ if (botId && ID.test(botId) && !isLayerId(botId)) return join(dataDir, "workspaces", botId);+ if (!cwd) return null;+ const [owner, ...rest] = relative(join(dataDir, "workspaces"), cwd).split(sep);+ return owner && ID.test(owner) && !isLayerId(owner) && !rest.includes("..") ? join(dataDir, "workspaces", owner) : null;+}+/** bubblewrap's argv for the plan (the command follows `--`). */export function bwrapArgs(plan: BoxPlan): string[] {const args: string[] = [];diff --git a/server/cloud-team-box-audience.e2e.test.ts b/server/cloud-team-box-audience.e2e.test.tsnew file mode 100644index 0000000000..3adafb8a12--- /dev/null+++ b/server/cloud-team-box-audience.e2e.test.ts@@ -0,0 +1,128 @@+// A real Team Cloud with the Owner (Olive) and two Members (Mira, Ben), whose engine runs a shell in its turns: a turn+// that is not the team's never writes the bot's own folder (the team's notes and skills) nor reads another person's+// conversation, while the team's chat still writes the team's notes and "Save to team memory" still works from a private+// chat. The box itself runs only where an unprivileged bubblewrap does (a Cloud home; not macOS, not CI's Ubuntu 24.04):+// there the shell's refusals are checked here; elsewhere the same plan is proven in server/host/team-box-scope.test.ts,+// and a real box in server/host/team-box-scope.linux.test.ts.+import { randomBytes } from "node:crypto";+import { existsSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { detectBox } from "./bot-box/detect.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const posix = process.platform !== "win32";+const boxed = posix && detectBox({ env: { ...process.env, OMB_CLOUD_ROLE: "team" } }).box === "bwrap";+const TOKEN = `ops_fake-team-box-${randomBytes(8).toString("hex")}`;+const OWNER = { email: "[email protected]", role: "owner" as const };+const MIRA = { email: "[email protected]", role: "member" as const };+const BEN = { email: "[email protected]", role: "member" as const };+const SHELL = `import { readFileSync as readToolCalls } from "node:fs";+process.env.FAKE_CLAUDE_DUMP = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/dump.json";+process.env.FAKE_CLAUDE_SHELL_LOG = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/shell.jsonl";+process.env.FAKE_CLAUDE_RUN_BASH = "1";+process.env.FAKE_CLAUDE_EXIT_AFTER_TURN = "1";+try { process.env.FAKE_CLAUDE_TOOL_CALLS = readToolCalls(process.env.FAKE_CLAUDE_FIXTURE_DIR + "/tool-calls.json", "utf8"); } catch {}`;++let fx: CloudSendFixture, team: CloudTeamFixture;+let owner = "", mira = "", ben = "";+let bot: { id: string; mainThreadId: string };+let dataDir = "", teamNotes = "", miraThread = "", benThread = "";++type Dump = { cwd: string; systemPrompt?: string | null };+const messages = async (token: string, threadId: string) => (await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages as Array<{ id: string; role: string; kind?: string; text?: string }>;+const idle = async (token: string) => ((await team.as(token, "GET", "/api/bots")).body.bots as Array<{ activity?: string; busy?: boolean }>)+ .every((entry) => entry.activity !== "working" && !entry.busy);+const shellLog = () => existsSync(join(team.home, "shell.jsonl"))+ ? readFileSync(join(team.home, "shell.jsonl"), "utf8").trim().split("\n").map((line) => JSON.parse(line) as { command: string; output: string }) : [];+async function turn(token: string, threadId: string, text: string, command?: string): Promise<{ dump: Dump; output: string }> {+ rmSync(join(team.home, "dump.json"), { force: true });+ const file = join(team.home, "tool-calls.json");+ if (command) writeFileSync(file, JSON.stringify([{ name: "Bash", input: { command } }])); else rmSync(file, { force: true });+ try {+ const before = (await messages(token, threadId)).length;+ const sent = await team.as(token, "POST", `/api/bots/${bot.id}/messages`, { text, threadId });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await expect.poll(async () => await idle(token) && (await messages(token, threadId)).length >= before + 2 && existsSync(join(team.home, "dump.json")),+ { timeout: 60_000, interval: 100 }).toBe(true);+ } finally {+ rmSync(file, { force: true });+ }+ const dump = JSON.parse(readFileSync(join(team.home, "dump.json"), "utf8")) as Dump;+ return { dump, output: command ? shellLog().filter((entry) => entry.command === command).at(-1)?.output ?? "" : "" };+}+const newThread = async (token: string, title: string) => {+ const created = await team.as(token, "POST", `/api/bots/${bot.id}/tasks`, { title });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ return created.body.task.threadId as string;+};++beforeAll(async () => {+ if (!posix) return;+ fx = await launchCloudSendFixture({ onePasswordToken: TOKEN, team: { id: "team-acme-box", name: "Acme", engine: SHELL }, cloudEngine: SHELL });+ team = fx.team!;+ dataDir = join(team.home, ".openmausbot");+ owner = (await team.pair(OWNER)).token!;+ mira = (await team.pair(MIRA)).token!;+ ben = (await team.pair(BEN)).token!;+ const created = await team.as(owner, "POST", "/api/bots", { name: "Scout", visibility: "everyone" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ bot = created.body.bot;+ teamNotes = join(dataDir, "workspaces", bot.id, "MEMORY.md");+ benThread = await newThread(ben, "Ben's payslip");+ miraThread = await newThread(mira, "Mira and Scout");+}, hostTimeout(180_000));++afterAll(async () => {+ await fx?.close();+});++it.runIf(posix)("Mira's private chat is told the team's folder is read-only there; the team's chat is not", async () => {+ // Ben's conversation folder, with what only he may read.+ const benTurn = await turn(ben, benThread, "Keep this.", "echo 'locker code sardine' > notes.md");+ expect(realpathSync(benTurn.dump.cwd)).toBe(realpathSync(join(dataDir, "task-workspaces", bot.id, benThread)));+ const { dump } = await turn(mira, miraThread, "Hello.");+ expect(realpathSync(dump.cwd)).toBe(realpathSync(join(dataDir, "task-workspaces", bot.id, miraThread)));+ expect(dump.systemPrompt).toContain(`${join("workspaces", bot.id)}) holds Acme's notes and skills: in this conversation they are read-only`);+ const main = await turn(owner, bot.mainThreadId, "Hello, team.");+ expect(main.dump.systemPrompt ?? "").not.toContain("in this conversation they are read-only");+ // A conversation folder of its own, so in a box its turns have the bot's folder (read-write, as the team's).+ expect(realpathSync(main.dump.cwd)).toBe(realpathSync(join(dataDir, "task-workspaces", bot.id, bot.mainThreadId)));+}, hostTimeout(120_000));++it.runIf(boxed)("a shell in Mira's private chat reads the team's notes but cannot write them, nor read Ben's conversation", async () => {+ const before = readFileSync(teamNotes, "utf8");+ const benNotes = join(dataDir, "task-workspaces", bot.id, benThread, "notes.md");+ const command = [+ `cat "${teamNotes}" >/dev/null && echo TEAM-READ`,+ `(echo mira >> "${teamNotes}") 2>&1 && echo TEAM-WRITTEN || echo TEAM-REFUSED`,+ `cat "${benNotes}" 2>&1 || echo BEN-UNREADABLE`,+ "echo draft > draft.md && echo OWN-WRITTEN",+ ].join("; ");+ const { output } = await turn(mira, miraThread, "Note it in the team's notes.", command);+ expect(output).toContain("TEAM-READ");+ expect(output).toContain("TEAM-REFUSED");+ expect(output).not.toContain("TEAM-WRITTEN");+ expect(output).toContain("BEN-UNREADABLE");+ expect(output).not.toContain("sardine");+ expect(output).toContain("OWN-WRITTEN");+ expect(readFileSync(teamNotes, "utf8")).toBe(before);+ // The turn ended as any other: the refusal is the shell's answer, not a failed turn.+ const last = (await messages(mira, miraThread)).filter((message) => message.role === "bot" && message.kind !== "activity").at(-1);+ expect(JSON.stringify(last)).not.toMatch(/error|failed/i);+}, hostTimeout(120_000));++it.runIf(posix)("the team's chat still writes the team's notes", async () => {+ const command = `echo 'we ship on Fridays' >> "${teamNotes}" && echo TEAM-WRITTEN`;+ const { output } = await turn(owner, bot.mainThreadId, "Remember we ship on Fridays.", command);+ expect(output).toContain("TEAM-WRITTEN");+ expect(readFileSync(teamNotes, "utf8")).toContain("we ship on Fridays");+}, hostTimeout(120_000));++it.runIf(posix)("Save to team memory still works from Mira's private chat", async () => {+ const line = (await messages(mira, miraThread)).filter((message) => message.role === "user").at(-1)!;+ const saved = await team.as(mira, "POST", `/api/bots/${bot.id}/memory/team`, { threadId: miraThread, messageId: line.id, text: "Payroll closes on the 25th" });+ expect(saved.status, JSON.stringify(saved.body)).toBeLessThan(300);+ expect(readFileSync(teamNotes, "utf8")).toContain("Payroll closes on the 25th (saved by");+}, hostTimeout(60_000));diff --git a/server/engine-homes/engine-homes.ts b/server/engine-homes/engine-homes.tsindex cce7f3a2d1..62acc7d347 100644--- a/server/engine-homes/engine-homes.ts+++ b/server/engine-homes/engine-homes.ts@@ -45,6 +45,11 @@ export class EngineHomes {return this.#setup ? this.#thread.run(threadId, start) : start();}+ /** The conversation the caller runs in, on a Team Cloud; undefined elsewhere. */+ thread(): string | undefined {+ return this.#setup ? this.#thread.getStore() : undefined;+ }+/** The audience key of the conversation the caller runs in, so engines never share a process across audiences. */scope(): string | null {const threadId = this.#setup ? this.#thread.getStore() : undefined;diff --git a/server/host/cloud-team-host.ts b/server/host/cloud-team-host.tsindex 60f665e025..20dac8222f 100644--- a/server/host/cloud-team-host.ts+++ b/server/host/cloud-team-host.ts@@ -11,11 +11,13 @@ import { ensureWorkspace, loadMemory, workspaceDir } from "../workspace.ts";import type { EngineHomes } from "../engine-homes/engine-homes.ts";import { storeThreads, type StoreBotThreads } from "../engine-homes/migrate.ts";import type { ConversationShares } from "./conversation-shares.ts";+import { createTeamBoxScope, type TeamBoxBots } from "./team-box-scope.ts";+import type { BoxAudienceScope } from "../bot-box/box.ts";export interface CloudTeamHostDeps {team: CloudTeam | null;dataDir: string;- store: { groupByThread(threadId: string): { id: string } | undefined; readonly bots?: StoreBotThreads };+ store: { groupByThread(threadId: string): { id: string } | undefined; readonly bots?: StoreBotThreads & TeamBoxBots };starters: { get(threadId: string): string | undefined };/** Keys that name no person (nobody, outside). */markers: ReadonlySet<string>;@@ -27,6 +29,8 @@ export interface CloudTeamHostDeps {serverProfile?: { read(): ServerProfile | undefined; clear(): void };/** Started on a team: each audience's engines get their own home (server/engine-homes). */engineHomes?: Pick<EngineHomes, "start">;+ /** Given the audience rule on a team, for every box (server/host/team-box-scope.ts). */+ box?: { scopeAudiences(scope: BoxAudienceScope | null): void };}export interface TeamSessionInfo { id: string; name: string; role: TeamRole }@@ -51,6 +55,7 @@ export function createCloudTeamHost(deps: CloudTeamHostDeps) {return person && !deps.shares?.isShareKey(person) ? person : null;};if (team) deps.engineHomes?.start({ dataDir: deps.dataDir, audienceOf, threads: () => storeThreads(deps.store.bots ?? []) });+ if (team) deps.box?.scopeAudiences(createTeamBoxScope({ audienceOf, bots: () => deps.store.bots ?? [] }));/** The layer a turn in this conversation writes into: the bot's own folder off a team or for the team's conversations,* a sibling folder for a room's or a member's. The folder exists before the turn starts, so the box can bind it. */const layer = (botId: string, threadId: string): string => {@@ -124,12 +129,14 @@ export function createCloudTeamHost(deps: CloudTeamHostDeps) {const turn = audienceOf(threadId);return (other) => mayRead(audienceOf(other), turn);},- /** The team's notes, read-only, for a turn that writes elsewhere (a room's or a member's layer). */+ /** The team's notes, read-only, for a turn that writes elsewhere (a room's or a member's layer), and that the box+ * keeps the team's folder read-only for it, so a refused write there is never a surprise. */sharedNotesPrompt(botId: string, threadId: string): string {if (!team || layer(botId, threadId) === botId) return "";+ const readOnly = `\n\nYour shared folder (${workspaceDir(botId)}) holds ${team.name}'s notes and skills: in this conversation they are read-only, and writing there fails. Save what you learn here with your memory tools, and make files in your working folder.`;const shared = loadMemory(botId);- if (!shared) return "";- return `\n\n${team.name}'s shared notes with you (read-only here; what you save in this conversation stays with it):\n${shared.text}`;+ if (!shared) return readOnly;+ return `${readOnly}\n\n${team.name}'s shared notes with you (read-only here; what you save in this conversation stays with it):\n${shared.text}`;},/** "About the user" for a turn: on a team only a member's own, with their name, in their own conversations; the* server's profile otherwise. */diff --git a/server/host/team-box-scope.linux.test.ts b/server/host/team-box-scope.linux.test.tsnew file mode 100644index 0000000000..9a07ebc2b1--- /dev/null+++ b/server/host/team-box-scope.linux.test.ts@@ -0,0 +1,77 @@+// The audience rule 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; team-box-scope.test.ts proves the plan.+import { spawnSync } from "node:child_process";+import { mkdirSync, mkdtempSync, readFileSync, 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 "../bot-box/detect.ts";+import { bwrapArgs, planBox, type BoxRequest } from "../bot-box/plan.ts";+import { createTeamBoxScope } from "./team-box-scope.ts";++const detection = detectBox({ env: { ...process.env, OMB_BOT_BOX: "1" } });+const available = detection.box === "bwrap" && detection.tools !== null;+const root = mkdtempSync(join(tmpdir(), "omb-team-box-"));+afterAll(() => rmSync(root, { recursive: true, force: true }));++const home = join(root, "home"), dataDir = join(home, ".openmausbot");+const team = join(dataDir, "workspaces", "bot-a"), miraLayer = join(dataDir, "workspaces", "bot-a--member-p_mira");+const conversation = (threadId: string) => join(dataDir, "task-workspaces", "bot-a", threadId);+const put = (path: string, text: string) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); };+const audiences: Record<string, "team" | `member:${string}`> = { "t-team": "team", "t-mira": "member:p_mira", "t-ben": "member:p_ben" };+const scope = createTeamBoxScope({ audienceOf: (threadId) => audiences[threadId] ?? "team", bots: () => [{ id: "bot-a", tasks: Object.keys(audiences).map((threadId) => ({ threadId })) }] });++function shellIn(threadId: string, script: string, more: Partial<BoxRequest> = {}): string {+ const cwd = conversation(threadId);+ const audience = scope({ threadId, botId: "bot-a", sharedProcess: Boolean(more.botThreads) });+ const plan = planBox({ dataDir, home, codeRoots: [], engineRoots: [], bridges: [] }, { command: "/bin/sh", args: [], cwd, env: { HOME: home, PATH: "/usr/bin:/bin" }, ...(audience ? { audience } : {}), ...more });+ const ran = spawnSync(detection.tools!.bwrap, [...bwrapArgs(plan), "--", "/bin/sh", "-c", script], { env: { HOME: home, PATH: "/usr/bin:/bin" }, encoding: "utf8", timeout: 30_000 });+ return `${ran.stdout}${ran.stderr}`;+}++describe.skipIf(!available)(`the audience rule in a real box (${available ? "bubblewrap works here" : `skipped: ${detection.reason}`})`, () => {+ beforeAll(() => {+ put(join(team, "MEMORY.md"), "team notes\n");+ put(join(team, "skills", "report", "SKILL.md"), "the team's skill\n");+ put(join(miraLayer, "MEMORY.md"), "mira's notes\n");+ for (const threadId of Object.keys(audiences)) put(join(conversation(threadId), "notes.md"), `${threadId}: sardine\n`);+ });++ it("a shell in Mira's private chat reads the team's notes but cannot write them, nor read Ben's conversation", () => {+ const output = shellIn("t-mira", [+ `cat "${join(team, "MEMORY.md")}"`,+ `echo mira >> "${join(team, "MEMORY.md")}" || echo TEAM-NOTES-REFUSED`,+ `echo x > "${join(team, "skills", "report", "SKILL.md")}" || echo TEAM-SKILL-REFUSED`,+ `echo mira >> "${join(miraLayer, "MEMORY.md")}" && echo OWN-LAYER-WRITTEN`,+ `cat "${join(conversation("t-ben"), "notes.md")}" || echo BEN-UNREADABLE`,+ `echo done > "${join(conversation("t-mira"), "draft.md")}" && echo OWN-FOLDER-WRITTEN`,+ ].join("\n"), { rw: [miraLayer] });+ expect(output).toContain("team notes");+ expect(output).toContain("TEAM-NOTES-REFUSED");+ expect(output).toMatch(/Read-only file system/);+ expect(output).toContain("TEAM-SKILL-REFUSED");+ expect(output).toContain("OWN-LAYER-WRITTEN");+ expect(output).toContain("BEN-UNREADABLE");+ expect(output).not.toContain("t-ben: sardine");+ expect(output).toContain("OWN-FOLDER-WRITTEN");+ expect(readFileSync(join(team, "MEMORY.md"), "utf8")).toBe("team notes\n");+ }, 60_000);++ it("a process Mira's conversations share lists neither Ben's conversation nor writes the team's", () => {+ const output = shellIn("t-mira", [+ `ls "${join(dataDir, "task-workspaces", "bot-a")}"`,+ `cat "${join(conversation("t-team"), "notes.md")}"`,+ `echo x >> "${join(conversation("t-team"), "notes.md")}" || echo TEAM-CHAT-REFUSED`,+ ].join("\n"), { botThreads: true });+ expect(output).not.toContain("t-ben");+ expect(output).toContain("t-team: sardine");+ expect(output).toContain("TEAM-CHAT-REFUSED");+ }, 60_000);++ it("the team's chat still writes the team's notes", () => {+ const output = shellIn("t-team", `echo team >> "${join(team, "MEMORY.md")}" && echo TEAM-NOTES-WRITTEN`);+ expect(output).toContain("TEAM-NOTES-WRITTEN");+ expect(readFileSync(join(team, "MEMORY.md"), "utf8")).toBe("team notes\nteam\n");+ }, 60_000);+});diff --git a/server/host/team-box-scope.test.ts b/server/host/team-box-scope.test.tsnew file mode 100644index 0000000000..6ad78c7822--- /dev/null+++ b/server/host/team-box-scope.test.ts@@ -0,0 +1,140 @@+// The audience rule in the bot box on a Team Cloud, through the same wiring a turn uses: the Team Cloud host registers+// its scope with the box, a spawn inside a conversation (engine homes) asks the box for its plan, and the plan says what+// that box may write. bubblewrap itself is a stand-in here that records and runs nothing boxed; the plan is what a real+// one is given (team-box-scope.linux.test.ts runs it in a real box where one can run).+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";++import { botBox, type WrappedSpawn } from "../bot-box/box.ts";+import { visibleInBox, type BoxRequest } from "../bot-box/plan.ts";+import { DATA_DIR } from "../config.ts";+import { engineHomes } from "../engine-homes/engine-homes.ts";+import { boxedSpawn, sharedBoxScope } from "../procs.ts";+import { removeTempDir } from "../testing/cleanup.ts";+import { ensureTaskWorkspace } from "../workspace.ts";+import { createCloudTeamHost } from "./cloud-team-host.ts";+import { botConversations, createTeamBoxScope } from "./team-box-scope.ts";++const BOT = "bot-scout";+const bots = [{ id: BOT, threadId: "main", tasks: [{ threadId: "mira-1" }, { threadId: "mira-2" }, { threadId: "ben-1" }, { threadId: "team-1" }] }];+const starters = new Map([["mira-1", "p_mira"], ["mira-2", "p_mira"], ["ben-1", "p_ben"], ["team-1", "nobody"], ["main", "nobody"], ["mira-new", "p_mira"]]);+const store = { groupByThread: (threadId: string) => (threadId === "room-1" ? { id: "g1" } : undefined), bots };+const team = (box: { scopeAudiences: typeof botBox.scopeAudiences } | undefined, on = true) => createCloudTeamHost({+ team: on ? { id: "team-acme", name: "Acme" } as never : null, dataDir: DATA_DIR, store, starters, markers: new Set(["nobody"]), engineHomes, ...(box ? { box } : {}),+});++describe("the Team Cloud's box scope", () => {+ const scope = createTeamBoxScope({ audienceOf: (threadId) => team(undefined).audienceOf(threadId), bots: () => bots });++ it("keeps the team's folder read-only for every turn that is not the team's", () => {+ expect(scope({ threadId: "main", botId: BOT, sharedProcess: false })).toEqual({ teamReadOnly: false });+ expect(scope({ threadId: "team-1", botId: BOT, sharedProcess: false })).toEqual({ teamReadOnly: false });+ expect(scope({ threadId: "mira-1", botId: BOT, sharedProcess: false })).toEqual({ teamReadOnly: true });+ expect(scope({ threadId: "room-1", botId: null, sharedProcess: false })).toEqual({ teamReadOnly: true });+ });++ it("gives a shared process its own audience's conversations, the team's read-only, and never another person's", () => {+ expect(scope({ threadId: "mira-1", botId: BOT, sharedProcess: true })?.threads).toEqual({ rw: ["mira-1", "mira-2"], ro: ["main", "team-1"] });+ expect(scope({ threadId: "team-1", botId: BOT, sharedProcess: true })?.threads).toEqual({ rw: ["main", "team-1"], ro: [] });+ expect(scope({ threadId: "ben-1", botId: BOT, sharedProcess: true })?.threads).toEqual({ rw: ["ben-1"], ro: ["main", "team-1"] });+ expect(scope({ threadId: "mira-new", botId: BOT, sharedProcess: true })?.threads, "a conversation the store has not listed yet is still its own")+ .toEqual({ rw: ["mira-1", "mira-2", "mira-new"], ro: ["main", "team-1"] });+ expect(botConversations(bots, "bot-gone")).toEqual([]);+ });+});++// The box's gates listen on unix sockets, which Windows refuses at a file path; the box runs only on a Linux Cloud home.+describe.skipIf(process.platform === "win32")("a Team Cloud turn's box, through the spawn path", () => {+ let scratch = "";+ const plans: WrappedSpawn[] = [];+ const folder = (threadId: string) => ensureTaskWorkspace(BOT, threadId);+ const at = (path: string) => join(DATA_DIR, path);+ /** The plan a spawn of the bot's engine gets in this conversation, in `cwd`. */+ const planIn = (threadId: string, cwd: string, more: Partial<BoxRequest> = {}) => engineHomes.within(threadId, () => {+ const wrapped = boxedSpawn({ command: "/usr/local/bin/claude", args: [] }, { cwd, env: { HOME: homedir() }, box: more }, "bot");+ expect(wrapped).not.toBeNull();+ plans.push(wrapped!);+ return wrapped!.plan;+ });++ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), "omb-team-box-scope-"));+ const fakeBwrap = join(scratch, "fake-bwrap.sh");+ writeFileSync(fakeBwrap, "#!/bin/sh\nexit 0\n");+ chmodSync(fakeBwrap, 0o755);+ await botBox.start({+ dataDir: DATA_DIR, home: homedir(), port: 8799, denyEnv: new Set(), env: {}, log: () => {},+ detect: () => ({ box: "bwrap", reason: null, tools: { bwrap: fakeBwrap, socat: "/usr/bin/true" } }),+ });+ for (const threadId of ["mira-1", "mira-2", "ben-1", "team-1"]) writeFileSync(join(folder(threadId), "notes.md"), `${threadId}'s notes`);+ });+ afterAll(async () => {+ for (const wrapped of plans) wrapped.release();+ vi.restoreAllMocks();+ botBox.scopeAudiences(null);+ engineHomes.stop();+ await botBox.stop();+ await removeTempDir(scratch);+ });++ it("Mira's private chat reads the team's notes and writes only her own; Ben's chat is not there", () => {+ const host = team(botBox);+ botBox.lend(BOT, "mira-1", host.layerDirs(BOT, "mira-1"));+ const plan = planIn("mira-1", folder("mira-1"));+ for (const file of ["MEMORY.md", "memory/x.md", "skills/report/SKILL.md"]) expect(visibleInBox(plan, at(`workspaces/${BOT}/${file}`)), file).toBe("ro");+ expect(visibleInBox(plan, join(host.layerDirs(BOT, "mira-1")[0]!, "MEMORY.md")), "her own layer").toBe("rw");+ expect(visibleInBox(plan, join(folder("mira-1"), "draft.md"))).toBe("rw");+ expect(visibleInBox(plan, join(folder("ben-1"), "notes.md"))).toBe("none");+ expect(visibleInBox(plan, at(`workspaces/${BOT}--member-p_ben/MEMORY.md`))).toBe("none");+ });++ it("the team's chat still writes the team's notes and skills", () => {+ team(botBox);+ const plan = planIn("team-1", folder("team-1"));+ for (const file of ["MEMORY.md", "skills/report/SKILL.md"]) expect(visibleInBox(plan, at(`workspaces/${BOT}/${file}`)), file).toBe("rw");+ expect(visibleInBox(plan, join(folder("mira-1"), "notes.md"))).toBe("none");+ });++ it("a room's turn in the bot's own folder makes files there and writes its own layer, never the team's notes", () => {+ const host = team(botBox);+ const own = at(`workspaces/${BOT}`);+ mkdirSync(own, { recursive: true });+ rmSync(join(own, "skills"), { recursive: true, force: true });+ botBox.lend(BOT, "room-1", host.layerDirs(BOT, "room-1"));+ const plan = planIn("room-1", own);+ expect(existsSync(join(own, "skills")), "made first, so the read-only bind has something to cover").toBe(true);+ expect(visibleInBox(plan, join(own, "report.md"))).toBe("rw");+ expect(visibleInBox(plan, join(own, "MEMORY.md"))).toBe("ro");+ expect(visibleInBox(plan, join(own, "skills", "x", "SKILL.md"))).toBe("ro");+ expect(visibleInBox(plan, at(`workspaces/${BOT}--room-g1/MEMORY.md`)), "the room's layer, lent to its boxes").toBe("rw");+ });++ it("a process Mira's conversations share has hers and the team's, read-only, and gets a new key for a new conversation", () => {+ team(botBox);+ const plan = planIn("mira-1", folder("mira-1"), { botThreads: true });+ expect(visibleInBox(plan, join(folder("mira-2"), "notes.md"))).toBe("rw");+ expect(visibleInBox(plan, join(folder("team-1"), "notes.md"))).toBe("ro");+ expect(visibleInBox(plan, join(folder("ben-1"), "notes.md"))).toBe("none");+ expect(visibleInBox(plan, at(`workspaces/${BOT}/MEMORY.md`))).toBe("ro");+ const key = (threadId: string) => engineHomes.within(threadId, () => sharedBoxScope(folder(threadId)));+ const mira = key("mira-1");+ expect(mira).not.toBe(key("team-1"));+ bots[0]!.tasks.push({ threadId: "mira-3" });+ try {+ expect(key("mira-1"), "a conversation made later gets a process whose box has its folder").not.toBe(mira);+ } finally {+ bots[0]!.tasks.pop();+ }+ });++ it("off a team the box is as it was: every turn writes the bot's own folder", () => {+ team(botBox, false);+ botBox.scopeAudiences(null);+ engineHomes.stop();+ const plan = planIn("mira-1", folder("mira-1"));+ expect(visibleInBox(plan, at(`workspaces/${BOT}/MEMORY.md`))).toBe("rw");+ expect(visibleInBox(planIn("mira-1", folder("mira-1"), { botThreads: true }), join(folder("ben-1"), "notes.md"))).toBe("rw");+ });+});diff --git a/server/host/team-box-scope.ts b/server/host/team-box-scope.tsnew file mode 100644index 0000000000..007b33f78a--- /dev/null+++ b/server/host/team-box-scope.ts@@ -0,0 +1,39 @@+// The bot box's side of a Team Cloud's audience rule (docs/team-cloud.md, "The audience rule"): a turn writes only into its+// own audience and reads only what everyone who sees its answer may see, so a shell in a member's private chat or a room+// never writes the bot's own folder (the team's notes and skills), and a process a bot's conversations share has only+// the conversations its audience may read. Registered with the box by the Team Cloud host; nothing here runs elsewhere.+import { mayRead, TEAM_AUDIENCE, type Audience } from "../audience.ts";+import type { BoxAudienceScope } from "../bot-box/box.ts";+import type { BoxAudience } from "../bot-box/plan.ts";++/** A bot's conversations as the store keeps them: its main chat and each of its tasks. */+export type TeamBoxBots = ReadonlyArray<{ id: string; threadId?: string; tasks?: ReadonlyArray<{ threadId: string }> }>;++export interface TeamBoxScopeDeps {+ audienceOf(threadId: string): Audience;+ bots(): TeamBoxBots;+}++/** Every conversation the store has for this bot; one it no longer has (deleted) is never put back. */+export function botConversations(bots: TeamBoxBots, botId: string): string[] {+ const bot = bots.find((entry) => entry.id === botId);+ if (!bot) return [];+ return [...new Set([...(bot.threadId ? [bot.threadId] : []), ...(bot.tasks ?? []).map((task) => task.threadId)])];+}++export function createTeamBoxScope(deps: TeamBoxScopeDeps): BoxAudienceScope {+ return ({ threadId, botId, sharedProcess }): BoxAudience => {+ const turn = deps.audienceOf(threadId);+ const audience: BoxAudience = { teamReadOnly: turn !== TEAM_AUDIENCE };+ if (!sharedProcess || !botId) return audience;+ const rw: string[] = [], ro: string[] = [];+ for (const other of botConversations(deps.bots(), botId)) {+ const of = deps.audienceOf(other);+ if (of === turn) rw.push(other);+ else if (mayRead(of, turn)) ro.push(other);+ }+ // The conversation that starts the process is its own, whether or not the store lists it yet.+ if (!rw.includes(threadId)) rw.push(threadId);+ return { ...audience, threads: { rw: rw.sort(), ro: ro.sort() } };+ };+}diff --git a/server/index.ts b/server/index.tsindex 7c5a641f65..a2b21f8a21 100644--- a/server/index.ts+++ b/server/index.ts@@ -950,7 +950,7 @@ const CLOUD_OWNER_KEY = CLOUD_PERSONAL ? `p_${createHash("sha256").update(`cloud/** Settled at boot once routines load (settleCloudHome); only `proven` feeds lending and memory. */let cloudEarlierOwners: Pick<CloudOwnership, "adopted" | "proven"> = { adopted: new Set(), proven: new Set() };/** Until it is settled, a Cloud home counts as shared. */-let cloudHome: ReturnType<typeof settleCloudHome> | null = null; const teamHost = createCloudTeamHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, store: { groupByThread: (threadId) => store.groupByThread(threadId), get bots() { return store.bots; } }, engineHomes, starters: threadStarters, shares: conversationShares, markers: new Set([CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY]), language: appLanguage,+let cloudHome: ReturnType<typeof settleCloudHome> | null = null; const teamHost = createCloudTeamHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, store: { groupByThread: (threadId) => store.groupByThread(threadId), get bots() { return store.bots; } }, engineHomes, box: botBox, starters: threadStarters, shares: conversationShares, markers: new Set([CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY]), language: appLanguage,serverProfile: { read: () => cfg.profile, clear: () => { adminActorScope.exit(() => saveConfig({ profile: { name: "", email: "", aboutMe: "", avatarUrl: "" } })); Object.assign(cfg, loadConfig()); } } }); const vaultReaders = createVaultReaders({ team: CLOUD_TEAM !== null, audienceOf: (threadId) => teamHost.audienceOf(threadId), personOf: actorKey });const teamOwners = createTeamOwners({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store: () => store, audienceOf: (threadId) => teamHost.audienceOf(threadId), starters: threadStarters }); const mausbotOwnChat = createMausBotOwnChat({ bots: () => store.bots, starters: threadStarters, personKey: (email) => personKey({ id: "", email }), moveNotes: (from, to, person) => moveMemoryLayer(from, to, personLanguages.forLine(person)) });const personRooms = createPersonRooms({ reads: CLOUD_TEAM ? createRoomReads(DATA_DIR, (person) => { botOrders?.forgetPerson(person); forgetNotificationReader(person); }) : null, store: () => store, newestMessageId: (threadId) => readCursor(threadId).lastReadMessageId, publicGroupState, broadcast, shared: (threadId) => teamHost.privateTo(threadId) === null || conversationShares.readers(threadId) !== null, wireBot: (botId) => { const bot = store.bot(botId); return bot ? wireBot(bot) : null; } });diff --git a/server/procs.ts b/server/procs.tsindex 45dab9c20b..0885713a87 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -9,6 +9,7 @@ import {type ExecFileOptions,type SpawnOptions,} from "node:child_process";+import { createHash } from "node:crypto";import { closeSync, existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";import type { Readable, Writable } from "node:stream";import { basename, dirname, join, resolve } from "node:path";@@ -264,15 +265,20 @@ export function boxedSpawn(resolved: ResolvedSpawn, opts: CliSpawnOptions, ownerif (opts.box === false || (owner !== "bot" && !opts.box)) return null;const request = typeof opts.box === "object" ? opts.box : {};const home = homed ? { home: homed.home, shared: homed.shared } : {};- return botBox.wrap({ command: resolved.command, args: resolved.args, cwd: typeof opts.cwd === "string" ? opts.cwd : undefined, env: opts.env ?? process.env, ...request, ...home });+ const threadId = engineHomes.thread();+ return botBox.wrap({ command: resolved.command, args: resolved.args, cwd: typeof opts.cwd === "string" ? opts.cwd : undefined, env: opts.env ?? process.env, ...(threadId ? { threadId } : {}), ...request, ...home });}/** What a process several conversations share must be boxed with to serve `cwd` (null with the box off): all of the bot's- * conversation folders for a conversation folder (task-workspaces/<bot>/<thread>, BoxRequest.botThreads), else `cwd`. */+ * conversation folders for a conversation folder (task-workspaces/<bot>/<thread>, BoxRequest.botThreads), on a Team+ * Cloud only those its audience may read (BoxAudience.threads), else `cwd`. */export function sharedBoxScope(cwd: string): string | null {if (!botBox.enabled()) return null;const parent = dirname(resolve(cwd));- return basename(dirname(parent)) === "task-workspaces" ? parent : resolve(cwd);+ if (basename(dirname(parent)) !== "task-workspaces") return resolve(cwd);+ const threadId = engineHomes.thread();+ const threads = botBox.sharedThreadsKey({ cwd, ...(threadId ? { threadId } : {}) });+ return threads ? `${parent}#${createHash("sha256").update(threads).digest("hex").slice(0, 16)}` : parent;}/** Security (bot-box/program-trust.ts): a spawn outside the box neither starts a program from a folder a boxed bot can