Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
test(comms): reproduce coordinate_bots dropped on Antigravity resume past the CLI tool limit
luishron123982dc636c1d0
diff --git a/server/comms.test.ts b/server/comms.test.tsindex 2d6792d670..71e94e33f4 100644--- a/server/comms.test.ts+++ b/server/comms.test.ts@@ -207,6 +207,12 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {chmodSync(antigravityCli, 0o755);chmodSync(antigravityHarness, 0o755);}+ // The native Antigravity CLI (agy), as the Shopify bot ran it: its own name in initialize, no harness beside it, and+ // the session's servers by URL. A script, so the fake runs under the name the driver looks for.+ const nativeAgy = join(home, "fake-agy-native", "antigravity");+ mkdirSync(dirname(nativeAgy), { recursive: true });+ writeFileSync(nativeAgy, `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(FAKE_CLI)} "$@"\n`);+ chmodSync(nativeAgy, 0o755);for (const instanceId of ["geminiAsker", "geminiDelegate"]) {const antigravityProfile = join(home, ".openmausbot", "providers", "antigravity", createHash("sha256").update(instanceId).digest("hex"), "antigravity-acp");mkdirSync(antigravityProfile, { recursive: true });@@ -272,8 +278,8 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {},config: { cli: antigravityCli, fullAuto: true },},- // The Antigravity asker that hands work on with coordinate_bots, its process gone after each result's wake, so the- // person's next turn resumes the session in a new one (session/resume), as after a restart.+ // The native Antigravity asker that hands work on with coordinate_bots, its process gone after each result's wake,+ // so the person's next turn resumes the session in a new one (session/resume), as after a restart.geminiDelegate: {driver: "antigravityAgent",environment: {@@ -283,8 +289,13 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {FAKE_ACP_MODES: "default,yolo",FAKE_ACP_EXIT_AFTER_WAKE: "1",FAKE_ACP_RPC_APPEND_FILE: join(home, "gemini-delegate-rpc.jsonl"),+ // Past this the CLI leaves out the session's largest tools, as the native Antigravity CLI does+ // (ANTIGRAVITY_CLI_TOOL_LIMIT, written out so the test reads the same on a build without it).+ FAKE_ACP_CLI_TOOL_LIMIT: "56600",+ FAKE_ACP_AGENT_NAME: "Antigravity ACP Server",+ FAKE_ACP_VERSION: "1.5.18",},- config: { cli: antigravityCli, fullAuto: true },+ config: { cli: nativeAgy, fullAuto: true },},// Hermes shape: keeps the first agents proxy it is offered for the life of the processpoolLister: {@@ -637,15 +648,37 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {async () => {await hideAll();const helper = await named("Helper", { modelSelection: HELPER });- const shop = await named("Shop", { modelSelection: { instanceId: "geminiDelegate", model: "gemini-4-neon" } });- const settled = (count: number) => waitUntil(async () => {- const current = await bot(shop.id);- const woke = current.messages.filter((m: any) => m.kind === "text" && m.role === "bot" && m.text === WOKE_WITH_RESULT).length;- return woke >= count && !current.busy && !(await bot(helper.id)).busy;- }, 45_000, `hand-off ${count} never settled`);+ // The person's own MCP server, as the Shopify bot's connectors were: many small tools whose schemas cannot be made+ // shorter. It starts small, so the first session fits; by the person's next message it lists 150 (as a connector+ // does once more apps are connected), and the resumed session is past the CLI's limit even at its shortest. Left to+ // choose, the CLI leaves out the largest tools, coordinate_bots among them.+ const shopTools = join(home, "shop-mcp-tools.json");+ const listShopTools = (count: number) => writeFileSync(shopTools, JSON.stringify(Array.from({ length: count }, (_, index) => ({+ name: `shop_tool_${index}`,+ description: `Store operation ${index}.`,+ inputSchema: { type: "object", properties: Object.fromEntries(Array.from({ length: 8 }, (_, field) => [`store_record_field_${field}`, { type: "string" }])) },+ }))));+ listShopTools(40);+ const fakeMcp = { command: process.execPath, args: ["--experimental-strip-types", fileURLToPath(new URL("./testing/fake-mcp-server.ts", import.meta.url))] };+ const imported = await api("POST", "/api/mcp/servers/import", { json: JSON.stringify({ mcpServers: { shopmcp: { ...fakeMcp, env: { FAKE_MCP_TOOLS_FILE: shopTools } } } }) });+ expect(imported.status, JSON.stringify(imported.body)).toBe(201);+ expect((await api("PATCH", "/api/mcp/servers/shopmcp", { enabled: true })).status).toBe(200);+ const shop = await named("Shop", { modelSelection: { instanceId: "geminiDelegate", model: "gemini-4-neon" }, mcpServers: ["shopmcp"] });+ const unknownTool = (messages: any[]) => messages.filter((m: any) => m.kind === "text" && /unknown tool/i.test(m.text ?? "")).map((m: any) => m.text);+ // Settled once the hand-off's result has woken Shop, or as soon as a call is refused as an unknown tool (the bug).+ const settled = async (count: number) => {+ await waitUntil(async () => {+ const current = await bot(shop.id);+ if (unknownTool(current.messages).length && !current.busy) return true;+ const woke = current.messages.filter((m: any) => m.kind === "text" && m.role === "bot" && m.text === WOKE_WITH_RESULT).length;+ return woke >= count && !current.busy && !(await bot(helper.id)).busy;+ }, 45_000, `hand-off ${count} never settled`);+ expect(unknownTool((await bot(shop.id)).messages), `coordinate_bots on hand-off ${count}`).toEqual([]);+ };expect((await api("POST", `/api/bots/${shop.id}/messages`, { text: "have @Helper do BRIEF_FIRST" })).status).toBe(202);await settled(1);+ listShopTools(150);// The person switches the conversation's model; the process that answered the wake is gone.expect((await api("PATCH", `/api/bots/${shop.id}`, { modelSelection: { instanceId: "geminiDelegate", model: "gemini-4-pro" } })).status).toBe(200);expect((await api("POST", `/api/bots/${shop.id}/messages`, { text: "now have @Helper do BRIEF_SECOND" })).status).toBe(202);@@ -665,7 +698,6 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {const requestIds = delegated.map((m: any) => /"requestId":"([\w-]+)"/.exec(m.text)?.[1]);expect(requestIds.every(Boolean)).toBe(true);expect(new Set(requestIds).size).toBe(2);- expect(current.messages.some((m: any) => /unknown tool/i.test(m.text ?? ""))).toBe(false);const works = assignments(helper.id, shop.id);expect(works.map((work) => work.id).sort()).toEqual([...requestIds].sort());diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex 9db95ecd65..48b4b699e3 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -81,6 +81,9 @@// (Copilot CLI 1.0.105 does this for auto)// FAKE_ACP_EXIT_ON_MODEL the process exits when set_config_option selects this model// FAKE_ACP_EXIT_AFTER_WAKE=1 the process exits once it has answered a hand-off result's wake turn+// FAKE_ACP_CLI_TOOL_LIMIT=<bytes> as the native Antigravity CLI does (antigravity-cli#1530): on every session/new and+// session/resume, list each server's tools and leave out the largest, whichever server, until the rest+// fit; delegate-peer then refuses a call to a tool left out with `unknown tool: "mcp_<server>_<tool>"`// FAKE_ACP_HANG_ON_MODEL set_config_option never answers a switch to this model, as a stuck account can; other requests// are still answered// FAKE_ACP_VARIANTS JSON map model -> {id?, currentValue?, options} of ACP select values@@ -651,8 +654,38 @@ function holdSessionMcp(): void {}async function listMcpTools(entry: AnyMcpEntry, handshake: unknown, hold = false): Promise<string[]> {- const names = (result: any) => (result?.tools ?? []).map((tool: { name: string; inputSchema?: unknown }) =>+ return (await listMcpToolDefinitions(entry, handshake, hold)).map((tool) =>process.env.FAKE_ACP_MCP_SCHEMA_BYTES === "1" ? `${tool.name}=${JSON.stringify(tool.inputSchema ?? {}).length}` : tool.name);+}++type ListedDefinition = { name: string; description?: string; inputSchema?: unknown };+/** FAKE_ACP_CLI_TOOL_LIMIT: the `<server>/<tool>` names this session's CLI shows the model, settled once the setup's lists are in. */+let cliShown: Promise<Set<string> | null> = Promise.resolve(null);+/** A definition's size as the CLI counts it (tool-schema-profile.ts schemaBytes, copied: this fake imports nothing). */+const cliDefinitionBytes = (tool: ListedDefinition) => {+ const text = JSON.stringify({ name: tool.name, description: tool.description ?? "", parameters: tool.inputSchema ?? { type: "object" } }) ?? "";+ return Buffer.byteLength(text) + 5 * (text.match(/[<>&]/g)?.length ?? 0) + 3 * (text.match(/[\u2028\u2029]/g)?.length ?? 0);+};+function fitSessionToCliLimit(): void {+ const limit = Number(process.env.FAKE_ACP_CLI_TOOL_LIMIT);+ if (!limit) return;+ const servers = sessionMcp;+ cliShown = Promise.all(servers.map(async (entry) => (await listMcpToolDefinitions(entry, GROK_MCP_HANDSHAKE).catch(() => []))+ .map((tool) => ({ key: `${entry.name}/${tool.name}`, bytes: cliDefinitionBytes(tool) })))).then((lists) => {+ const sized = lists.flat().sort((a, b) => b.bytes - a.bytes);+ let total = sized.reduce((sum, tool) => sum + tool.bytes, 0);+ const shown = new Set(sized.map((tool) => tool.key));+ for (const tool of sized) {+ if (total <= limit) break;+ total -= tool.bytes;+ shown.delete(tool.key);+ }+ return shown;+ });+}++async function listMcpToolDefinitions(entry: AnyMcpEntry, handshake: unknown, hold = false): Promise<ListedDefinition[]> {+ const names = (result: any): ListedDefinition[] => result?.tools ?? [];if (typeof entry.url === "string") {const post = await httpMcp(entry, handshake);return names(await post({ id: 2, method: "tools/list", params: {} }));@@ -662,7 +695,7 @@ async function listMcpTools(entry: AnyMcpEntry, handshake: unknown, hold = falsefor (const { name, value } of entry.env ?? []) env[name] = value;const child = spawn(entry.command!, entry.args ?? [], { env, stdio: ["pipe", "pipe", "ignore"] });if (hold) heldMcp.add(child);- const finish = (error: Error | null, tools?: string[]) => { clearTimeout(timer); if (!hold || error) child.kill(); if (error) reject(error); else resolve(tools!); };+ const finish = (error: Error | null, tools?: ListedDefinition[]) => { clearTimeout(timer); if (!hold || error) child.kill(); if (error) reject(error); else resolve(tools!); };const timer = setTimeout(() => finish(new Error("mcp timeout")), 20_000);child.on("error", (error) => finish(error));const write = (frame: object) => child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...frame })}\n`);@@ -1115,6 +1148,7 @@ function handle(msg: any) {agentsMcp = mode === "list-peers" ? agentsMcp ?? offered : offered;sessionMcp = acceptedMcp(servers);holdSessionMcp();+ fitSessionToCliLimit();if (process.env.FAKE_ACP_DUMP) {writeFileSync(`${process.env.FAKE_ACP_DUMP}.mcp.json`, JSON.stringify(servers, null, 2));}@@ -1228,6 +1262,7 @@ function handle(msg: any) {const offered = offeredAgents(msg.params.mcpServers);agentsMcp = mode === "list-peers" ? agentsMcp ?? offered : offered;sessionMcp = acceptedMcp(msg.params.mcpServers);+ fitSessionToCliLimit();}const opts = configOptions();const mdls = sessionModels();@@ -1847,13 +1882,25 @@ function handle(msg: any) {finish();return;}- if (mode === "delegate-peer" && agentsMcp) {+ const agentsUrl = sessionMcp.find((server) => server.name === "agents" && typeof server.url === "string");+ if (mode === "delegate-peer" && (agentsMcp || agentsUrl)) {// A turn whose text names BRIEF_<word> hands on that task, so two of the person's requests are two briefs.const named = [...promptText.matchAll(/\bBRIEF_\w+/g)].at(-1)?.[0];- void driveMcp(agentsMcp, [+ const calls = [{ name: "list_bots", args: () => ({}) },handoffCall(named ? `delegated task ${named}` : "delegated task", { reason: "followup", doneWhen: "the export opens in Numbers" }),- ])+ ];+ const drive = agentsMcp;+ void cliShown.then(async (shown) => {+ // The model can call only what the CLI showed it: a tool left out is unknown, as on the native CLI.+ const missing = shown && calls.map((call) => String(call.name)).find((name) => !shown.has(`agents/${name}`));+ if (missing) throw new Error(`unknown tool: "mcp_agents_${missing}"`);+ if (drive) return driveMcp(drive, calls);+ // The native CLI takes the agents server by URL.+ let last = "";+ for (const call of calls) last = await httpMcpCall(agentsUrl!, String(call.name), call.args(last) as Record<string, unknown>);+ return last;+ }).then((reply) => {out({ jsonrpc: "2.0", method: "session/update", params: { update: { sessionUpdate: "agent_message_chunk", content: { text: `delegated: ${reply}` } } } });complete();