Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(bot-box): keep the bot's own folders in its box when it works in a project folder
AdityaUmale0dd1c7869dc3
diff --git a/server/bot-box/plan.ts b/server/bot-box/plan.tsindex 66f8390945..67b6ee240d 100644--- a/server/bot-box/plan.ts+++ b/server/bot-box/plan.ts@@ -88,6 +88,9 @@ export interface BoxRequest {relay?: string;/** The conversation this spawn runs for, when the caller knows it (a Team Cloud's engine homes do). */threadId?: string;+ /** With `botId`, for a turn working outside its conversation's folder (a configured project folder): that folder+ * (task-workspaces/<botId>/<thread>, its handed-off files), put back read-write where it exists. */+ conversationFolder?: string;/** The bot whose turn that is, for the audience rule only (BoxAudience); unlike `botId` it puts back nothing. */conversationBot?: string;/** On a Team Cloud: what the conversation's audience gives the box of the bot's team things (BoxAudience). */@@ -249,6 +252,12 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {if (!covered(own) && own !== teamFolder) rw(own);}const ownFolders = botId && ID.test(botId) ? [join(dataDir, "workspaces", botId), join(dataDir, "task-workspaces", botId)] : [];+ // Security: only a conversation folder of this box's own bot, and never in a process other conversations share.+ const conversation = request.conversationFolder && !request.botThreads ? resolve(request.conversationFolder) : null;+ if (conversation && botId && ID.test(botId) && taskWorkspaceIds(conversation, dataDir)?.botId === botId && !covered(conversation)) {+ mounts.push({ kind: "bind", source: conversation, target: conversation, optional: true });+ if (!writable.includes(conversation)) writable.push(conversation);+ }if (mutate.has("bind-otherws")) {rw(join(dataDir, "workspaces"));rw(join(dataDir, "task-workspaces"));diff --git a/server/bot-box/turn-bot-folder.test.ts b/server/bot-box/turn-bot-folder.test.tsnew file mode 100644index 0000000000..99b52b9532--- /dev/null+++ b/server/bot-box/turn-bot-folder.test.ts@@ -0,0 +1,111 @@+// A bot with a configured project folder works in that folder, not in its own one under the data folder. Its turn's box+// must still have the bot's own folder (workspaces/<bot>, where the server saves a request_credential file) and its+// conversation folder (task-workspaces/<bot>/<thread>, handed-off files), and never another bot's. bubblewrap is a+// stand-in that runs nothing; the plan is what a real one is given.+import { chmodSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { DATA_DIR } from "../config.ts";+import { runInTurn } from "../crash-guard.ts";+import { boxedSpawn, sharedBoxScope } from "../procs.ts";+import { removeTempDir } from "../testing/cleanup.ts";+import { ensureTaskWorkspace, workspaceDir } from "../workspace.ts";+import { botBox, type WrappedSpawn } from "./box.ts";+import { visibleInBox, type BoxRequest } from "./plan.ts";++const BOT = "bot-with-project", OTHER = "bot-other";+const turn = { botId: BOT, threadId: "t1" };++// 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 turn's box in a configured project folder", () => {+ let scratch = "", project = "";+ const plans: WrappedSpawn[] = [];+ const spawnIn = (cwd: string | undefined, more: Partial<BoxRequest> = {}) => {+ const wrapped = boxedSpawn({ command: "/usr/local/bin/claude", args: [] }, { ...(cwd ? { cwd } : {}), env: { HOME: homedir() }, box: more }, "bot");+ expect(wrapped).not.toBeNull();+ plans.push(wrapped!);+ return wrapped!.plan;+ };++ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), "omb-turn-bot-folder-"));+ project = join(scratch, "project");+ mkdirSync(project, { recursive: true });+ for (const bot of [BOT, OTHER]) mkdirSync(workspaceDir(bot), { recursive: true });+ ensureTaskWorkspace(BOT, "t1");+ 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: 8798, denyEnv: new Set(), env: {}, log: () => {},+ detect: () => ({ box: "bwrap", reason: null, tools: { bwrap: fakeBwrap, socat: "/usr/bin/true" } }),+ });+ });+ afterAll(async () => {+ for (const wrapped of plans) wrapped.release();+ await botBox.stop();+ await removeTempDir(scratch);+ });++ it("gives the turn's bot its own folder and conversation folder read-write, so a key file saved there is readable", () => {+ const plan = runInTurn(turn, () => spawnIn(project));+ expect(visibleInBox(plan, project)).toBe("rw");+ expect(visibleInBox(plan, join(workspaceDir(BOT), ".openmausbot-secrets", "key.txt"))).toBe("rw");+ expect(visibleInBox(plan, join(ensureTaskWorkspace(BOT, "t1"), "handed.txt"))).toBe("rw");+ expect(plan.botId).toBe(BOT);+ });++ it("does the same for a project folder inside another bot's folder, without the rest of that folder", () => {+ const inOther = join(workspaceDir(OTHER), "grok-import");+ mkdirSync(inOther, { recursive: true });+ const plan = runInTurn(turn, () => spawnIn(inOther));+ expect(visibleInBox(plan, inOther)).toBe("rw");+ expect(visibleInBox(plan, join(workspaceDir(BOT), ".openmausbot-secrets", "key.txt"))).toBe("rw");+ expect(visibleInBox(plan, join(workspaceDir(OTHER), "MEMORY.md"))).toBe("none");+ });++ it("never gives it another bot's folders", () => {+ const plan = runInTurn(turn, () => spawnIn(project));+ expect(visibleInBox(plan, workspaceDir(OTHER))).toBe("none");+ expect(visibleInBox(plan, ensureTaskWorkspace(OTHER, "c1"))).toBe("none");+ expect(visibleInBox(plan, ensureTaskWorkspace(BOT, "t2"))).toBe("none");+ });++ it("keeps a bot the caller names over the turn's", () => {+ const plan = runInTurn(turn, () => spawnIn(project, { botId: OTHER }));+ expect(plan.botId).toBe(OTHER);+ expect(visibleInBox(plan, workspaceDir(BOT))).toBe("none");+ expect(visibleInBox(plan, ensureTaskWorkspace(BOT, "t1"))).toBe("none");+ });++ it("changes nothing for a spawn outside any turn, or with no working folder", () => {+ for (const plan of [spawnIn(project), runInTurn(turn, () => spawnIn(undefined))]) {+ expect(plan.botId).toBeNull();+ expect(visibleInBox(plan, workspaceDir(BOT))).toBe("none");+ }+ });++ it("leaves a conversation folder's box and a bot folder's box as their folder says", () => {+ const conversation = runInTurn(turn, () => spawnIn(ensureTaskWorkspace(OTHER, "c1")));+ expect(conversation.botId).toBe(OTHER);+ expect(visibleInBox(conversation, workspaceDir(BOT))).toBe("none");+ const room = runInTurn(turn, () => spawnIn(workspaceDir(OTHER)));+ expect(room.botId).toBeNull();+ expect(visibleInBox(room, workspaceDir(BOT))).toBe("none");+ });++ it("never lets two bots' turns in one project folder share an engine process", () => {+ const mine = runInTurn(turn, () => sharedBoxScope(project));+ const theirs = runInTurn({ botId: OTHER, threadId: "t2" }, () => sharedBoxScope(project));+ expect(mine).not.toBe(theirs);+ expect(runInTurn({ botId: BOT, threadId: "t3" }, () => sharedBoxScope(project))).toBe(mine);+ });++ it("keeps the conversation folder out of a process the bot's conversations share", () => {+ const plan = runInTurn(turn, () => spawnIn(project, { botThreads: true }));+ expect(visibleInBox(plan, workspaceDir(BOT))).toBe("rw");+ expect(visibleInBox(plan, ensureTaskWorkspace(BOT, "t1"))).toBe("none");+ });+});diff --git a/server/procs.ts b/server/procs.tsindex 324463746d..6fe298b080 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -14,11 +14,12 @@ import { closeSync, existsSync, readdirSync, readFileSync, realpathSync } from "import type { Readable, Writable } from "node:stream";import { basename, dirname, join, resolve } from "node:path";import { botBox, type WrappedSpawn } from "./bot-box/box.ts";-import type { BoxRequest } from "./bot-box/plan.ts";+import { type BoxRequest, under } from "./bot-box/plan.ts";import { homeProgramsDistrusted, serverMayRunFrom, serverPath } from "./bot-box/program-trust.ts";import { engineMemory } from "./engine-memory.ts";import { ENGINE_TAG_ENV, engineRunTag, engineStopped, recordEngine } from "./engine-records.ts";import { engineHomes } from "./engine-homes/engine-homes.ts";+import { currentTurn } from "./crash-guard.ts";import type { HomedSpawn } from "./engine-homes/layout.ts";import { resolveCliSpawn, type ResolvedSpawn } from "./env-path.ts";import { spawnBotWork } from "./oom-score.ts";@@ -266,7 +267,20 @@ export function boxedSpawn(resolved: ResolvedSpawn, opts: CliSpawnOptions, ownerconst request = typeof opts.box === "object" ? opts.box : {};const home = homed ? { home: homed.home, shared: homed.shared } : {};const threadId = engineHomes.thread(), conversationBot = engineHomes.bot();- return botBox.wrap({ command: resolved.command, args: resolved.args, cwd: typeof opts.cwd === "string" ? opts.cwd : undefined, env: opts.env ?? process.env, ...(threadId ? { threadId } : {}), ...(conversationBot ? { conversationBot } : {}), ...request, ...home });+ const cwd = typeof opts.cwd === "string" ? opts.cwd : undefined;+ const turn = projectFolderTurn(cwd);+ return botBox.wrap({ command: resolved.command, args: resolved.args, cwd, env: opts.env ?? process.env, ...(threadId ? { threadId } : {}), ...(conversationBot ? { conversationBot } : {}), ...turn, ...request, ...home });+}++/** The turn (crash-guard.ts) of a spawn working outside its bot's folders (a configured project folder, which may be in+ * another bot's folder), so its box gets that bot's own folder and conversation folder too. A conversation folder and a+ * bot's folder itself (a room's turn) already say whose they are. */+function projectFolderTurn(cwd: string | undefined): { botId: string; conversationFolder: string } | null {+ const dataDir = botBox.startOptions()?.dataDir, turn = currentTurn();+ if (!cwd || !dataDir || !turn?.botId) return null;+ const full = resolve(cwd), workspaces = join(resolve(dataDir), "workspaces"), conversations = join(resolve(dataDir), "task-workspaces");+ if (under(full, conversations) || dirname(full) === workspaces || full === workspaces) return null;+ return { botId: turn.botId, conversationFolder: join(conversations, turn.botId, turn.threadId) };}/** What the audience rule gives a box in `cwd` now, as a key (null off a team or with the box off): a process kept@@ -283,7 +297,11 @@ export function boxAudienceKey(cwd: string): string | null {export function sharedBoxScope(cwd: string): string | null {if (!botBox.enabled()) return null;const parent = dirname(resolve(cwd));- if (basename(dirname(parent)) !== "task-workspaces") return resolve(cwd);+ if (basename(dirname(parent)) !== "task-workspaces") {+ // Another bot's turn in the same project folder has that bot's folder in its box, so it never shares this process.+ const turn = projectFolderTurn(cwd);+ return turn ? `${resolve(cwd)}#${turn.botId}` : resolve(cwd);+ }const threadId = engineHomes.thread(), conversationBot = engineHomes.bot();const threads = botBox.sharedThreadsKey({ cwd, ...(threadId ? { threadId } : {}), ...(conversationBot ? { conversationBot } : {}) });return threads ? `${parent}#${createHash("sha256").update(threads).digest("hex").slice(0, 16)}` : parent;