Skip to content

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

fix(bot-box): serve the VPS computer's proxy from the host so boxed engines can reach it (#6956)

CI fixture197d6e589560
diff --git a/server/index.ts b/server/index.ts
index 2d5930c9d1..9abe0ffdf7 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -489,6 +489,7 @@ import type { WebhookTrigger } from "../shared/webhooks.ts";
import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts";
import { agentsProxyLaunch, agentsToolBridgeEnv, applyAgentsBridge, bridgedToolTitle, turnEngine } from "./agents-bridge-switch.ts"; import { serverTurnedOff } from "./drivers/agents-tool-groups.ts"; import { availableToolGroups, toolsOffPart } from "./tool-groups.ts"; import { agentsServerEnv, botDrivenConversation, COMPUTER_OFF_REFUSAL, computerPickRefusal, directTurnKind, handRoomSkills, roomSkillsRefusal, roomSkillsTurn, takeRoomSkills, type RoomSkillsClaim, type TurnKind } from "./agents-turn.ts";
import { harnessMcpTokenEnv } from "./harness-mcp-token.ts";
+import { vpsComputerTools, vpsComputerTurn } from "./vps-computer-rpc.ts";
import { loadBundledSkills, loadUserSkills, mergeSkills, renderSkillInstructions, selectBundledSkills, skillsLibraryEnabled, readSkillLibraryIndex } from "./skill-library.ts";
import { runSkillsLibraryBootSweep } from "./skills-library-migration.ts";
import { installedPlaybookInstructions } from "./installed-playbooks.ts";
@@ -5628,12 +5629,12 @@ function botComputerControlKey(bot: BotRecord): string {
return computer ? teamComputerOwner(computer.id) : bot.id;
}
-/** Waits here up to COMPUTER_CALL_WAIT_MS; a call that waited through a person's hold, or whose turn ended, is never performed. */
-async function computerCallGate(internalCapability: InternalCapability, signal?: AbortSignal, call?: ReturnType<typeof yourComputerCallFrom>): Promise<ControlState> {
+/** Waits here up to COMPUTER_CALL_WAIT_MS; a call that waited through a person's hold, or whose turn ended, is never performed. `since`, a `takeSequence`, is where a call that waited its turn counts takes from. */
+async function computerCallGate(internalCapability: InternalCapability, signal?: AbortSignal, call?: ReturnType<typeof yourComputerCallFrom>, since?: number): Promise<ControlState> {
const { botId, threadId, generation } = internalCapability;
const askedAt = Date.now();
const deadline = askedAt + COMPUTER_CALL_WAIT_MS;
- let personHeld = false; const owner = { threadId, generation }, person = { held: () => sharedVm.snapshot(botId, threadId).held, lastTake: () => sharedVm.lastTake(botId, threadId) }, tookFrom = sharedVm.takeSequence();
+ let personHeld = false; const owner = { threadId, generation }, person = { held: () => sharedVm.snapshot(botId, threadId).held, lastTake: () => sharedVm.lastTake(botId, threadId) }, tookFrom = since ?? sharedVm.takeSequence();
for (;;) {
const snapshot = sharedVm.snapshot(botId, threadId);
const helpOpen = snapshot.helpReason !== null;
@@ -5812,12 +5813,10 @@ async function mountBotVps(
opts.onClaimed(vpsCapture);
},
});
- return {
- integration: {
- ...vpsMcp,
- env: { ...vpsMcp.env, OMB_CONTROL_URL: vpsControl.url, OMB_CONTROL_TOKEN: vpsControl.token },
- },
- };
+ // A boxed engine cannot dial the VPS itself (no routes, public-only egress), so its proxy runs here and the engine
+ // reaches it through the harness gate, as the cloud computer's tools are served.
+ if (botBox.enabled()) return { integration: vpsComputerTools(bot.id, vpsControl, `http://127.0.0.1:${PORT}`, { sshAlias: remote.sshAlias, container: remote.container_id ?? vps.vpsContainerName(bot.id) }) };
+ return { integration: { ...vpsMcp, env: { ...vpsMcp.env, OMB_CONTROL_URL: vpsControl.url, OMB_CONTROL_TOKEN: vpsControl.token } } };
}
function mountBotBoat(
@@ -12932,9 +12931,10 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
// The turn's capability names its Boat; the Boat credential stays here.
if (await dispatchRoutes([savedSteps.journalRoutes({ capability: internalCapability, readBody: readInternalBody }), createAppFindRoute({ host: appSuggestions, botId: internalSender.id, readBody: readInternalBody, bot: (botId) => { const bot = connectorThread(botId, internalCapability.threadId)?.bot; return bot && bot.composio !== false && composio.configured(cfg) ? bot : null; }, refusal: (slug) => managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) ?? managedPolicy.appRefusal(slug) ?? teamConnections.connectRefusal(internalCapability, [slug]) })], { req, res, url, path, method, auth, json, readBody })) return; if (method === "POST" && path === "/api/internal/computer/mcp") {
const body = await readInternalBody();
- if (internalCapability.boxId === undefined) return json(res, 403, { error: "this turn has no cloud computer" });
const abort = new AbortController();
res.once("close", () => { if (!res.writableEnded) abort.abort(); });
+ // A boxed turn's VPS computer is served from the host's own proxy (vps-computer-rpc.ts); no Boat is named.
+ if (internalCapability.boxId === undefined) return vpsComputerTurn({ body, res, json, botId: internalCapability.botId, assertActive: requireActiveInternalCapability, takeSequence: () => sharedVm.takeSequence(), gate: (since) => computerCallGate(internalCapability, abort.signal, undefined, since), signal: abort.signal });
return json(res, 200, { result: await cloudComputerRpc(body, {
cfg, signal: abort.signal, folder: () => messageFileRootsForThread(internalCapability.botId, internalCapability.threadId)[0],
boxId: () => internalCapability.boxId ?? claimedBoatId(internalCapability),
diff --git a/server/vps-computer-rpc.test.ts b/server/vps-computer-rpc.test.ts
new file mode 100644
index 0000000000..f76b7f73f9
--- /dev/null
+++ b/server/vps-computer-rpc.test.ts
@@ -0,0 +1,260 @@
+// The boxed VPS computer's host-side stand-in: the mount a boxed engine starts, and what the engine's harness proxy
+// reaches through it, against a stand-in MCP server in the child seat.
+import { spawn, type ChildProcess } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { controlRefusal } from "./control-client.ts";
+import { harnessMcpTokenEnv } from "./harness-mcp-token.ts";
+import { SPAWNED_PROXIES } from "./proxy-paths.ts";
+import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { forgetVpsComputers, vpsComputerTools, vpsComputerTurn } from "./vps-computer-rpc.ts";
+
+const BOT = "bot-vps-test";
+const TOKEN = "turn-capability-token";
+const HARNESS = "http://127.0.0.1:8799";
+const HELD = "the person is holding the desktop right now";
+const HANDED_BACK = "the person took the desktop while this call waited";
+
+/** A stand-in for the Cua MCP server: MCP over stdio, one answer per line. `tag` marks which child answered;
+ * `mode slow` answers its first call 300 ms late; `marker`, when given, takes a line for every call it receives. */
+const FAKE_CHILD = [
+ `import fs from "node:fs";`,
+ `const tag = process.argv[2] ?? "";`,
+ `const mode = process.argv[3] ?? "";`,
+ `const marker = process.argv[4] ?? "";`,
+ `let buf = "", answered = 0;`,
+ `const reply = (m) => process.stdout.write(JSON.stringify(m) + "\\n");`,
+ `process.stdin.on("data", (c) => {`,
+ ` buf += c; let i;`,
+ ` while ((i = buf.indexOf("\\n")) !== -1) {`,
+ ` const line = buf.slice(0, i); buf = buf.slice(i + 1);`,
+ ` if (!line.trim()) continue;`,
+ ` let f; try { f = JSON.parse(line); } catch { continue; }`,
+ ` if (f.method === "initialize") reply({ jsonrpc: "2.0", id: f.id, result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "fake-cua-" + tag, version: "1" } } });`,
+ ` else if (f.method === "tools/list") reply({ jsonrpc: "2.0", id: f.id, result: { tools: [{ name: "screenshot-" + tag }] } });`,
+ ` else if (f.method === "tools/call") {`,
+ ` if (mode === "die") process.exit(1);`,
+ ` answered += 1;`,
+ ` if (marker) fs.appendFileSync(marker, "called\\n");`,
+ ` const text = "did " + f.params.name + " #" + answered + " on " + tag;`,
+ ` const wait = mode === "slow" && answered === 1 ? 300 : 0;`,
+ ` setTimeout(() => reply({ jsonrpc: "2.0", id: f.id, result: { content: [{ type: "text", text }] } }), wait);`,
+ ` }`,
+ ` }`,
+ `});`,
+].join("\n");
+
+const until = async <T>(read: () => T | Promise<T>, accept: (value: T) => boolean, ms = 10_000): Promise<T> => {
+ const end = Date.now() + ms;
+ for (;;) {
+ const value = await read();
+ if (accept(value)) return value;
+ if (Date.now() >= end) throw new Error(`fixture wait expired: ${JSON.stringify(value)}`);
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+};
+
+/** How many calls the stand-in child wrote to its marker. */
+const callsReceived = (marker: string): number =>
+ existsSync(marker) ? readFileSync(marker, "utf8").split("\n").filter((line) => line === "called").length : 0;
+
+describe("the boxed VPS computer's host-side proxy", () => {
+ let home = "";
+ let harness: Server;
+ let harnessUrl = "";
+ let shim: ChildProcess | null = null;
+ /** What the stub answered at POST /api/internal/computer/mcp, as harness-mcp-proxy sent it. */
+ const relayed: Array<{ auth: string | null; body: { method?: string; params?: { name?: string } } }> = [];
+ /** The desktop's takes as the host counts them: a gate refuses a call that arrived before the latest take, as the
+ * host's gate refuses one that waited through a person's hold. */
+ const takes = { now: 100, lastTake: 0 };
+ const gate = { held: false, blockedReason: HELD };
+ let mountedBot = BOT;
+ /** Each call's turn, as the host ends it when the caller goes away. */
+ const turns: AbortController[] = [];
+ /** One waiter per JSON-RPC id of the engine side of the shim. */
+ const waiting = new Map<number, (message: unknown) => void>();
+
+ const call = (method: string, params: unknown = {}, id = 1): Promise<any> => new Promise((resolve, reject) => {
+ const timer = setTimeout(() => { waiting.delete(id); reject(new Error(`no answer to ${method} #${id}`)); }, 20_000);
+ timer.unref?.();
+ waiting.set(id, (message) => { clearTimeout(timer); resolve(message); });
+ shim!.stdin!.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
+ });
+
+ /** Mounts the stand-in for the bot: `args` are the child's after its tag. */
+ const serve = (tag: string, args: string[] = [], command = process.execPath) =>
+ vpsComputerTools(BOT, { token: TOKEN }, HARNESS, { sshAlias: "prod-vps", container: `omb-cua-${tag}`, command,
+ args: command === process.execPath ? [join(home, "fake-cua.mjs"), tag, ...args] : args });
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), "omb-vps-rpc-"));
+ writeFileSync(join(home, "fake-cua.mjs"), FAKE_CHILD);
+ harness = createServer((req, res) => {
+ let body = "";
+ req.on("data", (chunk) => { body += chunk; });
+ req.on("end", async () => {
+ const parsed = JSON.parse(body) as { method?: string; params?: { name?: string } };
+ relayed.push({ auth: req.headers.authorization ?? null, body: parsed });
+ const turn = new AbortController();
+ turns.push(turn);
+ // As the host's route does: the VPS path ends the response itself, with 403 when the bot has no VPS computer.
+ await vpsComputerTurn({
+ body: parsed, res,
+ json: (_r, status, payload) => {
+ if (res.writableEnded) throw new Error("the response was already ended");
+ res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(payload));
+ },
+ botId: mountedBot,
+ assertActive: () => {},
+ takeSequence: () => takes.now,
+ gate: async (since) => {
+ const handedBack = takes.lastTake > since;
+ return { held: handedBack || gate.held, helpOpen: false, ...(handedBack ? { blockedReason: HANDED_BACK } : gate.held ? { blockedReason: gate.blockedReason } : {}) };
+ },
+ signal: turn.signal,
+ });
+ });
+ });
+ await new Promise<void>((resolve) => harness.listen(0, "127.0.0.1", resolve));
+ harnessUrl = `http://127.0.0.1:${(harness.address() as { port: number }).port}`;
+ shim = spawn(process.execPath, ["--experimental-strip-types", SPAWNED_PROXIES.harnessMcp, "computer"], {
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: "1", OMB_HARNESS_URL: harnessUrl, [harnessMcpTokenEnv("computer")]: TOKEN },
+ stdio: ["pipe", "pipe", "ignore"],
+ });
+ let buffer = "";
+ shim.stdout!.on("data", (chunk: Buffer) => {
+ buffer += chunk.toString("utf8");
+ let newline: number;
+ while ((newline = buffer.indexOf("\n")) !== -1) {
+ const line = buffer.slice(0, newline);
+ buffer = buffer.slice(newline + 1);
+ if (!line.trim()) continue;
+ let message: { id?: unknown } | null = null;
+ try { message = JSON.parse(line); } catch { continue; }
+ if (message && typeof message.id === "number" && waiting.has(message.id)) waiting.get(message.id)!(message);
+ }
+ });
+ shim.stderr?.on("data", (chunk: Buffer) => process.stderr.write(`harness proxy: ${chunk}`));
+ });
+
+ afterAll(async () => {
+ await waitForExit(shim ?? undefined, { signal: "SIGKILL" });
+ forgetVpsComputers();
+ harness.closeAllConnections();
+ await new Promise<void>((resolve) => harness.close(() => resolve()));
+ removeTempDir(home);
+ });
+
+ beforeEach(() => {
+ forgetVpsComputers();
+ gate.held = false;
+ takes.now += 10; takes.lastTake = 0;
+ turns.length = 0;
+ mountedBot = BOT;
+ serve("a", ["a"]);
+ });
+
+ it("the boxed mount is the cloud computer's shim with the turn's capability, and registers the VPS target", () => {
+ const mount = serve("a", ["a"]);
+ expect(mount.command).toBe(process.execPath);
+ expect(mount.args).toEqual([expect.stringMatching(/harness-mcp-proxy\.(?:ts|js)$/), "computer"]);
+ expect(mount.env.OMB_HARNESS_URL).toBe(HARNESS);
+ expect(mount.env[harnessMcpTokenEnv("computer")]).toBe(TOKEN);
+ expect(mount.platform).toBe("linux");
+ });
+
+ it("the engine's shim reaches the VPS proxy's tools with the turn's capability", async () => {
+ await expect(call("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "engine", version: "1" } })).resolves.toMatchObject({ result: { serverInfo: { name: "openmausbot-computer" } } });
+ await expect(call("tools/list", {}, 2)).resolves.toEqual({ jsonrpc: "2.0", id: 2, result: { tools: [{ name: "screenshot-a" }] } });
+ await expect(call("tools/call", { name: "screenshot", arguments: {} }, 3)).resolves.toEqual({ jsonrpc: "2.0", id: 3, result: { content: [{ type: "text", text: "did screenshot #1 on a" }] } });
+ expect(relayed.at(-2)).toMatchObject({ auth: `Bearer ${TOKEN}`, body: { method: "tools/list" } });
+ expect(relayed.at(-1)).toMatchObject({ auth: `Bearer ${TOKEN}`, body: { method: "tools/call", params: { name: "screenshot" } } });
+ });
+
+ it("calls act in order on the one desktop", async () => {
+ serve("slow", ["slow"]);
+ const first = call("tools/call", { name: "screenshot" }, 10);
+ const second = call("tools/call", { name: "get_screen_size" }, 11);
+ await expect(first).resolves.toMatchObject({ result: { content: [{ text: "did screenshot #1 on slow" }] } });
+ await expect(second).resolves.toMatchObject({ result: { content: [{ text: "did get_screen_size #2 on slow" }] } });
+ });
+
+ it("a person holding the desktop refuses the call without it reaching the VPS", async () => {
+ const marker = join(home, "held.txt");
+ serve("held", ["", marker]);
+ gate.held = true;
+ await expect(call("tools/call", { name: "screenshot" }, 12)).resolves.toEqual({
+ jsonrpc: "2.0", id: 12, result: { content: [{ type: "text", text: controlRefusal({ blockedReason: HELD }) }], isError: true },
+ });
+ expect(callsReceived(marker)).toBe(0);
+ });
+
+ it("a person who takes the desktop while a call waits for an earlier one refuses that call", async () => {
+ serve("slow", ["slow"]);
+ const first = call("tools/call", { name: "screenshot" }, 20);
+ const second = call("tools/call", { name: "click" }, 21);
+ await until(() => turns.length, (arrived: number) => arrived >= 2);
+ takes.lastTake = ++takes.now;
+ await expect(first).resolves.toMatchObject({ result: { content: [{ text: "did screenshot #1 on slow" }] } });
+ expect((await second).result).toEqual({ content: [{ type: "text", text: HANDED_BACK }], isError: true });
+ // The desktop never saw the refused call: a later one, arrived after the take, is the same child's second.
+ await expect(call("tools/call", { name: "get_screen_size" }, 22)).resolves.toMatchObject({ result: { content: [{ text: "did get_screen_size #2 on slow" }] } });
+ });
+
+ it("a call whose turn ended while it waited for an earlier one is never sent to the desktop", async () => {
+ const marker = join(home, "waiting.txt");
+ serve("slow", ["slow", marker]);
+ const first = call("tools/call", { name: "screenshot" }, 30);
+ const second = call("tools/call", { name: "click" }, 31);
+ await until(() => turns.length, (arrived: number) => arrived >= 2);
+ turns[1]!.abort();
+ await expect(first).resolves.toMatchObject({ result: { content: [{ text: "did screenshot #1 on slow" }] } });
+ expect((await second).result).toMatchObject({ isError: true, content: [{ text: "The turn ended before this call reached the VPS computer, so nothing was run." }] });
+ expect(callsReceived(marker)).toBe(1);
+ await expect(call("tools/call", { name: "get_screen_size" }, 32)).resolves.toMatchObject({ result: { content: [{ text: "did get_screen_size #2 on slow" }] } });
+ });
+
+ it("a call the desktop never answered ends unconfirmed, and the next one starts a new child", async () => {
+ const marker = join(home, "unconfirmed.txt");
+ serve("slow", ["slow", marker]);
+ const first = call("tools/call", { name: "type_text" }, 40);
+ await until(() => callsReceived(marker), (count: number) => count >= 1);
+ turns.at(-1)!.abort();
+ expect((await first).result).toMatchObject({ isError: true, content: [{ text: expect.stringContaining("the result was not confirmed") }] });
+ // The first call may still be typing on the desktop: a new child, whose count starts again, takes the next one.
+ await expect(call("tools/call", { name: "screenshot" }, 41)).resolves.toMatchObject({ result: { content: [{ text: "did screenshot #1 on slow" }] } });
+ });
+
+ it("a proxy that cannot start answers the failure instead of letting its start error escape", async () => {
+ serve("x", [], join(home, "no-such-proxy"));
+ const answer = await call("tools/call", { name: "screenshot" }, 50);
+ expect(answer.result.isError).toBe(true);
+ expect(answer.result.content[0].text).toContain("stopped before it connected");
+ });
+
+ it("a turn of a bot with no VPS computer answers 403", async () => {
+ mountedBot = "other-bot";
+ const answer = await call("tools/list", {}, 13);
+ expect(answer.error?.code).toBe(-32603);
+ expect(answer.error?.message).toContain("no cloud computer");
+ });
+
+ it("a re-provisioned container drops the child that pointed at the old one", async () => {
+ serve("b", ["b"]);
+ await expect(call("tools/call", { name: "screenshot" }, 14)).resolves.toMatchObject({ result: { content: [{ text: "did screenshot #1 on b" }] } });
+ await expect(call("tools/list", {}, 15)).resolves.toMatchObject({ result: { tools: [{ name: "screenshot-b" }] } });
+ });
+
+ it("a child that dies mid-call answers the failure, and a later call starts a new one", async () => {
+ serve("die", ["die"]);
+ const answer = await call("tools/call", { name: "screenshot" }, 16);
+ expect(answer.result.isError).toBe(true);
+ expect(answer.result.content[0].text).toContain("connection was interrupted");
+ serve("b", ["b"]);
+ await until(async () => (await call("tools/call", { name: "screenshot" }, 17)).result.content[0].text, (text: string) => text.includes("on b"));
+ });
+});
diff --git a/server/vps-computer-rpc.ts b/server/vps-computer-rpc.ts
new file mode 100644
index 0000000000..cfc2d4a25c
--- /dev/null
+++ b/server/vps-computer-rpc.ts
@@ -0,0 +1,220 @@
+// A VPS computer's proxy process, kept on the host: a boxed engine cannot reach the VPS itself (its network namespace
+// has no routes and the egress gate is public-only), so the engine gets the cloud computer's mount instead — the
+// harness MCP proxy it starts dials the harness gate, and POST /api/internal/computer/mcp serves this proxy's tools
+// for a turn whose capability names no Boat. The child speaks the same stdio MCP the engine would have spawned.
+import { spawn, type ChildProcess } from "node:child_process";
+import type { ServerResponse } from "node:http";
+
+import { controlRefusal, type ControlState } from "./control-client.ts";
+import { COMPUTER_PROXY_TIMEOUT_MS } from "./harness-budget.ts";
+import { harnessMcpTokenEnv } from "./harness-mcp-token.ts";
+import { augmentedPath } from "./env-path.ts";
+import { createLineSplitter } from "./mcp-bridge.ts";
+import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts";
+
+/** An idle child is dropped (its SSH master stays cached); the next call starts a new one. */
+const CHILD_IDLE_MS = 10 * 60_000;
+/** A child that has not finished its MCP handshake in this long is dead enough (SSH down, container gone). */
+const CHILD_START_MS = 30_000;
+const CONNECTION_LOST = "The VPS computer's connection was interrupted. Take a fresh screenshot before repeating anything whose result is uncertain.";
+
+interface VpsTarget { sshAlias?: string; container: string; command?: string; args?: readonly string[] }
+
+interface Pending {
+ resolve(value: Record<string, unknown>): void;
+ reject(error: Error): void;
+}
+
+interface Child {
+ proc: ChildProcess;
+ /** The child's MCP initialize handshake; answered before the first call is sent. */
+ ready: Promise<void>;
+ /** One MCP request, serialized after the child's earlier ones (one desktop: calls act in order). */
+ rpc(method: string, params: unknown, signal?: AbortSignal): Promise<Record<string, unknown>>;
+ sshAlias?: string;
+ container: string;
+}
+
+const targets = new Map<string, VpsTarget>();
+const children = new Map<string, Child>();
+/** Per bot: the desktop's calls in arrival order; one entry each, replaced by the next call. */
+const queues = new Map<string, Promise<unknown>>();
+
+/** Test seam: forget every target and child. */
+export function forgetVpsComputers(): void {
+ for (const botId of children.keys()) dropChild(botId);
+ targets.clear();
+}
+
+/** The turn's bot serves its VPS computer's tools from here: remembers the target and drops a child that points at
+ * another one (a re-provisioned container). Returns the mount a boxed engine starts instead of the stdio proxy. */
+export function vpsComputerTools(
+ botId: string,
+ control: { token: string },
+ harnessUrl: string,
+ target: VpsTarget,
+): { command: string; args: string[]; env: Record<string, string>; platform: "linux" } {
+ targets.set(botId, target);
+ const child = children.get(botId);
+ if (child && (child.container !== target.container || child.sshAlias !== target.sshAlias)) dropChild(botId);
+ return {
+ command: process.execPath,
+ args: [SPAWNED_PROXIES.harnessMcp, "computer"],
+ env: { ...AGENTS_NODE_FLAG, OMB_HARNESS_URL: harnessUrl, [harnessMcpTokenEnv("computer")]: control.token },
+ platform: "linux",
+ };
+}
+
+const failedResult = (text: string) => ({ content: [{ type: "text", text }], isError: true });
+const failure = (error: unknown) => failedResult(error instanceof Error ? error.message : String(error));
+/** Why a request the child never answered ended: the desktop may still be running it. */
+const unanswered = (text: string) => Object.assign(new Error(text), { unanswered: true });
+
+/** Serves the internal computer calls of a turn that names no Boat from the bot's VPS proxy, and always ends the
+ * response: 403 when that bot has none mounted. A tools/call passes `gate` when its turn comes in the bot's queue, as
+ * the engine-spawned proxy's control client would. */
+export async function vpsComputerTurn(turn: {
+ body: { method?: unknown; params?: unknown };
+ res: ServerResponse;
+ json(res: ServerResponse, status: number, payload: unknown): void;
+ botId: string;
+ assertActive(): void;
+ /** The desktop's take count now. */
+ takeSequence(): number;
+ /** The control gate, asked about the takes since a count. */
+ gate(since: number): Promise<ControlState>;
+ signal?: AbortSignal;
+}): Promise<void> {
+ const method = turn.body.method;
+ if ((method !== "tools/list" && method !== "tools/call") || !targets.has(turn.botId)) {
+ turn.json(turn.res, 403, { error: "this turn has no cloud computer" });
+ return;
+ }
+ turn.assertActive();
+ const arrivedAt = turn.takeSequence();
+ // One desktop: a call waits for the bot's earlier ones, in arrival order, and passes the gate when its turn comes, so
+ // a desktop a person took while it waited is never acted on.
+ const previous = queues.get(turn.botId) ?? Promise.resolve();
+ const queued = previous.then(async (): Promise<Record<string, unknown>> => {
+ if (method === "tools/call") {
+ const state = await turn.gate(arrivedAt);
+ if (state.held) return failedResult(controlRefusal(state));
+ turn.assertActive();
+ }
+ const child = await childFor(turn.botId, targets.get(turn.botId)!);
+ try {
+ return await child.rpc(method, turn.body.params ?? {}, turn.signal);
+ } catch (error) {
+ if (method === "tools/list") throw error;
+ // A call the desktop never answered may still be running there: the next one starts a new child, never this one.
+ if ((error as { unanswered?: true }).unanswered && children.get(turn.botId) === child) dropChild(turn.botId);
+ return failure(error);
+ }
+ });
+ queues.set(turn.botId, queued.then(() => undefined, () => undefined));
+ try {
+ turn.json(turn.res, 200, { result: await queued });
+ } catch (error) {
+ if (method === "tools/list") throw error;
+ turn.json(turn.res, 200, { result: failure(error) });
+ }
+}
+
+function dropChild(botId: string): void {
+ const child = children.get(botId);
+ if (!child) return;
+ children.delete(botId);
+ // The close handler still runs: it rejects the child's pending calls and skips the map (already gone).
+ child.proc.kill("SIGKILL");
+}
+
+function childFor(botId: string, target: VpsTarget): Promise<Child> {
+ const known = children.get(botId);
+ if (known && known.container === target.container && known.sshAlias === target.sshAlias) return Promise.resolve(known);
+ if (known) dropChild(botId);
+ const child = openChild(botId, target);
+ children.set(botId, child);
+ const start = Promise.race([
+ child.ready,
+ new Promise<never>((_, reject) => {
+ const timer = setTimeout(() => reject(new Error("The VPS computer's proxy did not start. Check the VPS in Settings.")), CHILD_START_MS);
+ timer.unref?.();
+ }),
+ ]);
+ return start.then(() => child, (error) => { dropChild(botId); throw error instanceof Error ? error : new Error(String(error)); });
+}
+
+function openChild(botId: string, target: VpsTarget): Child {
+ const command = target.command ?? process.execPath;
+ const args = [...(target.args ?? [SPAWNED_PROXIES.vpsContainerMcp, target.sshAlias ?? "", target.container])];
+ const proc = spawn(command, args, { shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, PATH: augmentedPath(), ...AGENTS_NODE_FLAG } });
+ proc.stdin?.on("error", () => {});
+ proc.stderr?.on("data", (chunk: Buffer) => process.stderr.write(`vps computer: ${chunk}`));
+ const pending = new Map<string, Pending>();
+ let sequence = 0;
+ let idle: NodeJS.Timeout | null = null;
+ let handshakeDone = false;
+ const touch = () => {
+ if (idle) clearTimeout(idle);
+ idle = setTimeout(() => dropChild(botId), CHILD_IDLE_MS);
+ idle.unref?.();
+ };
+ const stop = () => {
+ if (idle) clearTimeout(idle);
+ if (children.get(botId) === self) children.delete(botId);
+ const text = handshakeDone ? CONNECTION_LOST : "The VPS computer's proxy stopped before it connected. Check the VPS in Settings.";
+ for (const wait of pending.values()) wait.reject(handshakeDone ? unanswered(text) : new Error(text));
+ pending.clear();
+ };
+ proc.on("close", stop);
+ // A start that fails (EAGAIN, ENOENT) is an event on the process, with no listener of its own elsewhere.
+ proc.on("error", stop);
+ const takeLine = (line: string) => {
+ if (!line.trim()) return;
+ let frame: { id?: unknown; result?: unknown; error?: { message?: unknown } } | null = null;
+ try { frame = JSON.parse(line); } catch { return; }
+ if (typeof frame?.id !== "string" || !pending.has(frame.id)) return;
+ const wait = pending.get(frame.id)!;
+ pending.delete(frame.id);
+ touch();
+ if (frame.error) wait.reject(new Error(typeof frame.error.message === "string" ? frame.error.message : CONNECTION_LOST));
+ else if (frame.result && typeof frame.result === "object") wait.resolve(frame.result as Record<string, unknown>);
+ else wait.reject(new Error(CONNECTION_LOST));
+ };
+ const outbound = createLineSplitter(takeLine);
+ proc.stdout?.on("data", (chunk: Buffer) => outbound.push(chunk));
+ proc.stdout?.on("end", () => outbound.flush());
+ const send = (method: string, params: unknown, signal: AbortSignal | undefined) => new Promise<Record<string, unknown>>((resolve, reject) => {
+ if (proc.exitCode !== null || proc.signalCode !== null) return reject(new Error(CONNECTION_LOST));
+ // The abort event is not repeated for a listener added after it, so a turn that ended while this call waited is seen here.
+ if (signal?.aborted) return reject(new Error("The turn ended before this call reached the VPS computer, so nothing was run."));
+ const id = `omb-vps-${++sequence}`;
+ const timer = setTimeout(() => {
+ pending.delete(id);
+ reject(unanswered("The VPS computer did not answer in time. It may still have run; check its state before repeating anything."));
+ }, COMPUTER_PROXY_TIMEOUT_MS);
+ timer.unref?.();
+ const onAbort = () => {
+ pending.delete(id);
+ clearTimeout(timer);
+ reject(unanswered("The turn ended while the VPS computer was working, so the result was not confirmed."));
+ };
+ signal?.addEventListener("abort", onAbort, { once: true });
+ pending.set(id, {
+ resolve: (value) => { pending.delete(id); clearTimeout(timer); signal?.removeEventListener("abort", onAbort); touch(); resolve(value); },
+ reject: (error) => { pending.delete(id); clearTimeout(timer); signal?.removeEventListener("abort", onAbort); reject(error); },
+ });
+ proc.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
+ });
+ const rpc = (method: string, params: unknown, signal?: AbortSignal) => {
+ touch();
+ return send(method, params, signal);
+ };
+ const ready = rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "openmausbot-vps-computer", version: "1" } })
+ .then(() => {
+ handshakeDone = true;
+ try { proc.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`); } catch {}
+ });
+ const self: Child = { proc, ready, rpc, sshAlias: target.sshAlias, container: target.container };
+ return self;
+}