Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(claude): a bot's question reaches the person from inside the bot box (#3913)
Milind Soni8537559a98a3
diff --git a/docs/bot-box.md b/docs/bot-box.mdindex 3621e1c3fa..58228c95f8 100644--- a/docs/bot-box.md+++ b/docs/bot-box.md@@ -13,7 +13,7 @@ its database, its settings, other bots' folders and other turns' processes are n| `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: this turn's permission socket and the files its command line names (MCP config, system prompt), read-only | What the driver made for this one process |+| put back: this turn's permission socket (the engine's question and approval helper reaches the server through it), and, read-only, 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 || a network namespace with loopback only | Two loopback ports are bridged to unix sockets from outside (below); nothing else on the machine's loopback is reachable, and there is no route out |diff --git a/server/bot-box/ask-socket.linux.test.ts b/server/bot-box/ask-socket.linux.test.tsnew file mode 100644index 0000000000..edf422f743--- /dev/null+++ b/server/bot-box/ask-socket.linux.test.ts@@ -0,0 +1,67 @@+// A bot's question from inside a real box, where one can run: Linux with an unprivileged bubblewrap (a Cloud home, the Fly+// test machine). The question tool's helper (permission-proxy.ts) runs in the box with the engine and reaches the broker+// through the socket the driver puts back. Elsewhere the suite says so and skips, like the box's own self-check.+import { spawn } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, describe, expect, it } from "vitest";++import { createPermissionBroker } from "../drivers/claude.ts";+import { SPAWNED_PROXIES } from "../proxy-paths.ts";+import { defaultCodeRoots } from "./box.ts";+import { detectBox } from "./detect.ts";+import { bwrapArgs, planBox } from "./plan.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-box-ask-"));+afterAll(() => rmSync(root, { recursive: true, force: true }));++const home = join(root, "home"), dataDir = join(home, ".openmausbot"), cwd = join(dataDir, "task-workspaces", "bot-a", "t-1");+const env = { PATH: "/usr/bin:/bin", HOME: home };++/** One ask_user call through the helper in a box that puts back `rw`; the helper's MCP result. */+function askInBox(socket: string, rw: string[]): Promise<{ content: Array<{ text: string }>; isError?: boolean }> {+ const plan = planBox({ dataDir, home, codeRoots: defaultCodeRoots(), engineRoots: [], bridges: [] }, { command: process.execPath, args: [], cwd, env, rw });+ const child = spawn(detection.tools!.bwrap, [...bwrapArgs(plan), "--", process.execPath, SPAWNED_PROXIES.permission, socket], { env, stdio: ["pipe", "pipe", "inherit"] });+ return new Promise((resolve, reject) => {+ let out = "";+ const timer = setTimeout(() => { child.kill(); reject(new Error(`no answer from the helper in the box: ${out}`)); }, 20_000);+ child.stdout.setEncoding("utf8");+ child.stdout.on("data", (chunk: string) => {+ out += chunk;+ const reply = out.split("\n").map((line) => { try { return JSON.parse(line); } catch { return null; } }).find((msg) => msg?.id === 1);+ if (!reply) return;+ clearTimeout(timer);+ child.kill();+ resolve(reply.result);+ });+ child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "ask_user", arguments: { question: "Which account?" } } }) + "\n");+ });+}++describe.skipIf(!available)(`a bot's question from inside a real box (${available ? "bubblewrap works here" : `skipped: ${detection.reason}`})`, () => {+ it("reaches the broker through the socket put back in the box, and says what to do instead without it", async () => {+ mkdirSync(cwd, { recursive: true });+ const asked: string[] = [];+ const broker = await createPermissionBroker({+ socketPaths: [join(dataDir, "perm-test.sock")],+ onAsk: (ask) => {+ asked.push(String(ask.input.question));+ broker.answer(ask.id, "answer", "Work");+ },+ onResolve: () => {},+ });+ try {+ expect(await askInBox(broker.socketPath, [broker.socketPath])).toEqual({ content: [{ type: "text", text: "Work" }] });+ expect(asked).toEqual(["Which account?"]);+ const hidden = await askInBox(broker.socketPath, []);+ expect(hidden.isError).toBe(true);+ expect(hidden.content[0]!.text).toContain("could not show this question to the person");+ expect(asked).toHaveLength(1);+ } finally {+ broker.close();+ }+ }, 60_000);+});diff --git a/server/drivers/claude-box.test.ts b/server/drivers/claude-box.test.tsnew file mode 100644index 0000000000..bf6886ed1d--- /dev/null+++ b/server/drivers/claude-box.test.ts@@ -0,0 +1,73 @@+// A Claude turn where the bot box is on (every Cloud home): the engine and the helpers it starts see only what the box puts+// back, and the data folder is empty in there. The question tool's helper reaches the broker through a socket the driver+// makes in the data folder, so the box must put that socket back. Off a Cloud the box is off and nothing changes.+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, describe, expect, it, vi } from "vitest";++import { botBox, type WrappedSpawn } from "../bot-box/box.ts";+import { visibleInBox } from "../bot-box/plan.ts";+import { DATA_DIR, ensureDirs } from "../config.ts";+import type { ProviderInstance } from "../contracts.ts";+import { removeTempDir } from "../testing/cleanup.ts";+import { recordEvents } from "../testing/events.ts";+import { ClaudeDriver } from "./claude.ts";++const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-claude-cli.ts");+const KNOBS = ["FAKE_CLAUDE_DUMP", "FAKE_CLAUDE_TOOL_CALLS", "FAKE_CLAUDE_MODE"] as const;+const TMPDIR = process.env.TMPDIR;++describe("a Claude turn in the bot box", () => {+ const dirs: string[] = [];+ let instance: ProviderInstance | null = null;+ afterEach(async () => {+ await instance?.dispose();+ instance = null;+ vi.restoreAllMocks();+ await botBox.stop();+ for (const name of KNOBS) delete process.env[name];+ if (TMPDIR === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = TMPDIR;+ for (const dir of dirs.splice(0)) await removeTempDir(dir);+ });++ // The box's gates listen on unix sockets, which Windows refuses at a file path; the box runs only on a Linux Cloud home.+ it.skipIf(process.platform === "win32")("puts the turn's permission socket in the box, so the bot's question reaches the person", async () => {+ ensureDirs();+ chmodSync(FAKE_CLI, 0o755);+ const scratch = mkdtempSync(join(tmpdir(), "omb-claude-box-"));+ dirs.push(scratch);+ // A stand-in for bubblewrap: no namespaces, it runs what follows `--`; the plan it was given is what the test reads.+ const fakeBwrap = join(scratch, "fake-bwrap.sh");+ writeFileSync(fakeBwrap, `#!/bin/sh\nwhile [ "$1" != "--" ]; do shift; done; shift\nexec "$@"\n`);+ chmodSync(fakeBwrap, 0o755);+ await botBox.start({+ dataDir: DATA_DIR, home: homedir(), port: 8799, denyEnv: new Set(), env: {}, log: () => {},+ // /usr/bin/true stands in for socat: the shell init starts it, waits once, and execs the engine.+ detect: () => ({ box: "bwrap", reason: null, tools: { bwrap: fakeBwrap, socat: "/usr/bin/true" } }),+ });+ const wrap = vi.spyOn(botBox, "wrap");+ // A Cloud has no TMPDIR; here it holds the test's home, and the box puts back the folder TMPDIR names.+ delete process.env.TMPDIR;+ const dump = join(scratch, "dump.json");+ process.env.FAKE_CLAUDE_DUMP = dump;+ process.env.FAKE_CLAUDE_TOOL_CALLS = JSON.stringify([{ name: "ask_user", server: "ogb", input: { question: "Which account?" } }]);+ instance = await ClaudeDriver.create({ instanceId: "claude-box", displayName: "Claude", environment: {}, enabled: true, config: { cli: FAKE_CLI, permissionMode: "acceptEdits" } });+ const recorder = recordEvents(instance.adapter);+ const cwd = join(DATA_DIR, "task-workspaces", "bot-a", "t-boxed-ask");+ mkdirSync(cwd, { recursive: true });++ await instance.adapter.sendTurn({ threadId: "t-boxed-ask", botId: "bot-a", text: "Pick the account", approvalMode: "full", cwd });+ const opened = await recorder.until((event) => event.type === "request.opened", 30_000) as { requestId: string; requestType: string };+ expect(opened.requestType).toBe("question");+ expect(await instance.adapter.respondToRequest("t-boxed-ask", opened.requestId, { behavior: "answer", message: "Work" })).toBe("answered");+ await recorder.until((event) => event.type === "turn.completed", 30_000);++ const boxed = wrap.mock.results.map((result) => result.value as WrappedSpawn | null).find((spawned) => spawned?.plan.botId === "bot-a");+ expect(boxed, "the engine ran in the box").toBeTruthy();+ const socket = JSON.parse(readFileSync(dump, "utf8")).mcpConfig.mcpServers.ogb.args[1] as string;+ expect(visibleInBox(boxed!.plan, join(DATA_DIR, "messages.db")), "the data folder is empty in the box, as on a Cloud").toBe("none");+ expect(visibleInBox(boxed!.plan, socket), "the question tool's socket is in the box").toBe("rw");+ }, 60_000);+});diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 52ad176fc5..e0086f54a0 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -1359,11 +1359,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {let child: ReturnType<typeof spawnCli>;try {- child = spawnCli(config.cli, args, {- cwd,- env,- stdio: ["pipe", "pipe", "pipe"],- }, "bot");+ child = spawnCli(config.cli, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], ...(broker ? { box: { rw: [broker.socketPath] } } : {}) }, "bot");} catch (error) {cleanupUnownedLaunch();throw error;diff --git a/server/permission-proxy.test.ts b/server/permission-proxy.test.tsindex e177f4c204..0f23d7f0c9 100644--- a/server/permission-proxy.test.ts+++ b/server/permission-proxy.test.ts@@ -36,6 +36,7 @@ describe("permission proxy", () => {let asks: any[];let answerWith: (ask: any, index: number) => Record<string, unknown> | null;let conns: Socket[];+ let listen: () => Promise<void>;const results = new Map<number, any>();const rpc = (msg: unknown) => proxy.stdin!.write(JSON.stringify(msg) + "\n");@@ -77,7 +78,11 @@ describe("permission proxy", () => {conns = [];answerWith = () => null;const socketPath = brokerSocketPath(scratch, "test");- broker = createServer((conn: Socket) => {+ listen = async () => {+ broker = createServer(onConnection);+ await new Promise<void>((resolve) => broker.listen(socketPath, resolve));+ };+ const onConnection = (conn: Socket) => {conns.push(conn);let buf = "";conn.on("error", () => {});@@ -96,8 +101,8 @@ describe("permission proxy", () => {if (answer) conn.write(JSON.stringify({ t: "answer", id: ask.id, ...answer }) + "\n");}});- });- await new Promise<void>((resolve) => broker.listen(socketPath, resolve));+ };+ await listen();startProxy(socketPath);rpc({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} });@@ -107,10 +112,16 @@ describe("permission proxy", () => {afterEach(async () => {results.clear();proxy?.kill();- await new Promise<void>((resolve) => broker.close(() => resolve()));+ if (broker.listening) await new Promise<void>((resolve) => broker.close(() => resolve()));removeTempDir(scratch);});+ /** The broker stops listening and drops every connection, as when the socket is gone or unreachable. */+ const brokerGone = async () => {+ for (const conn of conns.splice(0)) conn.destroy();+ await new Promise<void>((resolve) => broker.close(() => resolve()));+ };+it("withholds an excluded question without losing the CLI permission callback", async () => {const exited = once(proxy, "exit"); proxy.kill(); await exited; results.clear();startProxy(brokerSocketPath(scratch, "test"), { ...process.env, OMB_PERMISSION_TOOL_SCOPE: JSON.stringify({ allow: ["native:*"] }) });@@ -392,4 +403,43 @@ describe("permission proxy", () => {const res = await waitFor(2);expect(resultJson(res)).toMatchObject({ behavior: "deny" });});++ it("tells a waiting question what to do when its connection drops, and asks the next one on a new connection", async () => {+ answerWith = () => null;+ rpc({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "ask_user", arguments: { question: "One?" } } });+ await waitForAsks(1);+ for (const conn of conns.splice(0)) conn.destroy();+ const dropped = await waitFor(2);+ expect(dropped.result.isError).toBe(true);+ expect(dropped.result.content[0].text).toContain("Ask in your reply instead");+ answerWith = () => ({ behavior: "answer", message: "second", source: "user" });+ rpc({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "ask_user", arguments: { question: "Two?" } } });+ expect((await waitFor(3)).result.content[0].text).toBe("second");+ expect(asks.map((ask) => ask.input.question)).toEqual(["One?", "Two?"]);+ expect(conns).toHaveLength(1);+ });++ it("tells the bot what to do instead while nobody can be asked, and asks once the broker is back", async () => {+ await brokerGone();+ rpc({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "ask_user", arguments: { question: "Which account?" } } });+ const question = await waitFor(2);+ expect(question.result.isError).toBe(true);+ expect(question.result.content[0].text).toMatch(/could not show this question to the person.*Ask in your reply instead: end it with the exact question/);+ rpc({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "approve", arguments: { tool_name: "Bash", input: { command: "git push" } } } });+ expect(resultJson(await waitFor(3))).toEqual({+ behavior: "deny",+ message: expect.stringMatching(/could not ask the person to approve this step.*Skip this step, and say in your reply what you wanted to do and why/),+ });+ rpc({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "approve", arguments: { tool_name: "AskUserQuestion", input: QUESTION } } });+ expect(resultJson(await waitFor(4))).toMatchObject({ behavior: "deny", message: expect.stringContaining("Ask in your reply instead") });+ expect(asks).toEqual([]);++ await listen();+ answerWith = () => ({ behavior: "answer", message: "Work", source: "user" });+ rpc({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "ask_user", arguments: { question: "Which account?" } } });+ const answered = await waitFor(5);+ expect(answered.result.content[0].text).toBe("Work");+ expect(answered.result.isError).toBeUndefined();+ expect(asks).toHaveLength(1);+ }, 20_000);});diff --git a/server/permission-proxy.ts b/server/permission-proxy.tsindex 385c408986..55453320b7 100644--- a/server/permission-proxy.ts+++ b/server/permission-proxy.ts@@ -1,7 +1,8 @@// MCP stdio server the claude CLI spawns for --permission-prompt-tool; forwards each ask to the server's broker over a unix socket.// stdout is the MCP channel: never console.log here.-import { connect } from "node:net";+import { connect, type Socket } from "node:net";import { randomUUID } from "node:crypto";+import { setTimeout as sleep } from "node:timers/promises";import { parseAskQuestions, questionAnswersByQuestion, type AskQuestion } from "../shared/ask-question.ts";import { allowsTool, parseToolScope } from "../shared/tool-scope.ts";import { REFUSED_NEXT_STEP } from "./reply-habits.ts";@@ -13,56 +14,105 @@ const allowQuestion = allowsTool(selection.scope, { kind: "mcp", server: "ogb",const socketPath = process.argv[2] ?? "";-const waiting = new Map<string, (msg: any) => void>();-const conn = connect(socketPath);-// JSON lines can span reads; a stream decoder keeps a split character whole.-conn.setEncoding("utf8");-+interface BrokerAnswer {+ behavior?: string;+ message?: string;+ source?: string;+ always?: boolean;+}+type AskKind = "question" | "permission";interface AllowPermissionResult {behavior: "allow";updatedInput: object;updatedPermissions?: object[];}-const dead = () => {- for (const resolve of waiting.values()) {- resolve({ behavior: "deny", message: "OpenMausBot: permission broker unavailable — skip this action" });- }- waiting.clear();++/** What the bot is told when the person cannot be asked at all: what to do instead, so it never just skips. */+const UNREACHABLE_NOTE: Record<AskKind, string> = {+ question:+ "OpenMausBot could not show this question to the person: its question service did not answer. Do not retry this tool. Ask in your reply instead: end it with the exact question and stop there until they answer.",+ permission:+ "OpenMausBot could not ask the person to approve this step: its approval service did not answer. Skip this step, and say in your reply what you wanted to do and why, so the person can decide.",};-conn.on("error", dead);-conn.on("close", dead);+const unreachable = (kind: AskKind): BrokerAnswer => ({ behavior: "deny", message: UNREACHABLE_NOTE[kind], source: "system" });-let connBuf = "";-conn.on("data", (chunk) => {- connBuf += chunk;- let nl;- while ((nl = connBuf.indexOf("\n")) !== -1) {- const line = connBuf.slice(0, nl);- connBuf = connBuf.slice(nl + 1);- let msg: any;- try {- msg = JSON.parse(line);- } catch {- continue;- }- if (msg.t === "answer") {- waiting.get(msg.id)?.(msg);- waiting.delete(msg.id);+/** Asks waiting for the broker, by id; an answer only ever comes back on the connection its ask went out on. */+const waiting = new Map<string, { conn: Socket; kind: AskKind; resolve: (answer: BrokerAnswer) => void }>();+let live: Socket | null = null;+let opening: Promise<Socket | null> | null = null;++function open(): Promise<Socket | null> {+ return new Promise((resolve) => {+ const conn = connect(socketPath);+ // JSON lines can span reads; a stream decoder keeps a split character whole.+ conn.setEncoding("utf8");+ let connected = false;+ let buf = "";+ conn.on("data", (chunk) => {+ buf += chunk;+ let nl;+ while ((nl = buf.indexOf("\n")) !== -1) {+ const line = buf.slice(0, nl);+ buf = buf.slice(nl + 1);+ let msg: any;+ try {+ msg = JSON.parse(line);+ } catch {+ continue;+ }+ const entry = msg?.t === "answer" ? waiting.get(String(msg.id)) : undefined;+ if (entry?.conn !== conn) continue;+ waiting.delete(String(msg.id));+ entry.resolve(msg);+ }+ });+ conn.once("connect", () => {+ connected = true;+ resolve(conn);+ });+ conn.on("error", () => {});+ conn.once("close", () => {+ if (!connected) resolve(null);+ if (live === conn) live = null;+ for (const [id, entry] of waiting) {+ if (entry.conn !== conn) continue;+ waiting.delete(id);+ entry.resolve(unreachable(entry.kind));+ }+ });+ });+}++/** The connection to the broker, opened again after a drop; a few quick tries ride out a broker that is still binding. */+function brokerConnection(): Promise<Socket | null> {+ if (live && !live.destroyed) return Promise.resolve(live);+ opening ??= (async () => {+ for (const pause of [0, 200, 800]) {+ if (pause) await sleep(pause);+ const conn = await open();+ if (conn) return (live = conn);}- }-});+ return null;+ })().finally(() => {+ opening = null;+ });+ return opening;+}+// Connected at start, so a process that outlives its session never reaches a newer broker bound at the same path.+void brokerConnection();const send = (obj: unknown) => process.stdout.write(JSON.stringify(obj) + "\n");-function askBroker(ask: Record<string, unknown>): Promise<any> {+async function askBroker(ask: Record<string, unknown> & { id: string }, kind: AskKind): Promise<BrokerAnswer> {+ const conn = await brokerConnection();+ if (!conn || conn.destroyed) return unreachable(kind);return new Promise((resolve) => {- waiting.set(String(ask.id), resolve);- if (conn.destroyed) return dead();- try {- conn.write(JSON.stringify(ask) + "\n");- } catch {- dead();- }+ waiting.set(ask.id, { conn, kind, resolve });+ conn.write(JSON.stringify(ask) + "\n", (error) => {+ if (!error || waiting.get(ask.id)?.conn !== conn) return;+ waiting.delete(ask.id);+ resolve(unreachable(kind));+ });});}@@ -88,13 +138,7 @@ async function answerNativeQuestions(input: unknown): Promise<string> {"OpenMausBot: this AskUserQuestion call had no answerable question (each one needs question text), so nobody was shown it. Ask again with a well-formed call, or continue without it.",});}- const answer = await askBroker({- t: "ask",- id: randomUUID(),- kind: "question",- tool: ASK_USER_QUESTION,- input: { questions },- });+ const answer = await askBroker({ t: "ask", id: randomUUID(), kind: "question", tool: ASK_USER_QUESTION, input: { questions } }, "question");if (answer.behavior === "deny") {return JSON.stringify({ behavior: "deny", message: answer.message || "Denied from OpenMausBot" });}@@ -160,7 +204,7 @@ async function handle(msg: any) {if (msg.method === "tools/call") {const name = msg.params?.name;const args = msg.params?.arguments ?? {};- const reply = (text: string) => send({ jsonrpc: "2.0", id: msg.id, result: { content: [{ type: "text", text }] } });+ const reply = (text: string, isError = false) => send({ jsonrpc: "2.0", id: msg.id, result: { content: [{ type: "text", text }], ...(isError ? { isError } : {}) } });if (name === "ask_user" && !allowQuestion) return reply("OpenMausBot: this question tool is excluded by the bot's tool selection.");if (name === "approve" && args.tool_name === ASK_USER_QUESTION) {return reply(await answerNativeQuestions(args.input));@@ -174,10 +218,11 @@ async function handle(msg: any) {: Array.isArray(args.suggestions)? args.suggestions: null;- const answer: any = await askBroker(+ const answer = await askBroker(isQuestion? { t: "ask", id: askId, kind: "question", tool: "ask_user", input: { question: args.question, choices: args.choices, ...(picksSeveral ? { questions: picksSeveral } : {}) } }: { t: "ask", id: askId, tool: args.tool_name, input: args.input },+ isQuestion ? "question" : "permission",);let text = answer.message || "No answer was given — use your best judgment.";if (picksSeveral && answer.source === "user" && typeof answer.message === "string") {@@ -192,7 +237,7 @@ async function handle(msg: any) {text = JSON.stringify({ behavior: "deny", message: (answer.message || "Denied from OpenMausBot") + (answer.source === "user" ? REFUSED_NEXT_STEP : "") });}}- return reply(text);+ return reply(text, isQuestion && answer.behavior === "deny");}if (String(msg.method ?? "").startsWith("notifications/")) return;if (msg.id != null) {