Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bot box: a shared OpenCode process serves only its bot's conversations, boxed with all of their folders (#4788)
Milind Soni90102ee90086
diff --git a/server/bot-box/box.ts b/server/bot-box/box.tsindex c28a2c207d..c626b66dea 100644--- a/server/bot-box/box.ts+++ b/server/bot-box/box.ts@@ -124,11 +124,13 @@ export class BoxRunner {if (!broker || plan.net !== "isolated") return { env, token: null, release: () => {}, unbrokered: [] };const ids = request.cwd ? taskWorkspaceIds(request.cwd, this.options.setup.dataDir) : null;// The token is minted first (its value goes in the environment), then granted exactly what the rewrite took out.- const minted = broker.mintForProcess({ botId: plan.botId, threadId: ids?.threadId ?? null, grants: {} });+ // A process the bot's conversations share belongs to none of them.+ const threadId = request.botThreads ? null : ids?.threadId ?? null;+ const minted = broker.mintForProcess({ botId: plan.botId, threadId, grants: {} });const rewrite = brokerRewrite(env, minted.token, broker.port);broker.revoke(minted.token);if (!Object.keys(rewrite.grants).length) return { env, token: null, release: () => {}, unbrokered: rewrite.unbrokered };- const granted = broker.mintForProcess({ botId: plan.botId, threadId: ids?.threadId ?? null, grants: rewrite.grants });+ const granted = broker.mintForProcess({ botId: plan.botId, threadId, grants: rewrite.grants });const again = brokerRewrite(env, granted.token, broker.port);return { env: again.env, token: granted.token, release: () => broker.revoke(granted.token), unbrokered: again.unbrokered };}diff --git a/server/bot-box/plan.test.ts b/server/bot-box/plan.test.tsindex 08d84eb3dc..671463f46d 100644--- a/server/bot-box/plan.test.ts+++ b/server/bot-box/plan.test.ts@@ -44,6 +44,17 @@ linuxBox("the box plan", () => {expect(visibleInBox(plan, "/root/.ssh/id_ed25519")).toBe("none");});+ it("a process the bot's conversations share sees all of that bot's conversation folders and uploads, and no other bot's", () => {+ const plan = planBox(setup(), { command: "opencode", args: ["acp"], cwd, env: { HOME: home }, botThreads: true });+ expect(plan.botId).toBe("bot-a");+ for (const own of ["task-workspaces/bot-a/thread-1/a.md", "task-workspaces/bot-a/thread-2/notes.md", "workspaces/bot-a/MEMORY.md"]) expect(visibleInBox(plan, join(dataDir, own)), own).toBe("rw");+ expect(visibleInBox(plan, join(dataDir, "box-uploads", "bot-a", "thread-2", "photo.png"))).toBe("ro");+ for (const hidden of ["task-workspaces/bot-b/thread-9/notes.md", "workspaces/bot-b/MEMORY.md", "box-uploads/bot-b/thread-9/x.png", "messages.db"]) {+ expect(visibleInBox(plan, join(dataDir, hidden)), hidden).toBe("none");+ }+ expect(visibleInBox(turn(), join(dataDir, "box-uploads", "bot-a", "thread-2", "photo.png")), "one conversation's box keeps only its own uploads").toBe("none");+ });+it("writes the bubblewrap argv in mount order, with its own namespaces and the bridged sockets", () => {const args = bwrapArgs(turn());const text = args.join(" ");diff --git a/server/bot-box/plan.ts b/server/bot-box/plan.tsindex bd42038aae..d72cd1e412 100644--- a/server/bot-box/plan.ts+++ b/server/bot-box/plan.ts@@ -68,6 +68,9 @@ export interface BoxRequest {net?: BoxNet;/** The bot whose own folder (workspaces/<bot>) is put back; derived from a task-workspace cwd when absent. */botId?: string;+ /** One process serves every conversation of the bot (a shared OpenCode process): all of the bot's conversation folders+ * are read-write and all of their uploads read-only, in place of only the starting conversation's. */+ botThreads?: boolean;/** A Team Cloud audience's engine home, bound read-write in place of the server's HOME, none of which the box then has. */home?: string;/** Files bound read-write over their names in `home`: the team's engine sign-ins. */@@ -179,6 +182,8 @@ export function planBox(setup: BoxSetup, request: BoxRequest): BoxPlan {const cwd = request.cwd ? resolve(request.cwd) : null;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));if (cwd && !covered(cwd)) rw(cwd);if (botId && ID.test(botId)) {const own = join(dataDir, "workspaces", botId);@@ -206,7 +211,7 @@ 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 = boxUploadsDir(dataDir, ids.botId, ids.threadId);+ 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 readOnly = new Set<string>();diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 8d8a209ec5..9be470eafe 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -17,7 +17,7 @@ import { decodeInjectId } from "../local-inject.ts";import { DeviceAuthController, type DeviceSignIn } from "../device-auth.ts";import { deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSessionPrompt, writePromptSplitReceipt } from "../prompt-split.ts";import type { PromptSplitReceipt } from "../prompt-split.ts";-import { describeSpawnFailure, execCli, killCliTree, spawnCli } from "../../procs.ts";+import { describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts";import { runAcpOneShot } from "./background-text.ts";import { sanitizeAcpToolMessage } from "./tool-log.ts";import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";@@ -632,7 +632,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) } }, "bot");+ const child = spawnCli(launch.command, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv: instanceEnvNames(input.environment, env), botThreads: hostKey !== null } }, "bot");const host = new AcpHost(child, hostKey, { source: SOURCE, logMessage: nativeLogMessage, unrouted: refuse });hosts.add(host);child.once("close", () => hosts.delete(host));@@ -1093,8 +1093,8 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>? { ...spawnEnv, [support.sessionModelEnv]: launchModel }: spawnEnv;let launchedThisTurn = false;- // The folder and the tool selection ride session/new, so threads differing only there can share a process; never two audiences of a Team Cloud, whose engine homes differ.- const hostKey = support.shareProcess && inheritedScopeFingerprint === null ? JSON.stringify([...processContract, launchModel ?? null, engineHomes.scope()]) : null;+ // The folder and the tool selection ride session/new, so threads differing only there can share a process (in the bot box, only one bot's); never two audiences of a Team Cloud, whose engine homes differ.+ const hostKey = support.shareProcess && inheritedScopeFingerprint === null ? JSON.stringify([...processContract, launchModel ?? null, engineHomes.scope(), sharedBoxScope(cwd)]) : null;const launchSession = () => {const opened = openSession(threadId, launch, [...(launch.args ?? []), ...spawnArgs], launchEnv, cwd, contractKey, hostKey);opened.launchModel = launchModel;diff --git a/server/drivers/acp/shared-process.test.ts b/server/drivers/acp/shared-process.test.tsindex 3929ece837..75fde0761f 100644--- a/server/drivers/acp/shared-process.test.ts+++ b/server/drivers/acp/shared-process.test.ts@@ -7,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { ProviderInstance, RuntimeEvent, SendTurnInput } from "../../contracts.ts";import { TurnNotStartedError } from "../../contracts.ts";+import { botBox } from "../../bot-box/box.ts";import { engineHomes } from "../../engine-homes/engine-homes.ts";import * as procs from "../../procs.ts";import { removeTempDir } from "../../testing/cleanup.ts";@@ -128,6 +129,20 @@ describe("ACP threads sharing one agent process", () => {expect(f.spawned).toHaveLength(3);});+ it("in the bot box shares a process only among one bot's conversations, boxed with all of that bot's conversation folders", async () => {+ vi.spyOn(botBox, "enabled").mockReturnValue(true);+ const f = await fixture();+ const folder = (bot: string, thread: string) => join(f.scratch, "task-workspaces", bot, thread);+ for (const [bot, thread] of [["bot-a", "thread-a"], ["bot-a", "thread-b"], ["bot-b", "thread-c"]]) mkdirSync(folder(bot, thread), { recursive: true });+ await f.run("thread-a", { cwd: folder("bot-a", "thread-a") });+ await f.run("thread-b", { cwd: folder("bot-a", "thread-b") });+ expect(f.spawned, "the second conversation of the same bot joins its process").toHaveLength(1);+ await f.run("thread-c", { cwd: folder("bot-b", "thread-c") });+ expect(f.spawned, "another bot's folders are not in that process's box").toHaveLength(2);+ const boxes = vi.mocked(procs.spawnCli).mock.calls.filter((call) => call[3] === "bot").map((call) => call[2].box);+ expect(boxes.every((box) => typeof box === "object" && box.botThreads === true)).toBe(true);+ });+it("on a Team Cloud never shares a process between two audiences, whose engines have homes of their own", async () => {const f = await fixture();const dataDir = mkdtempSync(join(tmpdir(), "omb-acp-homes-"));diff --git a/server/procs.ts b/server/procs.tsindex 3b79e77f8e..35280bb6ee 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -11,7 +11,7 @@ import {} from "node:child_process";import { closeSync, existsSync, readdirSync, readFileSync } from "node:fs";import type { Readable, Writable } from "node:stream";-import { join } from "node:path";+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 { engineMemory } from "./engine-memory.ts";@@ -173,7 +173,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" | "allowEnv" | "relay">;+ box?: boolean | Pick<BoxRequest, "rw" | "ro" | "net" | "botId" | "botThreads" | "allowEnv" | "relay">;/** 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`@@ -190,6 +190,14 @@ export function boxedSpawn(resolved: ResolvedSpawn, opts: CliSpawnOptions, ownerreturn botBox.wrap({ command: resolved.command, args: resolved.args, cwd: typeof opts.cwd === "string" ? opts.cwd : undefined, env: opts.env ?? process.env, ...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`. */+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);+}+export function spawnCli(cli: string,args: string[],