Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a chat-runtime turn going when one MCP server dies, and give small Clouds time to start them
milind-soni84450939f417
diff --git a/electron/cua-watch-restart.test.mjs b/electron/cua-watch-restart.test.mjsnew file mode 100644index 0000000000..b681d7cbc5--- /dev/null+++ b/electron/cua-watch-restart.test.mjs@@ -0,0 +1,117 @@+// The Mac driver's watch as cua.mjs wires it: a real start, a socket that stops answering, and a real restart. Nothing here can+// start the operator's own driver: attachStandalone stops at the app it can't find, and no child process exists to launch.+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({ home: "", alive: true, hosts: [], failStarts: 0, granted: true }));+vi.mock("electron", () => ({ app: { isPackaged: false, getPath: () => fixture.home }, ipcMain: { handle: () => {} } }));+vi.mock("@trycua/cua-driver/embedded", () => ({+ EmbeddedCuaDriverHost: class {+ constructor() { fixture.hosts.push(this); }+ async start() {+ if (fixture.failStarts > 0) { fixture.failStarts -= 1; throw new Error("the driver could not start"); }+ return { socketPath: "/fixture/driver.sock" };+ }+ stop = vi.fn(async () => {});+ uniffiDestroy = vi.fn();+ },+}));+vi.mock("@trycua/cua-driver/electron", () => ({+ requestMacOSPermissions: () => ({ accessibility: fixture.granted, screenRecording: fixture.granted }),+ hasRequiredMacOSPermissions: () => fixture.granted,+}));+vi.mock("node:fs", async (original) => {+ const fs = await original();+ return { ...fs, default: { ...fs.default, existsSync: (file) => {+ if (String(file).endsWith(".sock")) return fixture.alive;+ if (String(file).includes("CuaDriver.app")) return false;+ return fs.existsSync(file);+ } } };+});+vi.mock("node:net", async (original) => {+ const net = await original();+ const { EventEmitter } = await import("node:events");+ return { ...net, default: { ...net.default, createConnection: () => {+ const socket = Object.assign(new EventEmitter(), { destroy: vi.fn() });+ queueMicrotask(() => socket.emit("connect"));+ return socket;+ } } };+});+vi.mock("./cua-watch.mjs", async (original) => {+ const actual = await original();+ return { ...actual, DEAD_DRIVER_RETRY_MS: [5, 5], watchDriver: (options) => actual.watchDriver({ ...options, everyMs: 5, log: () => {} }) };+});++let cua;+beforeEach(async () => {+ Object.assign(fixture, { home: mkdtempSync(join(tmpdir(), "omb-cua-watch-")), alive: true, hosts: [], failStarts: 0, granted: true });+ vi.stubEnv("OPENMAUSBOT_CUA_EMBEDDED", "1");+ vi.stubEnv("CUA_DRIVER_PATH", "/fixture/cua-driver");+ vi.resetModules();+ cua = await import("./cua.mjs");+});+afterEach(async () => {+ await cua?.stopCua();+ vi.unstubAllEnvs();+ rmSync(fixture.home, { recursive: true, force: true });+});+const pause = (ms = 60) => new Promise((resolve) => setTimeout(resolve, ms));++describe.skipIf(process.platform !== "darwin")("the Mac driver dies after it started", () => {+ it("leaves a driver that answers alone", async () => {+ await cua.startCua();+ await pause();+ expect(fixture.hosts).toHaveLength(1);+ });++ it("starts it again, and watches the new one", async () => {+ await expect(cua.startCua()).resolves.toMatchObject({ mode: "embedded" });+ fixture.alive = false;+ await expect.poll(() => fixture.hosts.length).toBeGreaterThanOrEqual(2);+ expect(fixture.hosts[0].stop).toHaveBeenCalledOnce();+ fixture.alive = true;+ const settled = fixture.hosts.length;+ await pause();+ expect(fixture.hosts).toHaveLength(settled);+ fixture.alive = false;+ await expect.poll(() => fixture.hosts.length).toBeGreaterThan(settled);+ });++ it("tries again when the restart fails, and stops trying after a few", async () => {+ await cua.startCua();+ fixture.failStarts = 100;+ fixture.alive = false;+ await expect.poll(() => fixture.hosts.length).toBe(4);+ await pause(100);+ expect(fixture.hosts).toHaveLength(4);+ });++ it("recovers when a later try works", async () => {+ await cua.startCua();+ fixture.failStarts = 1;+ fixture.alive = false;+ await expect.poll(() => fixture.hosts.length).toBeGreaterThanOrEqual(3);+ fixture.alive = true;+ expect(JSON.parse((await import("node:fs")).readFileSync(join(fixture.home, "cua-connection.json"), "utf8")).mode).toBe("embedded");+ });++ it("doesn't keep asking when macOS permissions are what's missing", async () => {+ await cua.startCua();+ fixture.granted = false;+ fixture.alive = false;+ await expect.poll(() => fixture.hosts.length).toBe(1);+ await pause(100);+ expect(fixture.hosts).toHaveLength(1);+ expect(JSON.parse((await import("node:fs")).readFileSync(join(fixture.home, "cua-connection.json"), "utf8")).mode).toBe("unavailable");+ });++ it("stops watching on an explicit Stop", async () => {+ await cua.startCua();+ await cua.stopCua();+ fixture.alive = false;+ await pause();+ expect(fixture.hosts).toHaveLength(1);+ });+});diff --git a/electron/cua-watch.mjs b/electron/cua-watch.mjsnew file mode 100644index 0000000000..37bf2bbc4a--- /dev/null+++ b/electron/cua-watch.mjs@@ -0,0 +1,34 @@+// Nothing else notices when the computer-control driver dies after it started: its socket stops answering, every MCP bridge+// exits as soon as it connects, and computer control stays broken until the app restarts. This asks the socket every so+// often and calls `restart` once when it has stopped answering.++export const WATCH_EVERY_MS = 15_000;+export const MISSES_BEFORE_RESTART = 2;+/** Between further tries when a restart didn't bring the driver back; then it waits for the person. */+export const DEAD_DRIVER_RETRY_MS = [5_000, 30_000, 120_000, 600_000];++/** A failure more tries won't fix: the person has to act, and each try may ask macOS for the permission again. */+export function restartWorthTrying(message) {+ return !/grant access|permission|restart cancelled/i.test(String(message ?? ""));+}++/** `restart` runs at most once per watch: a successful restart starts a new one. */+export function watchDriver({ alive, restart, everyMs = WATCH_EVERY_MS, misses = MISSES_BEFORE_RESTART, log = console.warn }) {+ let timer = null, stopped = false, missed = 0;+ const arm = () => {+ timer = setTimeout(tick, everyMs);+ timer.unref?.();+ };+ async function tick() {+ timer = null;+ const up = await Promise.resolve().then(alive).catch(() => false);+ if (stopped) return;+ missed = up ? 0 : missed + 1;+ if (missed < misses) return arm();+ stopped = true;+ log(`[cua] the driver stopped answering after ${missed} checks; starting it again`);+ await Promise.resolve().then(restart).catch((error) => log(`[cua] could not start the driver again: ${error?.message ?? error}`));+ }+ arm();+ return { stop() { stopped = true; clearTimeout(timer); timer = null; } };+}diff --git a/electron/cua-watch.test.mjs b/electron/cua-watch.test.mjsnew file mode 100644index 0000000000..93b0dfffd4--- /dev/null+++ b/electron/cua-watch.test.mjs@@ -0,0 +1,67 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { MISSES_BEFORE_RESTART, WATCH_EVERY_MS, restartWorthTrying, watchDriver } from "./cua-watch.mjs";++const tick = () => vi.advanceTimersByTimeAsync(WATCH_EVERY_MS);++describe("watching the computer-control driver", () => {+ afterEach(() => { vi.useRealTimers(); });++ it("leaves a driver that answers alone", async () => {+ vi.useFakeTimers();+ const restart = vi.fn();+ const watch = watchDriver({ alive: async () => true, restart });+ for (let i = 0; i < 6; i++) await tick();+ expect(restart).not.toHaveBeenCalled();+ watch.stop();+ });++ it("starts it again once, after enough checks in a row have gone unanswered", async () => {+ vi.useFakeTimers();+ const restart = vi.fn(async () => {}), log = vi.fn();+ const watch = watchDriver({ alive: async () => false, restart, log });+ for (let i = 0; i < MISSES_BEFORE_RESTART - 1; i++) await tick();+ expect(restart).not.toHaveBeenCalled();+ for (let i = 0; i < 4; i++) await tick();+ expect(restart).toHaveBeenCalledTimes(1);+ expect(log.mock.calls[0][0]).toContain("stopped answering");+ watch.stop();+ });++ it("forgives one missed check: a laptop waking from sleep isn't a dead driver", async () => {+ vi.useFakeTimers();+ const answers = [false, true, false, true, false, true];+ const restart = vi.fn();+ const watch = watchDriver({ alive: async () => answers.shift() ?? true, restart });+ for (let i = 0; i < 6; i++) await tick();+ expect(restart).not.toHaveBeenCalled();+ watch.stop();+ });++ it("counts a check that throws as unanswered", async () => {+ vi.useFakeTimers();+ const restart = vi.fn(async () => {});+ const watch = watchDriver({ alive: async () => { throw new Error("no socket"); }, restart, log: () => {} });+ for (let i = 0; i < MISSES_BEFORE_RESTART; i++) await tick();+ expect(restart).toHaveBeenCalledTimes(1);+ watch.stop();+ });++ it("does nothing once stopped", async () => {+ vi.useFakeTimers();+ const restart = vi.fn();+ const watch = watchDriver({ alive: async () => false, restart });+ watch.stop();+ for (let i = 0; i < 6; i++) await tick();+ expect(restart).not.toHaveBeenCalled();+ });++ it.each([+ ["Accessibility and Screen Recording required; grant access in System Settings and restart OpenMausBot", false],+ ["Computer use restart cancelled", false],+ ["embedded host failed: EmbeddedDriverError.Spawn; standalone launch failed: timed out", true],+ [undefined, true],+ ])("decides whether another try can help: %s", (message, worth) => {+ expect(restartWorthTrying(message)).toBe(worth);+ });+});diff --git a/electron/cua.mjs b/electron/cua.mjsindex 9c2808714c..a95fb91695 100644--- a/electron/cua.mjs+++ b/electron/cua.mjs@@ -13,6 +13,7 @@ import { pathToFileURL } from "node:url";import localOriginModule from "./local-origin.cjs";import { createLocalComputerGrant } from "./local-computer-grant.mjs";import { driverFailure } from "./cua-failure.mjs";+import { DEAD_DRIVER_RETRY_MS, restartWorthTrying, watchDriver } from "./cua-watch.mjs";const { localOnly } = localOriginModule;@@ -52,6 +53,9 @@ let startupAbort = null;* is tried again by itself after these waits; a blocked or missing helper is not. */const RETRY_AFTER_MS = [15_000, 60_000];let retryTimer = null;+let driverWatch = null;+let deadDriverRetry = null;+let deadDriverRestarts = 0;let lifecycleGeneration = 0;let macRetry = null;let linuxRuntime = null;@@ -341,9 +345,28 @@ export async function startCua({ attempt = 0 } = {}) {retryTimer = setTimeout(() => { retryTimer = null; void startCua({ attempt: attempt + 1 }).catch(() => {}); }, RETRY_AFTER_MS[attempt]);retryTimer.unref?.();}+ watchMacDriver(nextConnection);return persistAndNotify(nextConnection);}+/** Starts computer control again when the running Mac driver stops answering, and keeps trying for a while if that fails. */+function watchMacDriver(connection) {+ driverWatch?.stop();+ driverWatch = null;+ if (process.platform !== "darwin" || (connection.mode !== "embedded" && connection.mode !== "standalone")) return;+ deadDriverRestarts = 0;+ driverWatch = watchDriver({ alive: () => socketAlive(connection.socketPath), restart: restartDeadDriver });+}++async function restartDeadDriver() {+ const attempt = deadDriverRestarts;+ const outcome = await restartCua();+ if (outcome.enabled || !restartWorthTrying(outcome.message) || attempt >= DEAD_DRIVER_RETRY_MS.length) return;+ deadDriverRestarts = attempt + 1;+ deadDriverRetry = setTimeout(() => { deadDriverRetry = null; void restartDeadDriver().catch(() => {}); }, DEAD_DRIVER_RETRY_MS[attempt]);+ deadDriverRetry.unref?.();+}+export async function cuaPermissionsStatus() {const binary = resolveDriverBinary();if (!binary) return { available: false };@@ -364,6 +387,10 @@ export async function cuaPermissionsStatus() {export async function stopCua() {clearTimeout(retryTimer);retryTimer = null;+ driverWatch?.stop();+ driverWatch = null;+ clearTimeout(deadDriverRetry);+ deadDriverRetry = null;lifecycleGeneration++;startupAbort?.abort();startupAbort = null;diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex 96dd8a2ff6..d5dd76467b 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -6,9 +6,10 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { augmentedPath } from "../env-path.ts";import { MESSAGE_FILE_MAX_BYTES } from "../message-file.ts";import { Ajv2020 } from "ajv/dist/2020.js";-import { ChatToolSessionError, SAVED_RESULTS_FOLDER, SAVED_RESULTS_KEPT, chatToolNotices, directServers, mountChatTools, trimmedToolsNotice, type ChatToolSession } from "./chat-mcp-tools.ts";+import { ChatMcpClient, ChatToolSessionError, SAVED_RESULTS_FOLDER, SAVED_RESULTS_KEPT, chatToolNotices, directServers, mcpStartupMs, mountChatTools, trimmedToolsNotice, type ChatToolSession } from "./chat-mcp-tools.ts";import { EXECUTOR_LIKE_TOOLS } from "../testing/executor-like-tools.ts";import type { ToolScope } from "../../shared/tool-scope.ts";+import type { SendTurnInput } from "../contracts.ts";import { catalogServer, CUA_DRIVER_WINDOWS_TOOLS, syntheticToolNames } from "../testing/cua-driver-tools.ts";import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";@@ -305,30 +306,128 @@ describe("Chat MCP session", () => {it.each([["too many tools", `reply(message, {tools:Array.from({length:2001},(_,i)=>({name:"tool"+i,inputSchema:schema}))});`],["invalid RPC", `process.stdout.write('{"result":1}\\n');`],- ])("still fails startup for a harness mount and awaits child cleanup for %s", async (_label, response) => {+ ])("fails startup when the agents server can't start, naming it, and awaits child cleanup for %s", async (_label, response) => {const f = fixture(`if (message.method === "tools/list") { ${response} continue; }`);- await expect(f.mount(true, true)).rejects.toThrow(/MCP/);+ await expect(mountChatTools({ agents: f.server } as SendTurnInput["integrations"], f.controller.signal)).rejects.toThrow(/^MCP server "agents" didn't start: MCP/);expect(alive(f.read().pid)).toBe(false);});- it("rejects untrusted transport error text without leaking it", async () => {+ describe("a built-in the turn can go on without", () => {+ const broken = `if (message.method === "tools/list") { process.stdout.write('{"result":1}\\n'); continue; }`;+ it.each([+ ["computer", "localComputer"],+ ["browser", "browser"],+ ["email", "email"],+ ["device", "device"],+ ["data", "data"],+ ] as const)("%s is left out and the turn says so, while the others still mount", async (server, key) => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ try {+ const dead = fixture(broken), agents = fixture();+ const session = await mountChatTools({ [key]: dead.server, agents: agents.server } as SendTurnInput["integrations"], dead.controller.signal, true);+ sessions.push(session);+ expect(session.skipped).toEqual([{ server, reason: expect.stringMatching(/MCP/) }]);+ expect(chatToolNotices(session).join(" ")).toContain(`MCP server "${server}" was skipped for this turn`);+ expect(session.definitions.map((tool) => tool.function.name)).toEqual(["agents_write"]);+ expect(alive(dead.read().pid)).toBe(false);+ } finally { warn.mockRestore(); }+ });+ });++ describe("a server that fails during a turn", () => {+ const warnings = () => vi.spyOn(console, "warn").mockImplementation(() => {});+ async function pair(body: string, env: Record<string, string> = {}) {+ const failing = fixture(body), healthy = fixture();+ const session = await mountChatTools({ custom: { audit: { ...failing.server, env: { ...failing.server.env, ...env } }, other: healthy.server } }, failing.controller.signal);+ sessions.push(session);+ return { failing, healthy, session, signal: failing.controller.signal };+ }++ it("takes only that server, says which and why, masks its stderr, and leaves the other tools working", async () => {+ const warn = warnings();+ try {+ const token = "fixture-configured-value-77";+ const { failing, session, signal } = await pair(`if (message.method === "tools/call") { process.stderr.write("early line\\nboom with " + process.env.API_TOKEN + " and sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123\\n"); setTimeout(() => process.exit(3), 20); return; }`, { API_TOKEN: token });+ const result = await session.execute("audit_write", { value: "x" }, signal);+ expect(result.ok).toBe(false);+ expect(result.text).toContain("MCP server exited before the session closed.");+ expect(result.text).toContain("It last said: boom with [redacted]");+ expect(result.text).toContain('That was the MCP server "audit". It is stopped for the rest of this turn');+ expect(result.text).not.toContain(token);+ expect(result.text).not.toContain("abcdefghijklmnopqrstuvwxyz0123");+ expect(alive(failing.read().pid)).toBe(false);++ await expect(session.execute("other_write", { value: "y" }, signal)).resolves.toMatchObject({ ok: true, text: "recorded:y" });+ expect(() => session.validate("other_write", { value: "y" })).not.toThrow();+ } finally { warn.mockRestore(); }+ });++ it("never runs a call again on a server that stopped, and says why", async () => {+ const warn = warnings();+ try {+ const { failing, session, signal } = await pair(`if (message.method === "tools/call") { process.exit(3); }`);+ await session.execute("audit_write", { value: "x" }, signal);+ const again = await session.execute("audit_write", { value: "x" }, signal);+ expect(again.ok).toBe(false);+ expect(again.text).toContain('MCP server exited before the session closed. That was the MCP server "audit"');+ expect(failing.read().calls.filter((call) => call.method === "tools/call")).toHaveLength(1);+ } finally { warn.mockRestore(); }+ });++ it("says so on the next call when the server stopped between calls", async () => {+ const warn = warnings();+ try {+ const { session, signal } = await pair(`if (message.method === "tools/list") { reply(message, {tools:[{name:"write",description:"Fixture write",inputSchema:schema}]}); setTimeout(() => process.exit(0), 20); continue; }`);+ await new Promise((resolve) => setTimeout(resolve, 400));+ const result = await session.execute("audit_write", { value: "x" }, signal);+ expect(result).toMatchObject({ ok: false, text: expect.stringContaining("MCP server exited before the session closed") });+ } finally { warn.mockRestore(); }+ });++ it("still ends the turn's session when the person stops it", async () => {+ const f = fixture(`if (message.method === "tools/call") { return; }`);+ const session = await f.mount();+ const stop = new AbortController();+ const pending = session.execute("audit_write", { value: "x" }, stop.signal);+ await vi.waitFor(() => expect(f.read().calls.some((call) => call.method === "tools/call")).toBe(true));+ stop.abort();+ await expect(pending).rejects.toBeInstanceOf(ChatToolSessionError);+ expect(() => session.validate("audit_write", { value: "x" })).toThrow(ChatToolSessionError);+ });+ });++ describe("how long a server gets to start", () => {+ it("is about half a minute on a Cloud home and eight seconds elsewhere", () => {+ expect(mcpStartupMs({ OMB_CLOUD_ROLE: "home" })).toBe(30_000);+ expect(mcpStartupMs({ OMB_CLOUD_ROLE: "team" })).toBe(30_000);+ expect(mcpStartupMs({})).toBe(8_000);+ });++ it.each(["initialize", "tools/list"])("reports an overrun in %s as a startup timeout, not as a request whose outcome is uncertain", async (method) => {+ const f = fixture(`if (message.method === "${method}") { return; }`);+ const client = new ChatMcpClient(f.server);+ await expect(client.tools(f.controller.signal, undefined, 150)).rejects.toThrow(/^MCP startup timed out$/);+ await client.close();+ });+ });++ it("keeps a server that refused a call, without leaking what it said", async () => {const f = fixture(`if (message.method === "tools/call") { send({jsonrpc:"2.0",id:message.id,error:{code:-1,message:"secret-fixture-key"}}); continue; }`);const session = await f.mount();- const result = await session.execute("audit_write", { value: "test" }, f.controller.signal).catch((error: Error) => error);- expect(result).toBeInstanceOf(ChatToolSessionError);- expect(String(result)).toContain("MCP request failed");- expect(String(result)).not.toContain("secret-fixture-key");- expect(alive(f.read().pid)).toBe(false);+ const result = await session.execute("audit_write", { value: "test" }, f.controller.signal);+ expect(result).toMatchObject({ ok: false, text: 'MCP request failed; inspect the configured integration That was the MCP server "audit".' });+ expect(result.text).not.toContain("secret-fixture-key");+ expect(alive(f.read().pid)).toBe(true);});it("rejects malformed tool content instead of accepting an empty successful result", async () => {const f = fixture(`if (message.method === "tools/call") { reply(message,{content:[{type:"text",text:42}]}); continue; }`);const session = await f.mount();- const pending = session.execute("audit_write", {value:"test"}, f.controller.signal);- await expect(pending).rejects.toBeInstanceOf(ChatToolSessionError);- await expect(pending).rejects.toThrow("invalid content");- expect(alive(f.read().pid)).toBe(false);- expect(() => session.validate("audit_write", {value:"test"})).toThrow(ChatToolSessionError);+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ try {+ await expect(session.execute("audit_write", {value:"test"}, f.controller.signal)).resolves.toMatchObject({ ok: false, text: expect.stringContaining("invalid content") });+ expect(alive(f.read().pid)).toBe(false);+ } finally { warn.mockRestore(); }});it("keeps schema errors recoverable without dispatching or closing the transport", async () => {@@ -436,9 +535,12 @@ describe("Chat MCP session", () => {warn.mockRestore();});- it("fails setup when the Local VM lists no tools, but not when the owner's selection leaves none", async () => {+ it("goes on without a Local VM that lists no tools, saying so, and doesn't when the owner's selection leaves none", async () => {const empty = fixture(`if(message.method === "tools/list") { reply(message,{tools:[]}); continue; }`);- await expect(empty.mount(true, true)).rejects.toThrow("The Local VM listed no tools");+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ try {+ expect((await empty.mount(true, true)).skipped).toEqual([{ server: "computer", reason: "The Local VM listed no tools" }]);+ } finally { warn.mockRestore(); }expect(alive(empty.read().pid)).toBe(false);expect((await empty.mount(false)).definitions).toEqual([]);expect((await fixture().mount(true, true, { allow: ["mcp:computer:screenshot"] })).definitions).toEqual([]);@@ -1037,13 +1139,13 @@ describe("Chat MCP schema validation", () => {it("keeps a bounded frame limit for image-enabled custom servers", async () => {const f = fixture('if(message.method === "tools/call") { process.stdout.write("x".repeat(32*1024*1024+1)); continue; }');const session = await f.mount(true);- await expect(session.execute("audit_write", { value: "large" }, f.controller.signal)).rejects.toThrow(/frame|limit/i);+ await expect(session.execute("audit_write", { value: "large" }, f.controller.signal)).resolves.toMatchObject({ ok: false, text: expect.stringMatching(/frame|limit/i) });});it("rejects malformed image results without claiming execution success", async () => {const f = fixture('if(message.method === "tools/call") { reply(message,{content:[{type:"image",mimeType:"image/png",data:"not-base64"}]}); continue; }');const session = await f.mount(true);- await expect(session.execute("audit_write", { value: "screenshot" }, f.controller.signal)).rejects.toThrow("Invalid or oversized MCP image");+ await expect(session.execute("audit_write", { value: "screenshot" }, f.controller.signal)).resolves.toMatchObject({ ok: false, text: expect.stringContaining("Invalid or oversized MCP image") });});it.each([{ type: "object", properties: { value: { type: "string", minLength: 2 } }, required: ["value"] },@@ -1165,7 +1267,7 @@ describe("Chat MCP schema validation", () => {const f = fixture(delayed);const short = await mountChatTools({ custom: { audit: f.server } }, f.controller.signal, false, undefined, 100);sessions.push(short);- await expect(short.execute("audit_write", { value: "x" }, f.controller.signal)).rejects.toThrow("MCP request timed out");+ await expect(short.execute("audit_write", { value: "x" }, f.controller.signal)).resolves.toMatchObject({ ok: false, text: expect.stringContaining("MCP request timed out") });await expect(f.read().calls.filter((call) => call.method === "tools/call")).toHaveLength(1);const long = await mountChatTools({ custom: { audit: f.server } }, f.controller.signal, false, undefined, 5_000);diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex 8fc21f812e..76fe7ea275 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -6,6 +6,7 @@ import { join } from "node:path";import type { ValidateFunction } from "ajv";import { stripControlPlaneEnv } from "../config.ts";import type { SendTurnInput } from "../contracts.ts";+import { cloudRole } from "../bot-box/detect.ts";import { redactSecretsInText } from "../redact.ts";import { MESSAGE_FILE_MAX_BYTES } from "../message-file.ts";import { augmentedPath } from "../env-path.ts";@@ -62,6 +63,19 @@ function chatToolName(server: string, tool: string): string {return `${server}_${tool}`.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64) || "mcp_tool";}const STARTUP_MS = 8_000;+/** A small Cloud home that is busy can take this long to load Node and a server's own imports. */+const CLOUD_STARTUP_MS = 30_000;+const STARTUP_TIMED_OUT = "MCP startup timed out";+const REQUEST_TIMED_OUT = "MCP request timed out; execution outcome may be uncertain";+/** How much of a server's stderr is kept, and how much of its last line is ever shown. */+const STDERR_TAIL_CHARS = 4_000, STDERR_LINE_CHARS = 300;+/** Built-ins a turn can go on without, saying so. A turn can't run without the agents server. */+const OPTIONAL_BUILT_INS: ReadonlySet<string> = new Set(["computer", "browser", "composio", OWN_APPS_SERVER, "data", "email", "device"]);++/** How long a server that runs a command gets to start here. */+export function mcpStartupMs(env: Record<string, string | undefined> = process.env): number {+ return cloudRole(env) ? CLOUD_STARTUP_MS : STARTUP_MS;+}const DEFAULT_CALL_MS = 10 * 60_000;const FRAME_BYTES = 2 * 1024 * 1024;const OUTPUT_BYTES = 50 * 1024;@@ -97,11 +111,15 @@ export class ChatMcpClient {private frames = 0;private closed = false;private closing?: Promise<void>;+ private failure?: string;+ private stderrTail = "";+ private readonly configured: string[];private pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();/** `configured`: a server the person set up, whose own environment passes the bot box as theirs. */constructor(server: Server, computerUse = false, configured = false) {this.frameBytes = computerUse ? 32 * 1024 * 1024 : FRAME_BYTES;+ this.configured = Object.values(server.env).filter((value) => value.length >= 6);try {// The desktop shell inherits Finder's bare PATH, where `npx`-style servers cannot find `node`.this.child = spawnCli(server.command, server.args, {@@ -111,16 +129,30 @@ export class ChatMcpClient {} catch { throw new Error("MCP server could not start; check its command and installation"); }this.child.stdout.setEncoding("utf8");this.child.stdout.on("data", (chunk: string) => this.onData(chunk));- // Stderr may contain credentials; drain without recording or returning it.- this.child.stderr.on("data", () => {});+ this.child.stderr.on("data", (chunk: Buffer | string) => { this.stderrTail = `${this.stderrTail}${chunk}`.slice(-STDERR_TAIL_CHARS); });this.child.on("error", () => this.fail(new Error("MCP server could not start; check its command and installation")));- this.child.on("exit", () => this.fail(new Error("MCP server exited before the session closed")));+ // "close" follows the last of its output, so what it said on the way out is read first; a helper still holding stderr doesn't hold this up.+ this.child.on("exit", () => {+ const stop = () => this.fail(new Error(`MCP server exited before the session closed.${this.lastWords()}`));+ this.child.once("close", stop);+ setTimeout(stop, 200).unref();+ });this.child.stdin.on("error", () => this.fail(new Error("MCP server input closed")));}+ /** The last line the server wrote to stderr, for saying why it stopped. Stderr can hold credentials, so its configured+ * values and anything shaped like a secret are masked first, and a line cut off by the tail is never shown. */+ private lastWords(): string {+ const whole = this.stderrTail.length >= STDERR_TAIL_CHARS ? this.stderrTail.slice(this.stderrTail.indexOf("\n") + 1 || this.stderrTail.length) : this.stderrTail;+ const masked = this.configured.reduce((text, value) => text.split(value).join("[redacted]"), whole);+ const line = redactSecretsInText(masked).split("\n").map((entry) => entry.trim()).filter(Boolean).at(-1);+ return line ? ` It last said: ${line.slice(0, STDERR_LINE_CHARS)}` : "";+ }+private fail(error: Error): void {if (this.closed) return;this.closed = true;+ this.failure = error.message;for (const entry of this.pending.values()) entry.reject(error);this.pending.clear();void this.close().catch(() => {});@@ -186,9 +218,9 @@ export class ChatMcpClient {if (Buffer.byteLength(this.buffer) > this.frameBytes) this.fail(new Error("MCP response exceeds the frame limit"));}- async call(method: string, params: unknown, signal: AbortSignal, timeout: number, keepOnRefusal = false): Promise<unknown> {+ async call(method: string, params: unknown, signal: AbortSignal, timeout: number, keepOnRefusal = false, timedOut = REQUEST_TIMED_OUT): Promise<unknown> {if (signal.aborted) { await this.close(); throw aborted(); }- if (this.closed) throw new Error("MCP session closed");+ if (this.closed) throw new Error(this.failure ?? "MCP session closed");const id = this.nextId++;try {return await new Promise((resolve, reject) => {@@ -203,7 +235,7 @@ export class ChatMcpClient {catch {}finish(aborted());};- const timer = setTimeout(() => finish(new Error("MCP request timed out; execution outcome may be uncertain")), timeout);+ const timer = setTimeout(() => finish(new Error(timedOut)), timeout);timer.unref();signal.addEventListener("abort", cancel, { once: true });this.pending.set(id, { resolve: (value) => finish(undefined, value), reject: (error) => finish(error) });@@ -219,19 +251,19 @@ export class ChatMcpClient {async tools(signal: AbortSignal, include: (tool: unknown) => boolean = () => true, startupMs = STARTUP_MS, observer?: AppObserver): Promise<unknown[]> {const deadline = Date.now() + startupMs;const remaining = () => {- if (Date.now() >= deadline) throw new Error("MCP startup timed out");+ if (Date.now() >= deadline) throw new Error(STARTUP_TIMED_OUT);return deadline - Date.now();};const handshake = { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "openmausbot-chat", version: "1" } };let initialized: unknown;if (observer?.mount.extension) {- try { initialized = await this.call("initialize", withUiExtension(handshake), signal, remaining(), true); }+ try { initialized = await this.call("initialize", withUiExtension(handshake), signal, remaining(), true, STARTUP_TIMED_OUT); }catch (error) {if (!(error instanceof McpRequestRefused)) throw error;- initialized = await this.call("initialize", handshake, signal, remaining());+ initialized = await this.call("initialize", handshake, signal, remaining(), false, STARTUP_TIMED_OUT);}} else {- initialized = await this.call("initialize", handshake, signal, remaining());+ initialized = await this.call("initialize", handshake, signal, remaining(), false, STARTUP_TIMED_OUT);}if (!object(initialized)) throw new Error("MCP initialization returned an invalid result");observer?.initialized(initialized);@@ -241,7 +273,7 @@ export class ChatMcpClient {const cursors = new Set<string>();let cursor: string | undefined;for (let page = 0; page < MAX_PAGES; page += 1) {- const result = await this.call("tools/list", cursor ? { cursor } : {}, signal, remaining());+ const result = await this.call("tools/list", cursor ? { cursor } : {}, signal, remaining(), false, STARTUP_TIMED_OUT);if (!object(result) || !Array.isArray(result.tools)) throw new Error("MCP tools/list returned an invalid result");observer?.listed(result);tools.push(...result.tools.filter((tool) => modelVisible(tool) && include(tool)));@@ -434,12 +466,9 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]if (integrations?.data && eligible("data")) servers.push(["data", integrations.data]);if (integrations?.email && eligible("email")) servers.push(["email", integrations.email]);if (integrations?.device && eligible("device")) servers.push(["device", integrations.device]);- // Connected apps are optional: their tool catalog is fetched from the connected-apps service while- // mounting, so an unreachable service must not fail the whole turn. A failed mount is skipped like a- // configured server's, which the model is told about. (CLI engines already drop them and go on.)- const optionalBuiltIns = new Set<string>();- if (integrations?.composio) optionalBuiltIns.add("composio");- if (integrations?.composioOwn) optionalBuiltIns.add(OWN_APPS_SERVER);+ // A failed mount of an optional built-in is skipped like a configured server's, which the model is told about, so one+ // dead helper can't fail every later turn. (CLI engines already drop them and go on.)+ const startupMs = mcpStartupMs();const builtIns = servers.length;const besideBrowser = servers.some(([, descriptor]) => descriptor === integrations?.browser);const merged: MergedChatMcpServers[] = [];@@ -595,7 +624,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]const keeps = (tool: unknown) => !computer || !object(tool) || typeof tool.name !== "string" || listsComputerTool(tool.name, besideBrowser);const include = (tool: unknown) => keeps(tool) && (scope === undefined || (object(tool) && typeof tool.name === "string"&& ((searchable.has(name) && isDirectoryTool(tool.name)) || allowsTool(scope, { kind: "mcp", server: name, name: tool.name }))));- const tools = await client.tools(signal, include, searchable.has(name) ? REMOTE_MCP_STARTUP_MS : STARTUP_MS, observers.get(name));+ const tools = await client.tools(signal, include, searchable.has(name) ? REMOTE_MCP_STARTUP_MS : startupMs, observers.get(name));if (!tools.length && scope === undefined && descriptor === integrations?.localComputer) throw new Error("The Local VM listed no tools");// Harness mounts are known by descriptor, never by a name a configured server could claim. A grant// hashes the descriptor (no credential kept); machine bridges mint a bearer per turn, so theirs last a turn.@@ -608,8 +637,8 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]if (signal.aborted || closed) throw aborted();const name = servers[index]![0];if (mount.status === "rejected") {- if (index >= builtIns || optionalBuiltIns.has(name)) { await skip(name, mount.reason, startedAt[index]); continue; }- throw mount.reason;+ if (index >= builtIns || OPTIONAL_BUILT_INS.has(name)) { await skip(name, mount.reason, startedAt[index]); continue; }+ throw new Error(`MCP server "${name}" didn't start: ${mount.reason instanceof Error ? mount.reason.message : "no reason given"}`);}if (index < builtIns) {offeredTools.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) });@@ -668,7 +697,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]};const run = async (tool: RegisteredTool, args: Record<string, unknown>, callSignal: AbortSignal): Promise<ChatToolResult> => {try {- const result = await tool.client.call("tools/call", { name: tool.name, arguments: args }, AbortSignal.any([signal, callSignal]), callTimeoutMs);+ const result = await tool.client.call("tools/call", { name: tool.name, arguments: args }, AbortSignal.any([signal, callSignal]), callTimeoutMs, true);if (signal.aborted || callSignal.aborted) throw aborted();if (!object(result) || !Array.isArray(result.content) || (result.isError !== undefined && typeof result.isError !== "boolean")) throw new Error("MCP tool returned an invalid result; execution outcome may be uncertain");observers.get(tool.server)?.returned({ name: tool.name, arguments: args }, result);@@ -686,8 +715,17 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]return { text: await savedOrBounded(parts.join("\n") || (images.length ? "Screenshot captured." : "(empty result)"), chatToolName(tool.server, tool.name), resultFolder, scrub), ok: result.isError !== true && unsupported === 0,...(images.length ? { images } : {}) };} catch (error) {- await close();- throw new ChatToolSessionError(error instanceof Error ? error.message : "MCP transport failed; execution outcome may be uncertain");+ const reason = error instanceof Error ? error.message : "MCP transport failed; execution outcome may be uncertain";+ if (signal.aborted || callSignal.aborted) {+ await close();+ throw new ChatToolSessionError(reason);+ }+ // The server answered and said no, so it stays. Any other failure ends that server for this turn, so a call whose+ // outcome is uncertain can't run twice on it, and every other server carries on.+ if (error instanceof McpRequestRefused) return { ok: false, text: `${reason} That was the MCP server "${tool.server}".` };+ console.warn(`chat-mcp: MCP server "${tool.server}" stopped for this turn: ${reason}`);+ await tool.client.close().catch(() => {});+ return { ok: false, text: `${reason} That was the MCP server "${tool.server}". It is stopped for the rest of this turn; your other tools still work.` };}};const answer = (result: DirectoryResult): ChatToolResult => ({ text: boundedText(result.content.map((part) => part.text).join("\n")), ok: result.isError !== true });diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.tsindex af64a1bcc0..2487308d8f 100644--- a/server/drivers/openai-compat.test.ts+++ b/server/drivers/openai-compat.test.ts@@ -263,6 +263,30 @@ describe("OpenAICompatDriver", () => {await inst.dispose();}, 20_000);+ it.each([+ ["a network failure", () => { throw new TypeError("fetch failed"); }],+ ["a provider 503", () => new Response("overloaded", { status: 503 })],+ ])("retries %s instead of failing the turn", async (_label, firstAnswer) => {+ const reply = 'data: {"choices":[{"index":0,"delta":{"content":"done"}}]}\n\ndata: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n';+ let completions = 0;+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {+ if (String(input).endsWith("/models")) return new Response(JSON.stringify({ data: [] }), { status: 200 });+ completions += 1;+ return completions === 1 ? firstAnswer() : new Response(reply, { status: 200, headers: { "content-type": "text/event-stream" } });+ }));+ const inst = await OpenAICompatDriver.create({+ instanceId: "compat-retry", displayName: "Compat", enabled: true,+ config: { url: "https://api.example.com/v1", apiKeyEnv: "OPENAI_COMPAT_API_KEY" }, environment: { OPENAI_COMPAT_API_KEY: "secret" },+ });+ const recorder = recordEvents(inst.adapter);+ await inst.adapter.sendTurn({ threadId: "thread", text: "hi", model: "vendor/model" });+ expect(await recorder.until((event) => event.type === "turn.retrying")).toMatchObject({ attempt: 1 });+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: true });+ expect(completions).toBe(2);+ recorder.stop();+ await inst.dispose();+ });+it("exposes a refreshed model catalog", async () => {vi.stubGlobal("fetch",diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex af78e49f24..4bbacb36a5 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -330,6 +330,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {reasoning: true,billing: "metered",includeUsageInCompleted: true,+ retryScale: Number(process.env.FAKE_OPENAI_COMPAT_RETRY_SCALE ?? "1"),nativeLog: {source: "openai-compat.chat.completions",outgoing: (_turn, messages, model, tools) => ({diff --git a/server/engine-memory.test.ts b/server/engine-memory.test.tsindex 580aa0a73b..e476e74091 100644--- a/server/engine-memory.test.ts+++ b/server/engine-memory.test.ts@@ -1,9 +1,12 @@import type { ChildProcess } from "node:child_process";import { EventEmitter } from "node:events";+import { readFileSync, readdirSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import { TurnNotStartedError, type ProviderInstance, type RuntimeEvent, type RuntimeEventListener, type SendTurnInput } from "./contracts.ts";import {- BOT_TURN_GIVES_WAY_MS, BROWSER_BYTES, EngineMemory, memoryStallText, memoryStillWaitingText, memoryStopped, memoryStopText, memoryWaitText, PressureLedger, processGroupBytes, readHostMemory,+ BOT_TURN_GIVES_WAY_MS, BROWSER_BYTES, CHAT_RUNTIME_KINDS, EngineMemory, memoryStallText, memoryStillWaitingText, memoryStopped, memoryStopText, memoryWaitText, PressureLedger, processGroupBytes, readHostMemory,withEngineMemory, type HostMemory,} from "./engine-memory.ts";import { OOM_SCORE, protectSupervisor, spawnBotWork, spawnWithOomScore } from "./oom-score.ts";@@ -611,9 +614,36 @@ describe("an engine's adapter on a Cloud home", () => {expect(seen.slice(2).map((event) => event.type === "runtime.error" ? event.message : event.type)).toEqual([memoryStopText(false), "turn.completed"]);});+ it("makes a chat-runtime turn wait for memory, as its MCP servers need it", async () => {+ const h = host({ available: 300 * MB });+ h.memory.turnStarted("busy"); h.spawn("busy");+ const { instance, sent } = fakeInstance("openai-compat");+ const decorated = withEngineMemory(instance, h.memory);+ const seen: RuntimeEvent[] = [];+ decorated.adapter.onEvent((event) => seen.push(event));+ const turn = decorated.adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput);+ await settle();+ expect(seen).toEqual([expect.objectContaining({ type: "runtime.notice", threadId: "t1", provider: "openai-compat", message: memoryWaitText(1) })]);+ expect(sent).toEqual([]);+ await decorated.adapter.interruptTurn("t1");+ await expect(turn).rejects.toBeInstanceOf(TurnNotStartedError);+ });++ it("gates every engine built on the chat runtime", () => {+ const drivers = join(dirname(fileURLToPath(import.meta.url)), "drivers");+ const kinds = readdirSync(drivers).filter((file) => file.endsWith(".ts") && !file.endsWith(".test.ts")).flatMap((file) => {+ const source = readFileSync(join(drivers, file), "utf8");+ if (!source.includes("createOpenAIChatRuntime(")) return [];+ const kind = /driverKind: "([^"]+)"/.exec(source)?.[1] ?? /DRIVER_KIND = "([^"]+)"/.exec(source)?.[1];+ return kind ? [kind] : [`no kind found in ${file}`];+ });+ expect(kinds.length).toBeGreaterThanOrEqual(8);+ expect(kinds.filter((kind) => !CHAT_RUNTIME_KINDS.has(kind))).toEqual([]);+ });+it("leaves engines that start no process of their own, and every engine where the gate is off, as they are", () => {const h = host();- const api = fakeInstance("openai-compat");+ const api = fakeInstance("some-remote-engine");const adapter = api.instance.adapter;expect(withEngineMemory(api.instance, h.memory).adapter).toBe(adapter);const local = fakeInstance();diff --git a/server/engine-memory.ts b/server/engine-memory.tsindex 31ce577938..eae162b010 100644--- a/server/engine-memory.ts+++ b/server/engine-memory.ts@@ -31,6 +31,9 @@ const MINUTE_MS = 60_000, DAY_MINUTES = 24 * 60;export const ENGINE_PROCESS_KINDS: ReadonlySet<string> = new Set(["claudeAgent", "codex", "opencodeGo", "grokAgent", "geminiAgent", "kimiAgent","droidAgent", "cursorAgent", "qwenAgent", "hermesAgent", "clineAgent", "copilotAgent", "commandCodeAgent", "kiroAgent", "customAcp", "piAgent", "antigravityAgent"]);+/** Chat-runtime engines (openai-chat.ts) have no process of their own, but each turn starts its MCP servers, each a Node process. */+export const CHAT_RUNTIME_KINDS: ReadonlySet<string> = new Set(["openai-compat", "cerebras", "greenference", "grok", "groq", "meta", "minimax", "mistral"]);+export interface HostMemory { totalBytes: number; availableBytes: number; swapFreeBytes: number; oomKills: number | null; fullStall10: number | null }const procText = (path: string) => readFileSync(path, "utf8");@@ -521,7 +524,7 @@ export const engineMemory = new EngineMemory({ enabled: (process.env.OMB_CLOUD_R* for memory fails with that reason. The instance is changed in place: its `models` may be a getter a copy would freeze.*/export function withEngineMemory(instance: ProviderInstance, memory: EngineMemory = engineMemory): ProviderInstance {- if (!memory.enabled || !ENGINE_PROCESS_KINDS.has(instance.driverKind)) return instance;+ if (!memory.enabled || !(ENGINE_PROCESS_KINDS.has(instance.driverKind) || CHAT_RUNTIME_KINDS.has(instance.driverKind))) return instance;const adapter = instance.adapter;const listeners = new Set<RuntimeEventListener>();const waiting = new Map<string, AbortController>();diff --git a/server/testing/setup.ts b/server/testing/setup.tsindex de6141e27b..5bbe59ad97 100644--- a/server/testing/setup.ts+++ b/server/testing/setup.ts@@ -10,6 +10,8 @@ import { removeTempDir } from "./cleanup.ts";const home = mkdtempSync(join(tmpdir(), "omb-test-home-"));process.env.HOME = home;process.env.USERPROFILE = home;+// A provider that answers 5xx retries with backoff: no test should wait out real seconds.+process.env.FAKE_OPENAI_COMPAT_RETRY_SCALE ??= "0.001";// OMB_DATA_DIR must never escape the throwaway home the suite deletes.delete process.env.OMB_DATA_DIR;// Do not let a developer's Hermes global config path leak into per-test homes.