Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(chat): keep tool-search names stable and refit after late joins
AdityaUmaleab163c6e410c
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex bbee914a75..2c8c3baf1e 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -47,7 +47,7 @@ function fixture(body = "", toolSchema: Record<string, unknown> = schema) {const script = join(dir, "fake-mcp.mjs");const receipt = join(dir, "receipt.json");writeFileSync(script, `#!/usr/bin/env node- import { writeFileSync } from "node:fs";+ import { existsSync, readFileSync, writeFileSync } from "node:fs";import { spawn } from "node:child_process";const receipt = process.env.RECEIPT;const schema = ${JSON.stringify(toolSchema)};@@ -1493,12 +1493,23 @@ describe("Chat MCP tool limit, fairly shared", () => {describe("Chat MCP servers starting in the background", () => {const slowStart = (ms: number) => `if (message.method === "initialize") { setTimeout(() => reply(message, {protocolVersion:"2024-11-05",capabilities:{tools:{}}}), ${ms}); continue; }`;const ask: ChatToolDefinition = { type: "function", function: { name: "ask_user", description: "Ask", parameters: { type: "object" } } };- const background = async (integrations: SendTurnInput["integrations"], signal: AbortSignal) => {- const session = await mountChatTools(integrations, signal, false, undefined, undefined, undefined, undefined, undefined, undefined, true);+ const background = async (integrations: SendTurnInput["integrations"], signal: AbortSignal, toolLimit?: number) => {+ const session = await mountChatTools(integrations, signal, false, undefined, undefined, undefined, undefined, undefined, toolLimit, true);sessions.push(session);return session;};const names = (session: ChatToolSession) => session.definitions.map((definition) => definition.function.name);+ /** A file whose path a catalog server waits on: the test writes it once the server may start. */+ const gate = () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-chat-mcp-gate-"));+ dirs.push(dir);+ return join(dir, "go");+ };+ const catalog = (tools: readonly string[], after: readonly string[] = []) => {+ const { dir, ready, server } = catalogServer(tools, { after });+ dirs.push(dir);+ return { ready, server };+ };/** Joins until a server that was still starting has been taken in. */const joined = async (session: ChatToolSession) => {let lines: string[] | undefined;@@ -1532,9 +1543,14 @@ describe("Chat MCP servers starting in the background", () => {});it("keeps a listed tool's name when a server joining later would have taken it", async () => {- const agents = fixture(slowStart(300));- const builtIn = fixture(slowStart(1_000));const configured = fixture();+ // Up once the configured server was asked for its tools, so those are listed from the start.+ const listed = JSON.stringify(configured.receipt);+ const agents = fixture(`if (message.method === "initialize") { const since = Date.now();+ const up = () => (existsSync(${listed}) && readFileSync(${listed}, "utf8").includes("tools/list")) || Date.now() - since > 10_000+ ? reply(message, {protocolVersion:"2024-11-05",capabilities:{tools:{}}}) : setTimeout(up, 10);+ up(); continue; }`);+ const builtIn = fixture(slowStart(1_000));const session = await background({ agents: agents.server, data: builtIn.server, custom: { Data: configured.server } }, agents.controller.signal);expect(names(session)).toEqual(["agents_write", "data_write"]);await joined(session);@@ -1544,6 +1560,43 @@ describe("Chat MCP servers starting in the background", () => {expect(builtIn.read().calls.some((call) => call.method === "tools/call")).toBe(false);});+ it("keeps the tool search's names when a server joining later would have taken them", async () => {+ const notes = catalog(syntheticToolNames("note", 10));+ const agents = catalog(["write"], [notes.ready]);+ // Named like the tool search and offering the tool its call tool is listed as, it joins after the first round.+ const go = gate();+ const late = catalog(["call_tool"], [go]);+ const controller = new AbortController();+ controllers.push(controller);+ const session = await background({ agents: agents.server, custom: { notes: notes.server, mcp: late.server } }, controller.signal, 8);+ expect(names(session)).toEqual(["agents_write", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);+ writeFileSync(go, "");+ await joined(session);+ expect(names(session)).toEqual(["agents_write", "mcp_call_tool_2", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);+ await expect(session.execute("mcp_call_tool", { name: "notes_note_1", arguments: {} }, controller.signal)).resolves.toEqual({ ok: true, text: "ran note_1" });+ });++ it("keeps a searched tool's name when a listed server joins the tool search later", async () => {+ // "x" is listed and "x_a" searched; then "y" joins and takes the room "x" had, so "x" is searched too, before "x_a",+ // and its "a_b" reads as "x_a_b", the name the searched "b" of "x_a" already has.+ const listed = catalog(["a_b", "p_1"]);+ const searched = catalog(["b", ...syntheticToolNames("c", 5)]);+ const agents = catalog(["write"], [listed.ready, searched.ready]);+ const go = gate();+ const late = catalog(["write"], [go]);+ const controller = new AbortController();+ controllers.push(controller);+ const session = await background({ agents: agents.server, custom: { x: listed.server, x_a: searched.server, y: late.server } }, controller.signal, 7);+ expect(names(session)).toEqual(["agents_write", "x_a_b", "x_p_1", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);+ const call = (name: string) => session.execute("mcp_call_tool", { name, arguments: {} }, controller.signal);+ await expect(call("x_a_b")).resolves.toEqual({ ok: true, text: "ran b" });+ writeFileSync(go, "");+ await joined(session);+ expect(names(session)).toEqual(["agents_write", "y_write", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool"]);+ await expect(call("x_a_b")).resolves.toEqual({ ok: true, text: "ran b" });+ await expect(call("x_a_b_2")).resolves.toEqual({ ok: true, text: "ran a_b" });+ });+it("waits for every server without the agents server, or when not started in the background", async () => {for (const mount of [(f: ReturnType<typeof fixture>) => background({ custom: { slow: f.server } }, f.controller.signal),diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex 6f70d72eb3..9aeded7c1e 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -587,6 +587,10 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]// A tool keeps the name it was first listed under, so a server that joins later can't take it over.const assigned = new Map<ChatMcpClient, Map<string, string>>();const reserved = new Set<string>();+ // The same for the tool search: a searched tool and a directory tool keep their names whichever servers are listed.+ const searchedAs = new Map<ChatMcpClient, Map<string, string>>();+ const catalogReserved = new Set<string>();+ const directoryAs = new Map<string, string>();const register = (origin: ToolOrigin, tools: readonly CheckedTool[]) => {const staged: Array<{ tool: RegisteredTool; definition: ChatToolDefinition }> = [];for (const { tool, schema, check } of tools) {@@ -670,7 +674,9 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]const entries: CatalogTool[] = [];for (const { origin, tools } of searched) {for (const { tool, schema } of tools) {- const name = uniqueName(chatToolName(origin.server, tool.name), (candidate) => catalog.has(candidate));+ const name = searchedAs.get(origin.client)?.get(tool.name) ?? uniqueName(chatToolName(origin.server, tool.name), (candidate) => catalogReserved.has(candidate) || catalog.has(candidate));+ searchedAs.set(origin.client, (searchedAs.get(origin.client) ?? new Map<string, string>()).set(tool.name, name));+ catalogReserved.add(name);catalog.set(name, { ...origin, name: tool.name, schema });entries.push({ ...tool, name });}@@ -680,7 +686,9 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]return validate(args) ? undefined : schemaProblems(validate.errors);} });for (const tool of directory.listed({ server: DIRECTORY_SERVER, servers: searched.map(({ origin }) => origin.server) })) {- const name = uniqueName(chatToolName(DIRECTORY_SERVER, tool.name as string), (candidate) => registered.has(candidate) || directoryNames.has(candidate));+ const name = directoryAs.get(tool.name as string) ?? uniqueName(chatToolName(DIRECTORY_SERVER, tool.name as string), (candidate) => reserved.has(candidate) || registered.has(candidate) || directoryNames.has(candidate));+ directoryAs.set(tool.name as string, name);+ reserved.add(name);directoryNames.set(name, tool.name as string);definitions.push({ type: "function", function: { name, description: tool.description as string, parameters: tool.inputSchema as Record<string, unknown> } });}diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.tsindex 568b6bc27e..959fcb6bf9 100644--- a/server/drivers/openai-chat-tools.test.ts+++ b/server/drivers/openai-chat-tools.test.ts@@ -1505,37 +1505,70 @@ describe("a configured MCP server that cannot mount", () => {});describe("a turn with the person's Windows computer, the built-in browser and the agents server", () => {- function catalog(names: readonly string[], startMs = 0) {- const { dir, server } = catalogServer(names, startMs);+ const readyOf = new WeakMap<object, string>();+ function catalog(names: readonly string[], options: Parameters<typeof catalogServer>[1] = {}) {+ const { dir, ready, server } = catalogServer(names, options);cleanups.push(() => removeTempDir(dir));+ readyOf.set(server, ready);return server;}- const integrations = (agents: number, more: SendTurnInput["integrations"] = {}): SendTurnInput["integrations"] => ({- localComputer: { ...catalog(CUA_DRIVER_WINDOWS_TOOLS), scope: "local-computer" },- browser: catalog(syntheticToolNames("agent_browser", 32)),- // Started last, so the servers that start in the background are listed from the first request.- agents: catalog(syntheticToolNames("agent", agents), 1_500),- composio: catalog(syntheticToolNames("router", 7)),- data: catalog(syntheticToolNames("table", 5)),- ...more,- });+ const integrations = (agents: number, more: SendTurnInput["integrations"] = {}): SendTurnInput["integrations"] => {+ const computer = catalog(CUA_DRIVER_WINDOWS_TOOLS);+ const others = { localComputer: { ...computer, scope: "local-computer" as const }, browser: catalog(syntheticToolNames("agent_browser", 32)),+ composio: catalog(syntheticToolNames("router", 7)), data: catalog(syntheticToolNames("table", 5)), ...more };+ const servers = [computer, ...Object.entries(others).flatMap(([key, server]) => key === "custom" ? Object.values(server as object) : [server])];+ // Started once every other server has listed its tools, so the ones that start in the background are listed from the first request.+ const after = servers.flatMap((server) => readyOf.get(server) ?? []);+ return { ...others, agents: catalog(syntheticToolNames("agent", agents), { after }) };+ };it("sends the first request without waiting for a slow server, and lists its tools from the next round", async () => {let firstAt = 0;+ const notes = catalog(["note"], { startMs: 1_500 });const f = await fixture(async (_body, response, round) => {if (round > 1) return answer(response);firstAt = Date.now();- // Long enough for the slow server to have started before the next round.- await new Promise((resolve) => setTimeout(resolve, 2_000));+ // The slow server has started (and listed its tools) before the next round.+ for (const since = Date.now(); !existsSync(readyOf.get(notes)!) && Date.now() - since < 10_000;) await new Promise((resolve) => setTimeout(resolve, 10));sse(response, [chunk({ tool_calls: [toolCall("agents_agent_1", "{}")] }, "tool_calls")]);});const startedAt = Date.now();- await f.start({ integrations: { agents: catalog(syntheticToolNames("agent", 1)), custom: { notes: catalog(["note"], 1_500) } } });+ await f.start({ integrations: { agents: catalog(syntheticToolNames("agent", 1)), custom: { notes } } });expect(await f.completed()).toMatchObject({ ok: true });expect(firstAt - startedAt).toBeLessThan(1_000);expect(f.requests.map((request) => request.tools!.map((tool) => tool.function.name))).toEqual([["agents_agent_1", "ask_user"], ["agents_agent_1", "notes_note", "ask_user"]]);});+ it("lists fewer tools when servers that joined after a tool call go past the provider's limit", async () => {+ const gate = mkdtempSync(join(tmpdir(), "omb-chat-tools-gate-"));+ cleanups.push(() => removeTempDir(gate));+ const go = join(gate, "go");+ const notes = catalog(syntheticToolNames("note", 5), { after: [go] });+ const f = await fixture(async (body, response) => {+ if (!body.messages.some((message) => message.role === "tool")) {+ // The slow server starts, and has listed its tools, before the next round.+ writeFileSync(go, "");+ for (const since = Date.now(); !existsSync(readyOf.get(notes)!) && Date.now() - since < 10_000;) await new Promise((resolve) => setTimeout(resolve, 10));+ return sse(response, [chunk({ tool_calls: [toolCall("agents_agent_1", "{}")] }, "tool_calls")]);+ }+ if ((body.tools?.length ?? 0) <= 6) return answer(response);+ response.writeHead(400, { "content-type": "application/json" });+ response.end(JSON.stringify({ error: { message: `Invalid 'tools': array too long. Expected an array with maximum length 6, but got an array with length ${body.tools!.length} instead.`, type: "invalid_request_error" } }));+ });+ const warn = console.warn;+ console.warn = () => {};+ try {+ await f.start({ integrations: { agents: catalog(syntheticToolNames("agent", 1)), custom: { notes } } });+ expect(await f.completed()).toMatchObject({ ok: true });+ } finally { console.warn = warn; }+ expect(f.requests.map((request) => request.tools!.map((tool) => tool.function.name))).toEqual([+ ["agents_agent_1", "ask_user"],+ ["agents_agent_1", ...syntheticToolNames("notes_note", 5), "ask_user"],+ ["agents_agent_1", "mcp_search_tools", "mcp_describe_tool", "mcp_call_tool", "ask_user"],+ ]);+ expect(f.recorder.events.some((event) => event.type === "runtime.error")).toBe(false);+ });+it("sends at most 128 tools, ask_user and every agents tool among them", async () => {const f = await fixture((_body, response) => answer(response));await f.start({ integrations: integrations(42) });diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 073757cbf1..be11fd0502 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -627,10 +627,10 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)}turnEntry.ending = round === MAX_CHAT_ROUNDS - 1;// Servers still starting when the turn began join once they have, never after the tools were dropped (none left while ask_user is allowed).- if (!questionAllowed || tools.definitions.length) for (const message of await joinLateChatTools(tools, [ASK_USER_TOOL_DEFINITION]) ?? []) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });+ const joined = !questionAllowed || tools.definitions.length ? await joinLateChatTools(tools, [ASK_USER_TOOL_DEFINITION]) : undefined;+ for (const message of joined ?? []) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });native("out", options.nativeLog.outgoing(turn, messages, model, tools.definitions));- let attempt = 0;- let resized = false;+ let attempt = 0, resized = false;let completion: Completion;for (;;) {let streamed = false;@@ -678,8 +678,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)} catch (value) {const error = asError(value);const verdict = classifyError(error);- // A provider refuses a request with too many tools before running anything: learn its limit and list fewer.- const refit = streamed || seenCalls.size || abort.signal.aborted ? undefined : await refitChatTools(tools, error, chatToolLimitKey(options.apiUrl, model), [ASK_USER_TOOL_DEFINITION]);+ // Refused for too many tools, nothing ran: learn the limit and list fewer (after a call only when servers just joined).+ const refit = streamed || (seenCalls.size && !joined) || abort.signal.aborted ? undefined : await refitChatTools(tools, error, chatToolLimitKey(options.apiUrl, model), [ASK_USER_TOOL_DEFINITION]);if (refit) {for (const message of refit) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });noteToolBudget(turn.botId, tools.budget);diff --git a/server/testing/cua-driver-tools.ts b/server/testing/cua-driver-tools.tsindex 579c5c84a8..a84688dbce 100644--- a/server/testing/cua-driver-tools.ts+++ b/server/testing/cua-driver-tools.ts@@ -41,22 +41,32 @@ export function syntheticToolNames(prefix: string, count: number): string[] {}const CATALOG_SERVER = `+import { existsSync, writeFileSync } from "node:fs";import { createInterface } from "node:readline";const names = JSON.parse(process.env.CATALOG_TOOLS);+const after = JSON.parse(process.env.CATALOG_AFTER ?? "[]");const reply = (id, result) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\\n");+const started = (since = Date.now()) => new Promise((resolve) => {+ const check = () => after.every((path) => existsSync(path)) || Date.now() - since > 10_000 ? setTimeout(resolve, Number(process.env.CATALOG_START_MS ?? 0)) : setTimeout(check, 10);+ check();+});createInterface({ input: process.stdin }).on("line", (line) => {const request = JSON.parse(line);- if (request.method === "initialize") setTimeout(() => reply(request.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} } }), Number(process.env.CATALOG_START_MS ?? 0));- else if (request.method === "tools/list") reply(request.id, { tools: names.map((name) => ({ name, description: "Synthetic " + name, inputSchema: { type: "object" } })) });- else if (request.id !== undefined) reply(request.id, { content: [{ type: "text", text: "ran " + request.params?.name }] });+ if (request.method === "initialize") void started().then(() => reply(request.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} } }));+ else if (request.method === "tools/list") {+ reply(request.id, { tools: names.map((name) => ({ name, description: "Synthetic " + name, inputSchema: { type: "object" } })) });+ writeFileSync(process.env.CATALOG_READY, "");+ } else if (request.id !== undefined) reply(request.id, { content: [{ type: "text", text: "ran " + request.params?.name }] });});`;-/** A stdio MCP server, as a turn's integrations take it, that lists exactly `names`, `startMs` after it is asked to start.+/** A stdio MCP server, as a turn's integrations take it, that lists exactly `names`. It starts once every file in `after`+ * exists (another catalog server's `ready`), then `startMs` later, and writes `ready` once it has listed its tools.* Remove `dir` when done. */-export function catalogServer(names: readonly string[], startMs = 0): { dir: string; server: { command: string; args: string[]; env: Record<string, string> } } {+export function catalogServer(names: readonly string[], { startMs = 0, after = [] }: { startMs?: number; after?: readonly string[] } = {}): { dir: string; ready: string; server: { command: string; args: string[]; env: Record<string, string> } } {const dir = mkdtempSync(join(tmpdir(), "omb-catalog-mcp-"));const script = join(dir, "catalog.mjs");+ const ready = join(dir, "ready");writeFileSync(script, CATALOG_SERVER);- return { dir, server: { command: process.execPath, args: [script], env: { CATALOG_TOOLS: JSON.stringify(names), CATALOG_START_MS: String(startMs) } } };+ return { dir, ready, server: { command: process.execPath, args: [script], env: { CATALOG_TOOLS: JSON.stringify(names), CATALOG_START_MS: String(startMs), CATALOG_AFTER: JSON.stringify(after), CATALOG_READY: ready } } };}