Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Run keep-warm pings, warm summaries and app connections in the bot box (#5224)

Milind Sonib8022684d1f5
diff --git a/server/chat-apps-mcp.test.ts b/server/chat-apps-mcp.test.ts
index 27f86b3b8a..545ccb5b5c 100644
--- a/server/chat-apps-mcp.test.ts
+++ b/server/chat-apps-mcp.test.ts
@@ -35,7 +35,7 @@ const REPORT = {
const cleanup: Array<() => Promise<void> | void> = [];
afterEach(async () => { for (const step of cleanup.splice(0).reverse()) await step(); });
-function setup(options: { servers?: Record<string, Record<string, unknown>>; scope?: BotRecord["toolScope"]; approval?: "ask" | "full"; needsSignIn?: string[]; probe?: typeof probeMcpServer; oauth?: ChatAppsMcpOAuth; startupProbes?: boolean } = {}) {
+function setup(options: { servers?: Record<string, Record<string, unknown>>; scope?: BotRecord["toolScope"]; approval?: "ask" | "full"; needsSignIn?: string[]; probe?: typeof probeMcpServer; oauth?: ChatAppsMcpOAuth; startupProbes?: boolean; probeAs?: (server: { bot?: string }) => { id?: string; cwd?: string } } = {}) {
const dataDir = mkdtempSync(join(tmpdir(), "omb-chat-apps-mcp-"));
cleanup.push(() => removeTempDir(dataDir));
const threads = new Map<string, Message[]>();
@@ -74,6 +74,7 @@ function setup(options: { servers?: Record<string, Record<string, unknown>>; sco
oauth: options.oauth ?? { authState: (name) => (options.needsSignIn?.includes(name) ? "needs-sign-in" : "none"), accessToken: async () => null, requireSignIn: () => {} },
startupProbes: options.startupProbes ?? false,
...(options.probe ? { probe: options.probe } : {}),
+ ...(options.probeAs ? { probeAs: options.probeAs } : {}),
log: (line) => lines.push(line),
});
cleanup.push(() => { mcp.close(); apps.close(); });
@@ -312,6 +313,17 @@ describe("mounts and probes", () => {
expect(probe).toHaveBeenCalledTimes(1);
});
+ it("starts a command server for its background probe the way the bots' turns start it, never beside the server", async () => {
+ const probe = vi.fn(async () => ({ ok: false as const, error: "offline" }));
+ const probeAs = vi.fn((server: { bot?: string }) => (server.bot ? { id: server.bot, cwd: `/data/workspaces/${server.bot}` } : {}));
+ const { mcp, servers } = setup({ probe, probeAs, servers: { board: { ...board(), enabled: true }, own: { ...board(), enabled: true, bot: "bot-scout" } } });
+ expect(mcp.turnMounts({ board: board(), own: board() })).toEqual({});
+ await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(2));
+ // `asBot` is what makes the probe ask for the bot box (server/mcp-probe.ts); without it the command runs unboxed.
+ expect(probe.mock.calls.map((call) => (call as unknown as [unknown, unknown, unknown, { asBot?: unknown }])[3].asBot)).toEqual([{}, { id: "bot-scout", cwd: "/data/workspaces/bot-scout" }]);
+ expect(Object.keys(servers)).toEqual(["board", "own"]);
+ });
+
it("tells Settings which stored servers have been seen to offer an app", () => {
const { mcp, servers } = setup({ probe: vi.fn(async () => ({ ok: false as const, error: "offline" })) });
servers.board = { ...board(), enabled: true };
diff --git a/server/chat-apps-mcp.ts b/server/chat-apps-mcp.ts
index 272d72e93b..a43b7a9490 100644
--- a/server/chat-apps-mcp.ts
+++ b/server/chat-apps-mcp.ts
@@ -44,6 +44,8 @@ export interface ChatAppsMcpDeps {
storedServers(): Record<string, unknown>;
mountedServers(bot: BotRecord): Record<string, McpServerSpec>;
personMcp?(): readonly string[];
+ /** How a command server is started outside a turn: as the turns of its bot, or of any bot (server/mcp-probe.ts `asBot`). */
+ probeAs?(server: { bot?: string }): NonNullable<McpProbeOptions["asBot"]>;
oauth: ChatAppsMcpOAuth;
dataDir?: string;
catalog?: McpAppCatalog;
@@ -117,7 +119,14 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {
const now = deps.now ?? Date.now;
const log = deps.log ?? ((line: string) => console.info(`chat apps: ${line}`));
const catalog = deps.catalog ?? new McpAppCatalog(deps.dataDir ? `${deps.dataDir}/mcp-app-catalog.json` : null);
+ // A command server OpenMausBot starts by itself (the background probe, an app's own connection) runs where the bots'
+ // turns run it: in the bot box where that is on, never beside the server.
+ const asBot = (name: string) => {
+ const stored = storedServer(name, deps.storedServers()[name]);
+ return deps.probeAs?.(stored && !isRemoteMcpServer(stored) ? stored : {}) ?? {};
+ };
const connections = deps.connections ?? new AppConnections({
+ asBot,
onTools: (name, server, tools, extensions) => {
if (storedServer(name, deps.storedServers()[name])?.apps === false) return;
catalog.recordList(name, server, tools, extensions);
@@ -396,7 +405,7 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {
const target = isRemoteMcpServer(stored) ? await signedIn(name, stored) : stored;
if (!target) return;
const probed = { ...target, enabled: true } as StoredMcpServer;
- const result = await probe(probed, BACKGROUND_PROBE_MS, undefined, probeOptions(name, stored));
+ const result = await probe(probed, BACKGROUND_PROBE_MS, undefined, { ...probeOptions(name, stored), ...(isRemoteMcpServer(probed) ? {} : { asBot: asBot(name) }) });
if (!result.ok && result.auth === "required" && isRemoteMcpServer(probed) && !sendsCredentials(probed)) deps.oauth.requireSignIn(name, probed.url);
log(`probed ${name}: ${result.ok ? `apps=${catalog.get(name, stored)?.apps === true}` : result.auth === "required" ? "needs sign-in" : "failed"}`);
}).catch((error: unknown) => log(`probe of ${name} failed: ${String(error)}`));
diff --git a/server/drivers/claude-keepwarm-box.test.ts b/server/drivers/claude-keepwarm-box.test.ts
new file mode 100644
index 0000000000..927787069d
--- /dev/null
+++ b/server/drivers/claude-keepwarm-box.test.ts
@@ -0,0 +1,254 @@
+// A keep-warm ping and a warm summary where the bot box is on (every Cloud home). Both relaunch Claude Code with the live
+// process's MCP config, the bot's own command servers included, and Claude Code starts every listed command as it
+// launches, before any tool call and whatever its hooks deny. So a fork runs in a box like the bot's turns: the command
+// starts inside it, where the data folder is an empty one. Off a Cloud the box is off and nothing changes.
+import { chmodSync, existsSync, 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 { detectBox } from "../bot-box/detect.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";
+import { forkSpawnOptions } from "./claude-keepwarm.ts";
+
+const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-claude-cli.ts");
+const KNOBS = ["FAKE_CLAUDE_DUMP", "FAKE_CLAUDE_PING_DUMP", "FAKE_CLAUDE_COMPACT_DUMP", "FAKE_CLAUDE_STARTS_MCP"] as const;
+const TMPDIR = process.env.TMPDIR;
+
+/** A stand-in for bubblewrap with no namespaces: it runs what follows `--`, and what it runs can tell it is inside. */
+const MARKING_BWRAP = `#!/bin/sh
+while [ "$1" != "--" ]; do shift; done
+shift
+IN_FAKE_BOX=inside; export IN_FAKE_BOX
+exec "$@"
+`;
+/** The bot's own command server: appends where it ran and what it could read of the file it is given to `$0`. */
+const SERVER_SCRIPT = 'printf "%s %s\\n" "${IN_FAKE_BOX:-outside}" "$(cat "$1" 2>/dev/null || echo UNREADABLE)" >> "$0"';
+const botServer = (marker: string, secret: string) => ({ command: "/bin/sh", args: ["-c", SERVER_SCRIPT, marker, secret], env: {} });
+/** The boxed forks so far: the pings (never written down), or the summaries (kept as sessions). */
+const boxedForks = (wrap: { mock: { results: Array<{ value: unknown }> } }, kind: "ping" | "summary") =>
+ wrap.mock.results.map((result) => result.value as WrappedSpawn | null)
+ .filter((spawned): spawned is WrappedSpawn => Boolean(spawned?.args.includes("--fork-session")) && spawned!.args.includes("--no-session-persistence") === (kind === "ping"));
+
+describe("a fork's spawn", () => {
+ it("asks for the bot box by name, with its private folder read-only in it", () => {
+ const options = forkSpawnOptions({ cwd: "/work/t1" }, { PATH: "/usr/bin" }, "/tmp/omb-keepwarm-x");
+ expect(options).toMatchObject({ cwd: "/work/t1", engineHome: true, botWork: true, box: { ro: ["/tmp/omb-keepwarm-x"] } });
+ });
+});
+
+describe("keep-warm forks 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")("start the bot's own command server inside the box, for a ping and for a summary", async () => {
+ ensureDirs();
+ chmodSync(FAKE_CLI, 0o755);
+ const scratch = mkdtempSync(join(tmpdir(), "omb-keepwarm-box-"));
+ dirs.push(scratch);
+ const fakeBwrap = join(scratch, "fake-bwrap.sh");
+ writeFileSync(fakeBwrap, MARKING_BWRAP);
+ 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" } }),
+ });
+ 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 marker = join(scratch, "started.txt"), pingDump = join(scratch, "ping.json"), compactDump = join(scratch, "compact.json");
+ process.env.FAKE_CLAUDE_PING_DUMP = pingDump;
+ process.env.FAKE_CLAUDE_COMPACT_DUMP = compactDump;
+ process.env.FAKE_CLAUDE_STARTS_MCP = "notes";
+ instance = await ClaudeDriver.create({ instanceId: "claude-keepwarm-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-warm-box");
+ mkdirSync(cwd, { recursive: true });
+
+ await instance.adapter.sendTurn({
+ threadId: "t-warm-box", botId: "bot-a", text: "hi", approvalMode: "full", cwd,
+ integrations: { custom: { notes: botServer(marker, join(DATA_DIR, "config.json")) }, customResultBudgets: { notes: 0 } },
+ });
+ await recorder.until((event) => event.type === "turn.completed", 30_000);
+ expect(existsSync(marker), "the fake CLI starts servers only on a fork").toBe(false);
+
+ expect(await instance.adapter.cacheKeepWarm!.ping("t-warm-box")).toMatchObject({ ok: true });
+ // The server is still declared, as in the bot's turns: the tool list is part of the cached prefix.
+ expect(JSON.parse(readFileSync(pingDump, "utf8")).mcpConfig.mcpServers.notes).toMatchObject({ command: "/bin/sh" });
+ expect(readFileSync(marker, "utf8").trim().split("\n").map((line) => line.split(" ")[0]), "the ping started the bot's server in the box").toEqual(["inside"]);
+
+ const ping = boxedForks(wrap, "ping");
+ expect(ping, "the ping went through the box").toHaveLength(1);
+ const plan = ping[0]!.plan;
+ expect(plan.botId).toBe("bot-a");
+ expect(plan.net).toBe("isolated");
+ for (const hidden of ["messages.db", "config.json", join("workspaces", "bot-b"), join("task-workspaces", "bot-b", "t-other")]) {
+ expect(visibleInBox(plan, join(DATA_DIR, hidden)), `${hidden} is not in the ping's box`).toBe("none");
+ }
+ expect(visibleInBox(plan, cwd)).toBe("rw");
+ // The fork's own files: the MCP config and settings on its command line, and the deny hook the settings name.
+ const args = ping[0]!.args, mcpConfig = args[args.indexOf("--mcp-config") + 1]!;
+ expect(visibleInBox(plan, mcpConfig)).toBe("ro");
+ expect(visibleInBox(plan, join(dirname(mcpConfig), "deny-tools.mjs")), "the deny hook can run in the box").toBe("ro");
+
+ expect(await instance.adapter.cacheKeepWarm!.compact!("t-warm-box", { instructions: "" })).toMatchObject({ ok: true });
+ expect(JSON.parse(readFileSync(compactDump, "utf8")).mcpConfig.mcpServers.notes).toMatchObject({ command: "/bin/sh" });
+ expect(readFileSync(marker, "utf8").trim().split("\n").map((line) => line.split(" ")[0]), "the summary started it in the box too").toEqual(["inside", "inside"]);
+ const summary = boxedForks(wrap, "summary");
+ expect(summary, "the summary went through the box").toHaveLength(1);
+ expect(visibleInBox(summary[0]!.plan, join(DATA_DIR, "config.json"))).toBe("none");
+ }, 90_000);
+
+ // A ping is worth its cost only when its request starts byte for byte as the conversation's next turn will, and Claude
+ // Code builds that start from what it is launched with: its working folder, environment, system prompt file, MCP
+ // servers (whose tools it lists), flags, and the files it can see. So a fork must be launched as the boxed turn was.
+ it.skipIf(process.platform === "win32")("launch a ping and a summary as the boxed turn was launched, so they read the turn's cached prefix", async () => {
+ ensureDirs();
+ chmodSync(FAKE_CLI, 0o755);
+ const scratch = mkdtempSync(join(tmpdir(), "omb-keepwarm-prefix-"));
+ dirs.push(scratch);
+ const fakeBwrap = join(scratch, "fake-bwrap.sh");
+ writeFileSync(fakeBwrap, MARKING_BWRAP);
+ 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" } }),
+ });
+ const wrap = vi.spyOn(botBox, "wrap");
+ delete process.env.TMPDIR;
+ const turnDump = join(scratch, "turn.json"), pingDump = join(scratch, "ping.json"), compactDump = join(scratch, "compact.json");
+ process.env.FAKE_CLAUDE_DUMP = turnDump;
+ process.env.FAKE_CLAUDE_PING_DUMP = pingDump;
+ process.env.FAKE_CLAUDE_COMPACT_DUMP = compactDump;
+ instance = await ClaudeDriver.create({ instanceId: "claude-keepwarm-prefix", 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-warm-prefix");
+ mkdirSync(cwd, { recursive: true });
+ await instance.adapter.sendTurn({
+ threadId: "t-warm-prefix", botId: "bot-a", text: "hi", approvalMode: "full", cwd, model: "claude-sonnet-5", system: "You are Editor.",
+ integrations: { custom: { notes: botServer(join(scratch, "started.txt"), join(scratch, "none")) }, customResultBudgets: { notes: 0 } },
+ });
+ await recorder.until((event) => event.type === "turn.completed", 30_000);
+ expect(await instance.adapter.cacheKeepWarm!.ping("t-warm-prefix")).toMatchObject({ ok: true });
+ expect(await instance.adapter.cacheKeepWarm!.compact!("t-warm-prefix", { instructions: "" })).toMatchObject({ ok: true });
+
+ const turn = JSON.parse(readFileSync(turnDump, "utf8"));
+ const turnSpawn = wrap.mock.results.map((result) => result.value as WrappedSpawn | null).find((spawned) => spawned?.args.includes("stream-json"));
+ expect(turnSpawn, "the turn went through the box").toBeTruthy();
+ // Each boxed process gets its own broker token in place of the key; the broker sends the same key upstream.
+ const sameUpstream = (env: Record<string, string>) => Object.fromEntries(Object.entries(env).map(([name, value]) => [name, value.replace(/omb_t0_[a-f0-9]{48}/g, "<broker token>")]));
+ // The deny hook's folder and the dead permission socket are the fork's own; neither is in the request.
+ const servers = (config: { mcpServers: Record<string, { args?: string[] }> }) => Object.fromEntries(Object.entries(config.mcpServers)
+ .map(([name, server]) => [name, name === "ogb" ? { ...server, args: server.args?.slice(0, -1) } : server]));
+ const PREFIX_FLAGS = ["--model", "--permission-mode", "--strict-mcp-config", "--setting-sources", "--system-prompt-snapshot", "--allowedTools", "--disallowedTools", "--effort", "--permission-prompt-tool"];
+ const flags = (argv: string[]) => PREFIX_FLAGS.map((flag) => [flag, argv.includes(flag) ? argv[argv.indexOf(flag) + 1] : null]);
+ // What the box shows, but for each process's own private files: the turn's MCP config, prompt and permission socket,
+ // the fork's folder.
+ const PRIVATE = /\/(omb-(mcp|system|keepwarm|hook)-[^/]+|perm-[^/]+\.sock)(\/|$)/;
+ const view = (spawned: WrappedSpawn) => ({
+ mounts: spawned.plan.mounts.filter((mount) => !("source" in mount && PRIVATE.test(mount.source))),
+ net: spawned.plan.net, botId: spawned.plan.botId, options: spawned.plan.options,
+ });
+ for (const [what, dumpPath] of [["ping", pingDump], ["summary", compactDump]] as const) {
+ const fork = JSON.parse(readFileSync(dumpPath, "utf8"));
+ expect(fork.cwd, what).toBe(turn.cwd);
+ expect(sameUpstream(fork.env), `the ${what}'s environment`).toEqual(sameUpstream(turn.env));
+ expect(fork.systemPrompt, what).toBe(turn.systemPromptFile);
+ expect(servers(fork.mcpConfig), `the ${what}'s MCP servers`).toEqual(servers(turn.mcpConfig));
+ expect(flags(fork.argv), what).toEqual(flags(turn.argv));
+ const forkSpawn = boxedForks(wrap, what)[0];
+ expect(forkSpawn, `the ${what} went through the box`).toBeTruthy();
+ expect(view(forkSpawn!), `what the ${what} can see`).toEqual(view(turnSpawn!));
+ }
+ }, 90_000);
+
+ it.skipIf(process.platform === "win32")("with the box off, a fork runs as it did", async () => {
+ ensureDirs();
+ chmodSync(FAKE_CLI, 0o755);
+ const scratch = mkdtempSync(join(tmpdir(), "omb-keepwarm-nobox-"));
+ dirs.push(scratch);
+ const wrap = vi.spyOn(botBox, "wrap");
+ const marker = join(scratch, "started.txt");
+ process.env.FAKE_CLAUDE_STARTS_MCP = "notes";
+ instance = await ClaudeDriver.create({ instanceId: "claude-keepwarm-nobox", displayName: "Claude", environment: {}, enabled: true, config: { cli: FAKE_CLI, permissionMode: "acceptEdits" } });
+ const recorder = recordEvents(instance.adapter);
+ await instance.adapter.sendTurn({
+ threadId: "t-warm-nobox", botId: "bot-a", text: "hi", approvalMode: "full",
+ integrations: { custom: { notes: botServer(marker, join(scratch, "none")) }, customResultBudgets: { notes: 0 } },
+ });
+ await recorder.until((event) => event.type === "turn.completed", 30_000);
+ expect(await instance.adapter.cacheKeepWarm!.ping("t-warm-nobox")).toMatchObject({ ok: true });
+ expect(readFileSync(marker, "utf8").trim()).toBe("outside UNREADABLE");
+ expect(wrap.mock.results.every((result) => result.value === null)).toBe(true);
+ }, 60_000);
+});
+
+// The same in a real box, where one can run: Linux with an unprivileged bubblewrap (a Cloud home, the Fly test machine).
+const detection = detectBox({ env: { ...process.env, OMB_BOT_BOX: "1" } });
+const available = detection.box === "bwrap" && detection.tools !== null;
+
+describe.skipIf(!available)(`keep-warm forks in a real box (${available ? "bubblewrap works here" : `skipped: ${detection.reason}`})`, () => {
+ let instance: ProviderInstance | null = null;
+ afterEach(async () => {
+ await instance?.dispose();
+ instance = null;
+ await botBox.stop();
+ for (const name of KNOBS) delete process.env[name];
+ if (TMPDIR === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = TMPDIR;
+ });
+
+ it("the bot's command server a ping or a summary starts cannot read the data folder", async () => {
+ ensureDirs();
+ chmodSync(FAKE_CLI, 0o755);
+ writeFileSync(join(DATA_DIR, "config.json"), "the-server-secret-is-sardine");
+ const other = join(DATA_DIR, "workspaces", "bot-b");
+ mkdirSync(other, { recursive: true });
+ writeFileSync(join(other, "notes.md"), "another-bot-keeps-herring");
+ await botBox.start({ dataDir: DATA_DIR, home: homedir(), port: 18799, denyEnv: new Set(), env: { ...process.env, OMB_BOT_BOX: "1" }, log: () => {} });
+ expect(botBox.enabled()).toBe(true);
+ delete process.env.TMPDIR;
+ const cwd = join(DATA_DIR, "task-workspaces", "bot-a", "t-warm-real");
+ mkdirSync(cwd, { recursive: true });
+ mkdirSync(join(DATA_DIR, "workspaces", "bot-a"), { recursive: true });
+ // The conversation's folder is the one place both the box and the test can reach.
+ const marker = join(cwd, "started.txt"), marker2 = join(cwd, "started-b.txt");
+ process.env.FAKE_CLAUDE_STARTS_MCP = "notes,herring";
+ instance = await ClaudeDriver.create({ instanceId: "claude-keepwarm-real", displayName: "Claude", environment: {}, enabled: true, config: { cli: FAKE_CLI, permissionMode: "acceptEdits" } });
+ const recorder = recordEvents(instance.adapter);
+
+ await instance.adapter.sendTurn({
+ threadId: "t-warm-real", botId: "bot-a", text: "hi", approvalMode: "full", cwd,
+ integrations: {
+ custom: { notes: botServer(marker, join(DATA_DIR, "config.json")), herring: botServer(marker2, join(other, "notes.md")) },
+ customResultBudgets: { notes: 0, herring: 0 },
+ },
+ });
+ await recorder.until((event) => event.type === "turn.completed", 30_000);
+
+ expect(await instance.adapter.cacheKeepWarm!.ping("t-warm-real")).toMatchObject({ ok: true });
+ expect(await instance.adapter.cacheKeepWarm!.compact!("t-warm-real", { instructions: "" })).toMatchObject({ ok: true });
+ const started = readFileSync(marker, "utf8"), startedB = readFileSync(marker2, "utf8");
+ expect(started.trim().split("\n"), "started by the ping and by the summary").toHaveLength(2);
+ expect(started).not.toContain("sardine");
+ expect(started).toContain("UNREADABLE");
+ expect(startedB).not.toContain("herring");
+ expect(startedB).toContain("UNREADABLE");
+ }, 120_000);
+});
diff --git a/server/drivers/claude-keepwarm.ts b/server/drivers/claude-keepwarm.ts
index 956464c1e3..47ebf2f91c 100644
--- a/server/drivers/claude-keepwarm.ts
+++ b/server/drivers/claude-keepwarm.ts
@@ -10,12 +10,16 @@
// with the live process's exact launch contract plus `--resume <session> --fork-session` and
// `--no-session-persistence` (the copy is never written). Tools stay declared but none can run: a
// PreToolUse hook denies every call and the permission proxy points at a dead socket.
+//
+// The CLI starts every command server in its MCP config as it launches, before any tool call, and the bot's own servers
+// are in that config (the tool list is part of the prefix). So a fork runs where the bot's turns run: in the bot box
+// where that is on, with the same plan a turn gets (forkSpawnOptions).
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { CacheWarmPingResult } from "../contracts.ts";
-import { killCliTree, spawnCli } from "../procs.ts";
+import { killCliTree, spawnCli, type CliSpawnOptions } from "../procs.ts";
import { USAGE_LIMIT } from "./retry.ts";
export const KEEP_WARM_PROMPT = "Reply with the single word: warm";
@@ -109,6 +113,14 @@ export function parseKeepWarmResult(stdout: string, stderr: string, code: number
};
}
+/** How a fork is started: in the conversation's engine home and, where turns are boxed, in a box like its turns'
+ * (spawnCli boxes a spawn that names `box`; with the box off the spawn is unchanged). The box is asked for by name, never
+ * by owner: a fork is not the bot's engine, so nothing tracks it as one. `dir` holds the fork's private files; the deny
+ * hook in it is named only inside the settings file, so the folder is put in the box, read-only. */
+export function forkSpawnOptions(contract: Pick<KeepWarmContract, "cwd">, env: NodeJS.ProcessEnv, dir: string): CliSpawnOptions {
+ return { cwd: contract.cwd, env, stdio: ["pipe", "pipe", "pipe"], engineHome: true, botWork: true, box: { ro: [dir] } };
+}
+
/** Never throws. The credentialed MCP config, settings and prompt live in a 0700 temp dir removed at exit. */
export function runKeepWarmPing(opts: {
cli: string;
@@ -122,8 +134,8 @@ export function runKeepWarmPing(opts: {
}
/** One prompt on a fork of a live session, with that session's exact launch contract so its cached prompt start is read
- * again; no tool can run in it. Never throws. The credentialed MCP config, settings and prompt live in a 0700 temp dir
- * removed at exit. */
+ * again; no tool can run in it, and the servers it starts run where a turn's do. Never throws. The credentialed MCP
+ * config, settings and prompt live in a 0700 temp dir removed at exit. */
export function runForkedPrompt<T>(opts: {
cli: string;
contract: KeepWarmContract;
@@ -174,7 +186,7 @@ export function runForkedPrompt<T>(opts: {
return new Promise((resolve) => {
let child: ReturnType<typeof spawnCli>;
try {
- child = spawnCli(opts.cli, args, { cwd: contract.cwd, env, stdio: ["pipe", "pipe", "pipe"], engineHome: true, botWork: true });
+ child = spawnCli(opts.cli, args, forkSpawnOptions(contract, env, dir));
} catch (error) {
cleanup();
resolve(opts.failed(`the ${what} could not start: ${(error as Error).message}`));
diff --git a/server/engine-homes/engine-homes.test.ts b/server/engine-homes/engine-homes.test.ts
index 9a97152f51..42c04fb72d 100644
--- a/server/engine-homes/engine-homes.test.ts
+++ b/server/engine-homes/engine-homes.test.ts
@@ -60,17 +60,22 @@ describe("engine homes at run time", () => {
expect(existsSync(join(dataDir, "engine-homes", ".migrated"))).toBe(true);
});
- it("wrap every turn and keep-warm ping in its conversation", async () => {
+ it("wrap every turn, keep-warm ping and warm summary in its conversation", async () => {
const homes = new EngineHomes();
homes.start(setup());
const seen: Array<string | null> = [];
const instance = withEngineHomes({ adapter: {
sendTurn: async () => { await new Promise((resolve) => setTimeout(resolve, 1)); seen.push(homes.scope()); return { turnId: "x" }; },
- cacheKeepWarm: { ping: async () => { seen.push(homes.scope()); return { ok: false, reason: "test" }; }, hold: () => false },
+ cacheKeepWarm: {
+ ping: async () => { seen.push(homes.scope()); return { ok: false, reason: "test" }; }, hold: () => false,
+ compact: async () => { seen.push(homes.scope()); return { ok: false, reason: "test" }; },
+ },
} } as unknown as ProviderInstance, homes);
await instance.adapter.sendTurn({ threadId: "t-bob", text: "hi" });
await instance.adapter.cacheKeepWarm!.ping("t-main");
- expect(seen).toEqual([expect.stringMatching(/^member-[0-9a-f]{16}$/), "team"]);
+ await instance.adapter.cacheKeepWarm!.compact!("t-owner", { instructions: "" });
+ expect(seen).toEqual([expect.stringMatching(/^member-[0-9a-f]{16}$/), "team", expect.stringMatching(/^member-[0-9a-f]{16}$/)]);
+ expect(seen[2]).not.toBe(seen[0]);
});
});
diff --git a/server/engine-homes/engine-homes.ts b/server/engine-homes/engine-homes.ts
index f6a910bcd9..cce7f3a2d1 100644
--- a/server/engine-homes/engine-homes.ts
+++ b/server/engine-homes/engine-homes.ts
@@ -95,7 +95,7 @@ export class EngineHomes {
export const engineHomes = new EngineHomes();
-/** On a Team Cloud, every turn and keep-warm ping of this instance runs inside its conversation. */
+/** On a Team Cloud, every turn, keep-warm ping and warm summary of this instance runs inside its conversation. */
export function withEngineHomes(instance: ProviderInstance, homes: EngineHomes = engineHomes): ProviderInstance {
if (!homes.active()) return instance;
const adapter = instance.adapter;
@@ -103,7 +103,12 @@ export function withEngineHomes(instance: ProviderInstance, homes: EngineHomes =
(instance as { adapter: ProviderInstance["adapter"] }).adapter = {
...adapter,
sendTurn: (input) => homes.within(input.threadId, () => adapter.sendTurn(input)),
- ...(warm ? { cacheKeepWarm: { ...warm, ping: (threadId, options) => homes.within(threadId, () => warm.ping(threadId, options)) } } : {}),
+ ...(warm ? { cacheKeepWarm: {
+ ...warm,
+ ping: (threadId, options) => homes.within(threadId, () => warm.ping(threadId, options)),
+ // A summary forks the conversation's session, which lives in its audience's home, and starts the bot's servers there.
+ ...(warm.compact ? { compact: (threadId, options) => homes.within(threadId, () => warm.compact!(threadId, options)) } : {}),
+ } } : {}),
};
return instance;
}
diff --git a/server/index.ts b/server/index.ts
index c1f482d8d5..c6c5ccb198 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12109,7 +12109,7 @@ ROUTES.push(createBotMessageRoutes({
{ emoji, name: person.name ?? person.email, at: Date.now() }),
}));
const liveRoots = (threadId: string, botId: string | undefined) => { const bot = botId ? store.bot(botId) : store.botByThread(threadId); return bot ? messageFileRootsForThread(bot.id, threadId).filter((root) => root !== ATTACHMENTS_DIR) : null; }; const chatApps = createChatApps({ store, dataDir: DATA_DIR, liveRows: liveAppRows, liveRoots, paused: () => workspaceMaintenance.active || moveFreeze.frozen() });
-const chatAppsMcp = createChatAppsMcp({ store, apps: chatApps, dataDir: DATA_DIR, storedServers: () => cfg.mcpServers ?? {}, mountedServers: engineMcpServers, personMcp: teamConnections.personMcp, oauth: mcpOAuth });
+const chatAppsMcp = createChatAppsMcp({ store, apps: chatApps, dataDir: DATA_DIR, storedServers: () => cfg.mcpServers ?? {}, mountedServers: engineMcpServers, personMcp: teamConnections.personMcp, probeAs: (server) => mcpServersHost.probeAs(server), oauth: mcpOAuth });
ROUTES.push(createChatAppRoutes({ store, apps: chatApps, threadRefusal: cloudThreadRefusal, mcpRpc: chatAppsMcp.rpc, threadVisible: (auth, threadId) => (auth.kind !== "session" || sessions.isLive(auth.session.id)) && visibleTo(viewerFor(auth)).thread(threadId) }));
const { react } = createReactions({
store, reply: (input) => teamMessages.reactedIn(input.auth, input.threadId, input.target.id, input.answer, { sendId: input.sendId, sender: messageSender(input.auth) }) ?? personReplies.deliver({ ...input, about: "message" }),
diff --git a/server/mcp-app-connections-box.test.ts b/server/mcp-app-connections-box.test.ts
new file mode 100644
index 0000000000..a6e0bbe632
--- /dev/null
+++ b/server/mcp-app-connections-box.test.ts
@@ -0,0 +1,84 @@
+// OpenMausBot's own connection to a command MCP server (an app's page and calls) where the bot box is on: the command is
+// one a bot's turns also start, and may be the bot's own, so it starts in the box, where the data folder is an empty one.
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { homedir, tmpdir } from "node:os";
+import { join } from "node:path";
+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 { AppConnections } from "./mcp-app-connections.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+
+/** A stand-in for bubblewrap with no namespaces: it runs what follows `--`, and what it runs can tell it is inside. */
+const MARKING_BWRAP = `#!/bin/sh
+while [ "$1" != "--" ]; do shift; done
+shift
+IN_FAKE_BOX=inside; export IN_FAKE_BOX
+exec "$@"
+`;
+/** Says where it started, then answers nothing: the connection gives up on it. */
+const server = (marker: string) => ({ command: "/bin/sh", args: ["-c", 'printf "%s\\n" "${IN_FAKE_BOX:-outside}" >> "$0"', marker], env: { BOARD_KEY: "k" } });
+const TMPDIR = process.env.TMPDIR;
+
+describe.skipIf(process.platform === "win32")("an app's connection to a command server", () => {
+ const dirs: string[] = [];
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await botBox.stop();
+ if (TMPDIR === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = TMPDIR;
+ for (const dir of dirs.splice(0)) await removeTempDir(dir);
+ });
+
+ it("starts the command in the bot box where turns are boxed: as its bot, or with no bot's folder", async () => {
+ ensureDirs();
+ const scratch = mkdtempSync(join(tmpdir(), "omb-app-box-"));
+ dirs.push(scratch);
+ const fakeBwrap = join(scratch, "fake-bwrap.sh");
+ writeFileSync(fakeBwrap, MARKING_BWRAP);
+ 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" } }),
+ });
+ const wrap = vi.spyOn(botBox, "wrap");
+ delete process.env.TMPDIR;
+ const marker = join(scratch, "started.txt");
+ const own = join(DATA_DIR, "workspaces", "bot-a");
+ mkdirSync(own, { recursive: true });
+ const connections = new AppConnections({ asBot: (name) => (name === "own" ? { id: "bot-a", cwd: own } : {}) });
+ try {
+ await expect(connections.request("own", server(marker), "resources/list", {}, AbortSignal.timeout(20_000))).rejects.toThrow();
+ await expect(connections.request("shared", server(`${marker}.shared`), "resources/list", {}, AbortSignal.timeout(20_000))).rejects.toThrow();
+ } finally {
+ connections.closeAll();
+ }
+ expect(readFileSync(marker, "utf8").trim()).toBe("inside");
+ expect(readFileSync(`${marker}.shared`, "utf8").trim()).toBe("inside");
+ const [asBot, asAny] = wrap.mock.results.map((result) => result.value as WrappedSpawn);
+ expect(asBot!.plan.botId).toBe("bot-a");
+ expect(visibleInBox(asBot!.plan, own)).toBe("rw");
+ expect(asAny!.plan.botId).toBeNull();
+ for (const plan of [asBot!.plan, asAny!.plan]) {
+ expect(plan.net).toBe("isolated");
+ for (const hidden of ["messages.db", "config.json", join("workspaces", "bot-b")]) expect(visibleInBox(plan, join(DATA_DIR, hidden)), hidden).toBe("none");
+ }
+ expect(visibleInBox(asAny!.plan, own), "no bot's folder for a server that is every bot's").toBe("none");
+ // The keys the person saved for the server are its own to read.
+ expect(asBot!.env.BOARD_KEY).toBe("k");
+ }, 60_000);
+
+ it("with the box off, starts it as it did", async () => {
+ const scratch = mkdtempSync(join(tmpdir(), "omb-app-nobox-"));
+ dirs.push(scratch);
+ const marker = join(scratch, "started.txt");
+ const connections = new AppConnections({ asBot: () => ({ id: "bot-a", cwd: join(scratch, "missing") }) });
+ try {
+ await expect(connections.request("own", server(marker), "resources/list", {}, AbortSignal.timeout(20_000))).rejects.toThrow();
+ } finally {
+ connections.closeAll();
+ }
+ expect(readFileSync(marker, "utf8").trim()).toBe("outside");
+ }, 60_000);
+});
diff --git a/server/mcp-app-connections.ts b/server/mcp-app-connections.ts
index 403b46942d..cecf75bf71 100644
--- a/server/mcp-app-connections.ts
+++ b/server/mcp-app-connections.ts
@@ -1,13 +1,15 @@
// OMB's own connections to MCP app servers: they read an app's UI resource and run its view's calls long
-// after the turn that called the tool has ended. A command server is spawned with the probe environment.
+// after the turn that called the tool has ended. A command server is spawned with the probe environment, and where the
+// bots' turns are boxed it is started as they start it: in the bot box (as server/mcp-probe.ts does for Test).
import { createHash } from "node:crypto";
import { APP_EXTENSION_KEY } from "../shared/app.ts";
import type { McpServerSpec, RemoteMcpSpec, StdioMcpSpec } from "./contracts.ts";
+import { botBox } from "./bot-box/box.ts";
import { createLineSplitter } from "./mcp-bridge.ts";
import { UI_EXTENSION, withUiExtension } from "./mcp-app-observer.ts";
import { MAX_REMOTE_MCP_BYTES, McpHttpError, McpRpcError, REMOTE_MCP_STARTUP_MS, RemoteMcpClient } from "./mcp-http.ts";
-import { probeEnvironment } from "./mcp-probe.ts";
+import { probeEnvironment, type McpProbeOptions } from "./mcp-probe.ts";
import { killCliTree, spawnCli } from "./procs.ts";
export const APP_CONNECTION_IDLE_MS = 5 * 60_000;
@@ -28,6 +30,9 @@ export interface AppClient {
readonly closed: boolean;
}
+/** Whose turns a command server is started like: its bot's (own folder in the box), or any bot's (no bot's folder). */
+export type AppServerAs = NonNullable<McpProbeOptions["asBot"]>;
+
export interface AppClientHooks {
onNotification(method: string): void;
}
@@ -41,8 +46,13 @@ class StdioAppClient implements AppClient {
extensions: "ok" | "refused" | undefined;
serverInfo: Json | undefined;
- constructor(server: StdioMcpSpec, hooks: AppClientHooks) {
- this.child = spawnCli(server.command, server.args, { cwd: process.cwd(), env: probeEnvironment(server), stdio: ["pipe", "pipe", "pipe"] });
+ constructor(server: StdioMcpSpec, hooks: AppClientHooks, as: AppServerAs = {}) {
+ // With the box off `box` changes nothing, and the server starts where it always did.
+ this.child = spawnCli(server.command, server.args, {
+ ...(botBox.enabled() ? (as.cwd ? { cwd: as.cwd } : {}) : { cwd: process.cwd() }),
+ env: probeEnvironment(server), stdio: ["pipe", "pipe", "pipe"],
+ box: { ...(as.id ? { botId: as.id } : {}), allowEnv: Object.keys(server.env) },
+ });
const splitter = createLineSplitter((line) => this.onLine(line, hooks));
this.child.stdout.on("data", (chunk: Buffer) => {
// A connection lives for minutes; the bound is per message, not total.
@@ -163,8 +173,8 @@ class RemoteAppClient implements AppClient {
}
}
-export async function openAppClient(server: McpServerSpec, hooks: AppClientHooks, extension: boolean, signal: AbortSignal): Promise<AppClient> {
- const client = "url" in server ? new RemoteAppClient(server, hooks) : new StdioAppClient(server, hooks);
+export async function openAppClient(server: McpServerSpec, hooks: AppClientHooks, extension: boolean, signal: AbortSignal, as: AppServerAs = {}): Promise<AppClient> {
+ const client = "url" in server ? new RemoteAppClient(server, hooks) : new StdioAppClient(server, hooks, as);
try {
await client.initialize(signal, extension);
return client;
@@ -190,6 +200,8 @@ export interface AppConnectionsOptions {
now?: () => number;
open?: typeof openAppClient;
onTools?(name: string, server: McpServerSpec, tools: Json[], extensions: "ok" | "refused" | undefined): void;
+ /** Whose turns the named command server is started like; absent: any bot's. */
+ asBot?(name: string): AppServerAs;
}
function connectionLost(error: unknown): boolean {
@@ -203,6 +215,7 @@ export class AppConnections {
private readonly now: () => number;
private readonly open: typeof openAppClient;
private readonly onTools: AppConnectionsOptions["onTools"];
+ private readonly asBot: AppConnectionsOptions["asBot"];
constructor(options: AppConnectionsOptions = {}) {
this.idleMs = options.idleMs ?? APP_CONNECTION_IDLE_MS;
@@ -210,6 +223,7 @@ export class AppConnections {
this.now = options.now ?? Date.now;
this.open = options.open ?? openAppClient;
this.onTools = options.onTools;
+ this.asBot = options.asBot;
}
get size(): number { return this.slots.size; }
@@ -234,7 +248,7 @@ export class AppConnections {
if (current) delete current.tools;
}
},
- }, extension, AbortSignal.timeout(REMOTE_MCP_STARTUP_MS));
+ }, extension, AbortSignal.timeout(REMOTE_MCP_STARTUP_MS), this.asBot?.(name) ?? {});
const created: Slot = { name, server, client: opening, used: this.now() };
slot = created;
this.slots.set(key, created);
diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.ts
index 5ef9e25dcf..0c69a31933 100755
--- a/server/testing/fake-claude-cli.ts
+++ b/server/testing/fake-claude-cli.ts
@@ -25,6 +25,8 @@
// FAKE_CLAUDE_CACHE_READ_TOKENS cache_read_input_tokens per model call (default 2)
// FAKE_CLAUDE_PING_DUMP path for a keep-warm ping's {argv, env, prompt, mcpConfig, settings, systemPrompt}
// FAKE_CLAUDE_PING_USAGE JSON usage for a keep-warm ping's result (default: warm read 150000, write 40)
+// FAKE_CLAUDE_STARTS_MCP comma list of --mcp-config command servers a fork (`--fork-session`) starts as it launches,
+// before it answers and whatever its hooks say, as Claude Code 2.1.321 starts every listed one; each runs to its exit
// FAKE_CLAUDE_PING_RESULT raw json result for a keep-warm ping
// FAKE_CLAUDE_TEXT_DUMP FAKE_CLAUDE_DUMP for one-shot text runs
// FAKE_CLAUDE_TEXT_LOG JSON-lines file every one-shot prompt is appended to
@@ -56,7 +58,7 @@
// FAKE_CLAUDE_AUTOCOMPACT_AT tokens: a turn that starts at or above it compacts first, as Claude Code does at its threshold
// (PreCompact, FAKE_CLAUDE_COMPACT_MS of nothing, compact_boundary, then SessionStart "compact")
// FAKE_CLAUDE_COMPACT_MS how long a compaction takes: that one, or a one-shot `/compact` on a fork
-// FAKE_CLAUDE_COMPACT_DUMP path: a one-shot `/compact` on a fork (`--resume S --fork-session`) writes its {argv, prompt,
+// FAKE_CLAUDE_COMPACT_DUMP path: a one-shot `/compact` on a fork (`--resume S --fork-session`) writes its {argv, env, prompt,
// systemPrompt, mcpConfig, settings} here and answers with a new session; FAKE_CLAUDE_COMPACT_RESULT is its raw answer
// FAKE_CLAUDE_CONTEXT_TOKENS latest-prompt size reported in a scripted room-plan reply
// FAKE_CLAUDE_AUTH in (default) | out | unsupported | malformed | inherited-api-key: what `auth status` says
@@ -104,6 +106,17 @@ const streamCadence = (() => {
return Number.isSafeInteger(parsed.chars) && parsed.chars > 0 && Number.isSafeInteger(parsed.ms) && parsed.ms >= 0 ? parsed : null;
})();
+function startListedMcpServers(): void {
+ const names = (process.env.FAKE_CLAUDE_STARTS_MCP ?? "").split(",").filter(Boolean);
+ if (!names.length) return;
+ let servers: Record<string, { command?: string; args?: string[]; env?: Record<string, string> }> = {};
+ try { servers = JSON.parse(readFileSync(argAfter("--mcp-config") ?? "", "utf8")).mcpServers ?? {}; } catch {}
+ for (const name of names) {
+ const server = servers[name];
+ if (server?.command) spawnSync(server.command, server.args ?? [], { env: { ...process.env, ...server.env }, input: "", timeout: 10_000 });
+ }
+}
+
// Concurrent turns share a capture path: publish whole JSON in one rename.
const writeDumpAtomic = (path: string, contents: string): void => {
const tmp = `${path}.${process.pid}.tmp`;
@@ -400,6 +413,7 @@ if (["text", "json"].includes(argAfter("--output-format") ?? "")) {
process.stdin.on("data", (chunk) => { input += chunk; });
process.stdin.on("end", () => resolve(input));
});
+ if (argv.includes("--fork-session")) startListedMcpServers();
if (argv.includes("--fork-session") && prompt.trimStart().startsWith("/compact")) {
const file = (flag: string) => {
const path = argAfter(flag);
@@ -408,7 +422,7 @@ if (["text", "json"].includes(argAfter("--output-format") ?? "")) {
};
if (process.env.FAKE_CLAUDE_COMPACT_DUMP) {
writeDumpAtomic(process.env.FAKE_CLAUDE_COMPACT_DUMP, JSON.stringify({
- pid: process.pid, argv, prompt, cwd: process.cwd(), mcpConfig: JSON.parse(file("--mcp-config") ?? "null"),
+ pid: process.pid, argv, env: process.env, prompt, cwd: process.cwd(), mcpConfig: JSON.parse(file("--mcp-config") ?? "null"),
settings: JSON.parse(file("--settings") ?? "null"), systemPrompt: file("--append-system-prompt-file"),
hookEnv: Object.keys(process.env).filter((key) => key.startsWith("OMB_HOOK_")),
}, null, 2));