Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Train fix: a turn never runs without its Local VM or the agents server
milind-soni147c0a78697d
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex cb649bb08a..9bb9f04b91 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -315,7 +315,7 @@ describe("Chat MCP session", () => {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"],+ ["computer", "hostComputer"],["browser", "browser"],["email", "email"],["device", "device"],@@ -324,7 +324,9 @@ describe("Chat MCP session", () => {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);+ // This desktop's own computer is the optional one; a Local VM is not (below).+ const integrations = key === "hostComputer" ? { localComputer: { ...dead.server, scope: "local-computer" as const } } : { [key]: dead.server };+ const session = await mountChatTools({ ...integrations, 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`);@@ -334,6 +336,40 @@ describe("Chat MCP session", () => {});});+ describe("a server the turn must not run without", () => {+ const broken = `if (message.method === "tools/list") { process.stdout.write('{"result":1}\\n'); continue; }`;+ it("fails setup, naming it, when a Local VM can't start, and leaves no server running", async () => {+ const vm = fixture(broken), other = fixture();+ await expect(mountChatTools({ localComputer: vm.server, data: other.server } as SendTurnInput["integrations"], vm.controller.signal, true))+ .rejects.toThrow(/^MCP server "computer" didn't start: MCP/);+ expect(alive(vm.read().pid)).toBe(false);+ await vi.waitFor(() => expect(alive(other.read().pid)).toBe(false));+ });++ it.each([+ ["a Local VM", "computer", (server: Record<string, unknown>) => ({ localComputer: server })],+ ["the agents server", "agents", (server: Record<string, unknown>) => ({ agents: server })],+ ] as const)("ends the turn's session when %s fails during a call, instead of going on without it", async (_label, name, integrationsOf) => {+ const failing = fixture(`if (message.method === "tools/call") { process.exit(3); }`), other = fixture();+ const session = await mountChatTools({ ...integrationsOf(failing.server), data: other.server } as SendTurnInput["integrations"], failing.controller.signal, true);+ sessions.push(session);+ await expect(session.execute(`${name}_write`, { value: "x" }, failing.controller.signal)).rejects.toBeInstanceOf(ChatToolSessionError);+ expect(() => session.validate("data_write", { value: "y" })).toThrow(ChatToolSessionError);+ await vi.waitFor(() => expect(alive(other.read().pid)).toBe(false));+ });++ it("goes on without this desktop's own computer when it fails during a call", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ try {+ const failing = fixture(`if (message.method === "tools/call") { process.exit(3); }`), other = fixture();+ const session = await mountChatTools({ localComputer: { ...failing.server, scope: "local-computer" }, data: other.server } as SendTurnInput["integrations"], failing.controller.signal, true);+ sessions.push(session);+ await expect(session.execute("computer_write", { value: "x" }, failing.controller.signal)).resolves.toMatchObject({ ok: false });+ await expect(session.execute("data_write", { value: "y" }, failing.controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:y" });+ } 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> = {}) {@@ -536,12 +572,9 @@ describe("Chat MCP session", () => {warn.mockRestore();});- it("goes on without a Local VM that lists no tools, saying so, and doesn't when the owner's selection leaves none", async () => {+ it("fails setup when the Local VM lists no tools, but not when the owner's selection leaves none", async () => {const empty = fixture(`if(message.method === "tools/list") { reply(message,{tools:[]}); continue; }`);- 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(); }+ await expect(empty.mount(true, true)).rejects.toThrow("The Local VM listed no tools");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([]);diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex 7d1cf4a98d..8606cda381 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -58,7 +58,8 @@ export interface ChatToolSession {}type Server = { command: string; args: string[]; env: Record<string, string> };-type RegisteredTool = { client: ChatMcpClient; server: string; launch: string; builtInBrowser: boolean; agents: boolean; hostComputer: boolean; name: string; schema: ValidateFunction; searched: boolean };+/** `required`: a server the turn must not run without (see `mustHave` in mountChatTools). */+type RegisteredTool = { client: ChatMcpClient; server: string; launch: string; builtInBrowser: boolean; agents: boolean; hostComputer: boolean; required: boolean; name: string; schema: ValidateFunction; searched: boolean };function chatToolName(server: string, tool: string): string {return `${server}_${tool}`.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64) || "mcp_tool";}@@ -69,7 +70,8 @@ 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. */+/** Built-ins a turn can go on without, saying so. A turn can't run without the agents server, nor without a Local VM it+ * was given (mountChatTools `mustHave`). */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. */@@ -468,6 +470,10 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]if (integrations?.device && eligible("device")) servers.push(["device", integrations.device]);// 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.)+ // Safety: a turn never runs without the agents server, or without a Local VM it was given (any computer but this+ // desktop's own): without the VM's tools the model would do the work some other way, outside the VM. Such a server that+ // can't start, lists no tools, or fails during the turn ends the turn, as every server did before.+ const mustHave = (descriptor: Server) => descriptor === agentsServer || (descriptor === integrations?.localComputer && integrations?.localComputer?.scope !== "local-computer");const startupMs = mcpStartupMs();const builtIns = servers.length;const besideBrowser = servers.some(([, descriptor]) => descriptor === integrations?.browser);@@ -630,14 +636,14 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]// hashes the descriptor (no credential kept); machine bridges mint a bearer per turn, so theirs last a turn.const launch = createHash("sha256").update(JSON.stringify(descriptor)).digest("hex");const origin: ToolOrigin = { client, server: name, launch, builtInBrowser: descriptor === integrations?.browser, agents: descriptor === agentsServer,- hostComputer: descriptor === integrations?.localComputer && integrations?.localComputer?.scope === "local-computer", searched: searchable.has(name) };+ hostComputer: descriptor === integrations?.localComputer && integrations?.localComputer?.scope === "local-computer", required: index < builtIns && mustHave(descriptor), searched: searchable.has(name) };return { origin, tools };}));for (const [index, mount] of mounts.entries()) {if (signal.aborted || closed) throw aborted();const name = servers[index]![0];if (mount.status === "rejected") {- if (index >= builtIns || OPTIONAL_BUILT_INS.has(name)) { await skip(name, mount.reason, startedAt[index]); continue; }+ if (index >= builtIns || (OPTIONAL_BUILT_INS.has(name) && !mustHave(servers[index]![1]))) { 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) {@@ -716,7 +722,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]...(images.length ? { images } : {}) };} catch (error) {const reason = error instanceof Error ? error.message : "MCP transport failed; execution outcome may be uncertain";- if (signal.aborted || callSignal.aborted) {+ if (signal.aborted || callSignal.aborted || tool.required) {await close();throw new ChatToolSessionError(reason);}