Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Chat engines start without waiting for slow MCP servers
milind-soni9a8359869937
diff --git a/server/drivers/chat-host-computer.test.ts b/server/drivers/chat-host-computer.test.tsindex 1edfcd5ee5..3d01057cf5 100644--- a/server/drivers/chat-host-computer.test.ts+++ b/server/drivers/chat-host-computer.test.ts@@ -3,12 +3,13 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { randomUUID } from "node:crypto";-import { mountChatTools, type ChatToolSession } from "./chat-mcp-tools.ts";+import { joinLateChatTools, mountChatTools, type ChatToolDefinition, type ChatToolSession } from "./chat-mcp-tools.ts";+import type { SendTurnInput } from "../contracts.ts";import { HOST_COMPUTER_READY, HOST_COMPUTER_STAND_IN, hostComputerKey, hostComputerStartupMs } from "./chat-host-computer.ts";const FAKE = `- import { writeFileSync } from "node:fs";- const { MODE, DELAY_MS, ANSWERED } = process.env;+ import { existsSync, writeFileSync } from "node:fs";+ const { MODE, DELAY_MS, ANSWERED, GATE } = process.env;const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");const reply = (message, result) => send({ jsonrpc: "2.0", id: message.id, result });const schema = { type: "object", properties: { value: { type: "string" } }, required: ["value"], additionalProperties: false };@@ -22,10 +23,12 @@ const FAKE = `buffer = buffer.slice(newline + 1);if (MODE === "silent") continue;if (MODE === "exit") process.exit(3);- if (message.method === "initialize") setTimeout(() => {+ const answer = () => setTimeout(() => {writeFileSync(ANSWERED, "1");reply(message, { protocolVersion: "2024-11-05", capabilities: { tools: {} } });}, Number(DELAY_MS ?? 0));+ const opened = () => (!GATE || existsSync(GATE) ? answer() : setTimeout(opened, 10));+ if (message.method === "initialize") opened();else if (message.method === "tools/list") reply(message, { tools: [{ name: "write", description: "Fixture write", inputSchema: schema }] });else if (message.method === "tools/call") reply(message, { content: [{ type: "text", text: "recorded:" + message.params.arguments.value }] });}@@ -154,4 +157,29 @@ describe("this desktop's own computer in a chat turn", () => {expect(() => session.validate("computer_write", { value: "z" })).not.toThrow();await vi.waitFor(() => expect(lines).toEqual([expect.objectContaining({ text: { key: "chat.notice.computerToolsDidNotStart", params: { why: "chat.notice.part.computerToolsTookTooLong" } } })]));});++ it("in a background start, keeps its stand-in while a slower server joins, then lists its own tools beside both", async () => {+ const starting = computer(`background-${randomUUID()}`, { DELAY_MS: "2500" });+ const gate = join(dirs[0]!, `gate-${randomUUID()}`);+ const plain = (env: Record<string, string> = {}) => ({ command: process.execPath, args: [script], env: { ANSWERED: join(dirs[0]!, `answered-${randomUUID()}`), ...env } });+ const ask: ChatToolDefinition = { type: "function", function: { name: "ask_user", description: "Ask", parameters: { type: "object" } } };+ const settled: string[] = [];+ const session = await mountChatTools({ localComputer: starting.server, agents: plain(), custom: { notes: plain({ GATE: gate }) } } as SendTurnInput["integrations"],+ controller.signal, true, undefined, undefined, undefined, undefined, undefined, undefined,+ { startupMs: 1_000, hostComputerMs: 20_000, background: true, onSettled: (server) => settled.push(server) });+ sessions.push(session);+ expect(names(session)).toEqual(["agents_write", HOST_COMPUTER_STAND_IN]);+ expect(settled).not.toContain("notes");+ session.definitions.push(ask);++ writeFileSync(gate, "");+ await vi.waitFor(() => expect(settled).toContain("notes"), { timeout: 10_000, interval: 20 });+ expect(await joinLateChatTools(session, [ask])).toEqual([]);+ expect(names(session)).toEqual(["agents_write", HOST_COMPUTER_STAND_IN, "notes_write", "ask_user"]);++ await expect(session.execute(HOST_COMPUTER_STAND_IN, {}, controller.signal)).resolves.toEqual({ ok: true, text: HOST_COMPUTER_READY });+ expect(names(session)).toEqual(["agents_write", "computer_write", "notes_write", "ask_user"]);+ await expect(session.execute("notes_write", { value: "n" }, controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:n" });+ expect(await joinLateChatTools(session, [ask]), "nothing left to join").toBeUndefined();+ }, 30_000);});diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex 16d9e83852..f3f4c105f4 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -6,7 +6,7 @@ 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 { ChatMcpClient, ChatToolSessionError, SAVED_RESULTS_FOLDER, SAVED_RESULTS_KEPT, chatToolNotices, directServers, mcpStartupMs, mountChatTools, trimmedToolsNotice, type ChatToolSession } from "./chat-mcp-tools.ts";+import { ChatMcpClient, ChatToolSessionError, SAVED_RESULTS_FOLDER, SAVED_RESULTS_KEPT, chatToolNotices, directServers, joinLateChatTools, mcpStartupMs, mountChatTools, trimmedToolsNotice, type ChatToolDefinition, 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";@@ -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)};@@ -1490,3 +1490,134 @@ describe("Chat MCP tool limit, fairly shared", () => {} finally { await remote.close(); }});});++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, toolLimit?: number, onSettled?: (server: string) => void) => {+ const session = await mountChatTools(integrations, signal, false, undefined, undefined, undefined, undefined, undefined, toolLimit, { background: true, ...(onSettled ? { onSettled } : {}) });+ 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, server } = catalogServer(tools, { after });+ dirs.push(dir);+ return { server };+ };+ /** One gate file per server, written once the session has that server's tools (or failure) in hand. */+ const settledGates = (...servers: string[]) => {+ const files = new Map(servers.map((server) => [server, gate()]));+ return { files: [...files.values()], onSettled: (server: string) => { const file = files.get(server); if (file) writeFileSync(file, ""); } };+ };+ /** A server that answers `initialize` only once `file` exists. */+ const startsAfter = (file: string) => `if (message.method === "initialize") { const since = Date.now();+ const up = () => existsSync(${JSON.stringify(file)}) || Date.now() - since > 10_000+ ? reply(message, {protocolVersion:"2024-11-05",capabilities:{tools:{}}}) : setTimeout(up, 10);+ up(); continue; }`;+ /** Joins until a server that was still starting has been taken in. */+ const joined = async (session: ChatToolSession) => {+ let lines: string[] | undefined;+ await vi.waitFor(async () => { lines = await joinLateChatTools(session, [ask]); expect(lines).toBeDefined(); }, { timeout: 10_000, interval: 50 });+ return lines;+ };++ it("starts the turn once the agents server is up, and lists a slow server's tools when it joins", async () => {+ const agents = fixture();+ const slow = fixture(slowStart(1_500));+ const startedAt = Date.now();+ const session = await background({ agents: agents.server, custom: { slow: slow.server } }, agents.controller.signal);+ expect(Date.now() - startedAt).toBeLessThan(1_500);+ session.definitions.push(ask);+ expect(names(session)).toEqual(["agents_write", "ask_user"]);+ expect(await joined(session)).toEqual([]);+ expect(names(session)).toEqual(["agents_write", "slow_write", "ask_user"]);+ await expect(session.execute("slow_write", { value: "late" }, agents.controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:late" });+ expect(await session.join()).toBeUndefined();+ });++ it("says when a server that was still starting is skipped", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const agents = fixture();+ const late = fixture(`if (message.method === "tools/list") { setTimeout(() => reply(message, {tools:"invalid"}), 800); continue; }`);+ const session = await background({ agents: agents.server, custom: { late: late.server } }, agents.controller.signal);+ expect(session.skipped).toEqual([]);+ expect(await joined(session)).toEqual([expect.stringMatching(/^MCP server "late" was skipped for this turn: .*invalid result/)]);+ expect(names(session)).toEqual(["agents_write"]);+ warn.mockRestore();+ });++ it("keeps a listed tool's name when a server joining later would have taken it", async () => {+ const configured = fixture();+ // Up once the session has the configured server's tools, so those are listed from the start; the built-in starts after.+ const gates = settledGates("Data");+ const agents = fixture(startsAfter(gates.files[0]!));+ const go = gate();+ const builtIn = fixture(startsAfter(go));+ const session = await background({ agents: agents.server, data: builtIn.server, custom: { Data: configured.server } }, agents.controller.signal, undefined, gates.onSettled);+ expect(names(session)).toEqual(["agents_write", "data_write"]);+ writeFileSync(go, "");+ await joined(session);+ expect(names(session)).toEqual(["agents_write", "data_write_2", "data_write"]);+ await session.execute("data_write", { value: "same tool" }, agents.controller.signal);+ expect(configured.read().calls.some((call) => call.method === "tools/call")).toBe(true);+ 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 gates = settledGates("notes");+ const agents = catalog(["write"], gates.files);+ // 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, gates.onSettled);+ 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 gates = settledGates("x", "x_a");+ const agents = catalog(["write"], gates.files);+ 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, gates.onSettled);+ 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),+ (f: ReturnType<typeof fixture>) => mountChatTools({ agents: fixture().server, custom: { slow: f.server } }, f.controller.signal).then((session) => { sessions.push(session); return session; }),+ ]) {+ const slow = fixture(slowStart(300));+ const session = await mount(slow);+ expect(names(session)).toContain("slow_write");+ expect(await session.join()).toBeUndefined();+ }+ });+});diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex fe432e7051..af29a769aa 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -56,6 +56,9 @@ export interface ChatToolSession {budget: ToolBudget;/** Lists the turn's tools again within `limit`, after a provider refused that many; started servers keep running. */refit(limit: number): Promise<void>;+ /** With `background`: lists the tools of servers that finished starting since the last call. The lines say which were+ * skipped and what the tool limit did; undefined when none finished. */+ join(): Promise<string[] | undefined>;validate(name: string, args: unknown): void;/** Directory reads and OpenMausBot's own agents server need no card; call_tool shows the tool it runs. */view(name: string, args: Record<string, unknown>): ChatToolCallView;@@ -89,12 +92,16 @@ export function mcpStartupMs(env: Record<string, string | undefined> = process.e}/** `startupMs` replaces both mcpStartupMs budgets, `hostComputerMs` hostComputerStartupMs. `notice` hears, for the person,- * that this computer's tools did not start, worded once per `conversation`. */+ * that this computer's tools did not start, worded once per `conversation`. With `background` and the agents server, setup+ * waits only for the built-ins a turn acts through (agents, a computer, the browser); the rest are listed by `join` once+ * started. `onSettled` hears each server's name once it has listed its tools or failed. */export interface ChatToolMountOptions {startupMs?: number;hostComputerMs?: number;conversation?: string;notice?: (line: { message: string; text: ServerText }) => void;+ background?: boolean;+ onSettled?: (server: string) => void;}const DEFAULT_CALL_MS = 10 * 60_000;const FRAME_BYTES = 2 * 1024 * 1024;@@ -354,11 +361,24 @@ export async function refitChatTools(session: ChatToolSession, error: unknown, kreturn toolLimitNotices(session);}+/** Between rounds, lists the tools of servers that finished starting in the background, the runtime's own `runtime`+ * definitions kept after them. Undefined when none did. */+export async function joinLateChatTools(session: ChatToolSession, runtime: readonly ChatToolDefinition[]): Promise<string[] | undefined> {+ const kept = session.definitions.filter((definition) => runtime.includes(definition));+ const lines = await session.join();+ if (lines !== undefined) session.definitions.push(...kept);+ return lines;+}++function skippedServerNotice({ server, reason }: SkippedChatMcpServer): string {+ return `MCP server "${server}" was skipped for this turn: ${reason}`;+}+/** What the person hears about a turn's MCP servers before the model runs, one line each. */export function chatToolNotices(session: Pick<ChatToolSession, "skipped" | "trimmed" | "budget"> & Partial<Pick<ChatToolSession, "merged">>): string[] {return [...(session.merged ?? []).map(mergedServersNotice),- ...session.skipped.map(({ server, reason }) => `MCP server "${server}" was skipped for this turn: ${reason}`),+ ...session.skipped.map(skippedServerNotice),...toolLimitNotices(session),];}@@ -585,6 +605,12 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]const directoryNames = new Map<string, string>();let directory: ToolDirectory | undefined;const budget: ToolBudget = { limit: toolLimit, listed: 0, servers: [] };+ // A tool keeps the name it was first listed under, so a server that joins later never takes it over; the same for the+ // tool search's own tools and the tools it searches.+ const listedAs = new Map<ChatMcpClient, Map<string, string>>(), searchedAs = new Map<ChatMcpClient, Map<string, string>>();+ const reserved = new Set<string>(), catalogReserved = new Set<string>(), directoryAs = new Map<string, string>();+ const keepName = (names: Map<ChatMcpClient, Map<string, string>>, client: ChatMcpClient, tool: string, name: string) =>+ names.set(client, (names.get(client) ?? new Map<string, string>()).set(tool, name));const register = (origin: ToolOrigin, tools: readonly CheckedTool[]) => {const staged: Array<{ tool: RegisteredTool; definition: ChatToolDefinition }> = [];for (const { tool, schema, check } of tools) {@@ -599,14 +625,16 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]}const description = (typeof listed.description === "string" ? listed.description : "Configured MCP tool") +(Object.keys(constraints).length ? " Additional argument constraints (validated before execution): " + JSON.stringify(constraints) : "");- const name = uniqueName(chatToolName(origin.server, tool.name), (candidate) => registered.has(candidate) || candidate === standIn?.definition.function.name- || staged.some((entry) => entry.definition.function.name === candidate));+ const name = listedAs.get(origin.client)?.get(tool.name) ?? uniqueName(chatToolName(origin.server, tool.name), (candidate) => reserved.has(candidate)+ || registered.has(candidate) || candidate === standIn?.definition.function.name || staged.some((entry) => entry.definition.function.name === candidate));staged.push({ tool: { ...origin, name: tool.name, schema }, definition: { type: "function", function: { name, description, parameters } } });}if (Buffer.byteLength(JSON.stringify([...definitions, ...staged.map((entry) => entry.definition)])) > CATALOG_BYTES) throw new Error("MCP tool catalog exceeds the 1MB limit");for (const { tool, definition } of staged) {registered.set(definition.function.name, tool);definitions.push(definition);+ keepName(listedAs, tool.client, tool.name, definition.function.name);+ reserved.add(definition.function.name);}// Unlisted, so a call by an alias in an earlier tool call reaches the agents server, which runs it as its action// tool; the server holds it to that tool's full schema.@@ -666,7 +694,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));+ keepName(searchedAs, origin.client, tool.name, name);+ catalogReserved.add(name);catalog.set(name, { ...origin, name: tool.name, schema });entries.push({ ...tool, name });}@@ -676,42 +706,26 @@ 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> } });}}budget.listed = definitions.length;};- try {- if (signal.aborted) throw aborted();- // Concurrent starts, consumed in config order so names and collision suffixes stay stable.- const mounts = await Promise.allSettled(servers.map(async ([name, descriptor], index) => {- if (signal.aborted || closed) throw aborted();- const client = new ChatMcpClient(descriptor, computerUse, index >= builtIns);- clients.push(client);- started.set(name, client);- startedAt[index] = client;- const computer = descriptor === integrations?.localComputer;- 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 hostComputer = descriptor === integrations?.localComputer && integrations?.localComputer?.scope === "local-computer";- const host: HostComputerStart | undefined = hostComputer- ? await startHostComputer(hostComputerKey(descriptor), (record) => client.tools(signal, record, hostComputerMs), include, { quickMs: Math.min(startupMs, HOST_COMPUTER_QUICK_MS), firstMs: startupMs }, signal)- : undefined;- const budgetMs = searchable.has(name) ? REMOTE_MCP_STARTUP_MS : index < builtIns ? startupMs : configuredStartupMs;- const tools = host ? (host.state === "listed" || host.state === "pending" ? host.tools : []) : await client.tools(signal, include, budgetMs, observers.get(name));- if (!tools.length && scope === undefined && descriptor === integrations?.localComputer && (!host || host.state === "listed")) 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.- 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, required: index < builtIns && mustHave(descriptor), searched: searchable.has(name), ...(host?.state === "pending" ? { ready: host.ready } : {}) };- return { origin, tools, host };- }));- for (const [index, mount] of mounts.entries()) {+ type Mounted = { origin: ToolOrigin; tools: unknown[]; host: HostComputerStart | undefined };+ const outcomes: Array<PromiseSettledResult<Mounted> | undefined> = [];+ const consumed = new Set<number>();+ /** Takes in, in config order, the servers that finished starting since the last call; true when any did. */+ const absorb = async (): Promise<boolean> => {+ let any = false;+ for (const [index, mount] of outcomes.entries()) {+ if (!mount || consumed.has(index)) continue;if (signal.aborted || closed) throw aborted();+ consumed.add(index);+ any = true;const name = servers[index]![0];if (mount.status === "rejected") {if (index >= builtIns || (OPTIONAL_BUILT_INS.has(name) && !mustHave(servers[index]![1]))) { await skip(name, mount.reason, startedAt[index]); continue; }@@ -737,6 +751,47 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]try { configured.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) }); }catch (error) { await skip(mount.value.origin.server, error, mount.value.origin.client); }}+ return any;+ };+ try {+ if (signal.aborted) throw aborted();+ // Concurrent starts, consumed in config order so names and collision suffixes stay stable.+ const mounts = servers.map(async ([name, descriptor], index): Promise<Mounted> => {+ if (signal.aborted || closed) throw aborted();+ const client = new ChatMcpClient(descriptor, computerUse, index >= builtIns);+ clients.push(client);+ started.set(name, client);+ startedAt[index] = client;+ const computer = descriptor === integrations?.localComputer;+ 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 hostComputer = descriptor === integrations?.localComputer && integrations?.localComputer?.scope === "local-computer";+ const host: HostComputerStart | undefined = hostComputer+ ? await startHostComputer(hostComputerKey(descriptor), (record) => client.tools(signal, record, hostComputerMs), include, { quickMs: Math.min(startupMs, HOST_COMPUTER_QUICK_MS), firstMs: startupMs }, signal)+ : undefined;+ const budgetMs = searchable.has(name) ? REMOTE_MCP_STARTUP_MS : index < builtIns ? startupMs : configuredStartupMs;+ const tools = host ? (host.state === "listed" || host.state === "pending" ? host.tools : []) : await client.tools(signal, include, budgetMs, observers.get(name));+ if (!tools.length && scope === undefined && descriptor === integrations?.localComputer && (!host || host.state === "listed")) 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.+ 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, required: index < builtIns && mustHave(descriptor), searched: searchable.has(name), ...(host?.state === "pending" ? { ready: host.ready } : {}) };+ return { origin, tools, host };+ });+ const settled = mounts.map((mount, index) => mount.then((value) => { outcomes[index] = { status: "fulfilled", value }; },+ (reason: unknown) => { outcomes[index] = { status: "rejected", reason }; }).then(() => options.onSettled?.(servers[index]![0])));+ // Waited for in the background too: what the turn can't run without, the computer and browser a computer-use turn acts+ // through from its first step, and a server sharing its name with another, whose tools' names depend on the order.+ const waited = (index: number) => {+ const [name, descriptor] = servers[index]!;+ return (index < builtIns && (mustHave(descriptor) || !OPTIONAL_BUILT_INS.has(name) || descriptor === integrations?.localComputer || descriptor === integrations?.browser))+ || servers.filter(([other]) => other === name).length > 1;+ };+ const waitAll = !options.background || !servers.some(([, descriptor]) => descriptor === agentsServer);+ await Promise.all(settled.filter((_, index) => waitAll || waited(index)));+ await absorb();await layout(toolLimit);if (signal.aborted || closed) throw aborted();} catch (error) { await close(); throw error; }@@ -858,6 +913,14 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]if (closed || signal.aborted) throw new ChatToolSessionError("MCP session closed");await layout(limit);},+ async join() {+ if (closed || signal.aborted) return undefined;+ const skippedBefore = skipped.length, limitBefore = toolLimitNotices({ trimmed, budget }).join("\n");+ if (!await absorb()) return undefined;+ await layout(budget.limit);+ const limitAfter = toolLimitNotices({ trimmed, budget });+ return [...skipped.slice(skippedBefore).map(skippedServerNotice), ...(limitAfter.join("\n") === limitBefore ? [] : limitAfter)];+ },async execute(name, args, callSignal) {validate(name, args);if (callSignal.aborted) { await close(); throw aborted(); }diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.tsindex 0f2fc674c6..df0bdaa502 100644--- a/server/drivers/openai-chat-tools.test.ts+++ b/server/drivers/openai-chat-tools.test.ts@@ -5,7 +5,7 @@ import { createServer, type ServerResponse } from "node:http";import { tmpdir } from "node:os";import { join } from "node:path";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { ensureDirs, NATIVE_DIR } from "../config.ts";import { BUILT_IN_DATA_SYSTEM_PROMPT } from "../data/instructions.ts";@@ -103,8 +103,31 @@ createInterface({ input: process.stdin }).on("line", async (line) => {});`;+/** What the turn's own tool session has in hand: each server that has listed its tools (or failed) and can be taken in,+ * also written as a file named after the server in `gates` when set. */+const mountSettled = vi.hoisted(() => ({ servers: new Set<string>(), gates: undefined as string | undefined }));+vi.mock("./chat-mcp-tools.ts", async (importOriginal) => {+ const actual = await importOriginal<typeof import("./chat-mcp-tools.ts")>();+ return { ...actual, mountChatTools: (...args: Parameters<typeof actual.mountChatTools>) => {+ const call: Parameters<typeof actual.mountChatTools> = [...args];+ call[9] = { ...call[9], onSettled: (server) => {+ mountSettled.servers.add(server);+ if (mountSettled.gates) writeFileSync(join(mountSettled.gates, server), "");+ } };+ return actual.mountChatTools(...call);+ } };+});+/** Waits until the turn's tool session has `server` in hand; fails if it has not within 30 s. */+async function settledServer(server: string) {+ for (const since = Date.now(); !mountSettled.servers.has(server);) {+ if (Date.now() - since > 30_000) throw new Error(`the turn's tool session never had ${server} in hand`);+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+}const cleanups: Array<() => Promise<void>> = [];afterEach(async () => {+ mountSettled.servers.clear();+ mountSettled.gates = undefined;for (const cleanup of cleanups.splice(0).reverse()) await cleanup();});@@ -1491,18 +1514,67 @@ 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[]) {- const { dir, server } = catalogServer(names);+ function catalog(names: readonly string[], options: Parameters<typeof catalogServer>[1] = {}) {+ const { dir, server } = catalogServer(names, options);cleanups.push(() => removeTempDir(dir));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)),- agents: catalog(syntheticToolNames("agent", agents)),- composio: catalog(syntheticToolNames("router", 7)),- data: catalog(syntheticToolNames("table", 5)),- ...more,+ const integrations = (agents: number, more: SendTurnInput["integrations"] = {}): SendTurnInput["integrations"] => {+ const others = { localComputer: { ...catalog(CUA_DRIVER_WINDOWS_TOOLS), scope: "local-computer" as const }, browser: catalog(syntheticToolNames("agent_browser", 32)),+ composio: catalog(syntheticToolNames("router", 7)), data: catalog(syntheticToolNames("table", 5)), ...more };+ const names = Object.entries(others).flatMap(([key, server]) => key === "localComputer" ? ["computer"] : key === "custom" ? Object.keys(server as object) : [key]);+ // Started once the turn's tool session has every other server in hand, so the ones that start in the background are listed from the first request.+ const gates = mkdtempSync(join(tmpdir(), "omb-chat-tools-settled-"));+ cleanups.push(() => removeTempDir(gates));+ mountSettled.gates = gates;+ return { ...others, agents: catalog(syntheticToolNames("agent", agents), { after: names.map((name) => join(gates, name)) }) };+ };++ 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();+ // The turn has the slow server's tools in hand before the next round.+ await settledServer("notes");+ 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 } } });+ 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 the turn has its tools in hand, before the next round.+ writeFileSync(go, "");+ await settledServer("notes");+ 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 () => {diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 5e47576a78..d7975c4c90 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -14,7 +14,7 @@ import { ASK_USER_TOOL, ASK_USER_TOOL_DEFINITION, askQuestionSummary, parseAskQuimport { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";import { redactSecretsInText } from "../redact.ts";import { toolDetailPreview } from "../tool-summary.ts";-import { ChatToolSessionError, chatToolNotices, mountChatTools, refitChatTools, withHostFileTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";+import { ChatToolSessionError, chatToolNotices, joinLateChatTools, mountChatTools, refitChatTools, withHostFileTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";import { noteToolBudget } from "../tool-budgets.ts";import { chatToolLimitFor, chatToolLimitKey } from "../tool-count-limit.ts";import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent, type ChatContentPart } from "./chat-images.ts";@@ -606,11 +606,10 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const scope = parsed.scope;const toolsOff = options.tools === false || options.toolUse?.(model) === false;tools = await mountChatTools(toolsOff ? undefined : withHostFileTools(turn.integrations), abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,- toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model), { conversation: turn.threadId, notice: ({ message, text }) => emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message), text }) });+ toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model), { background: true, conversation: turn.threadId, notice: ({ message, text }) => emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message), text }) });noteToolBudget(turn.botId, tools.budget);for (const message of chatToolNotices(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });const questionAllowed = !toolsOff && allowsTool(scope, { kind: "native", name: ASK_USER_TOOL });- let optionalQuestionOnly = questionAllowed && tools.definitions.length === 0;// An MCP server squatting ask_user cannot shadow it (dispatch intercepts the name); skip its definition.if (questionAllowed && !tools.definitions.some((definition) => definition.function.name === ASK_USER_TOOL)) {tools.definitions.push(ASK_USER_TOOL_DEFINITION);@@ -623,6 +622,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)messages.push({ role: "user", content: unread.join("\n\n") });deliveredAsides.push(...unread);}+ // Servers still starting join between rounds, never once the tools were dropped (none left while ask_user is allowed).+ 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;@@ -673,9 +675,9 @@ 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]);- if (refit) {+ // Refused for too many tools, nothing ran: learn the limit and list fewer (after a call only when servers just joined).+ const listedBefore = tools.definitions.length, refit = streamed || (seenCalls.size && !joined) || abort.signal.aborted ? undefined : await refitChatTools(tools, error, chatToolLimitKey(options.apiUrl, model), [ASK_USER_TOOL_DEFINITION]);+ if (refit && tools.definitions.length < listedBefore) {for (const message of refit) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });noteToolBudget(turn.botId, tools.budget);emit({ ...base(turn.threadId, turnId), type: "turn.retrying", attempt: 1, delayMs: 0, reason: "tool_limit" });@@ -708,9 +710,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)if (!abort.signal.aborted) throw new ChatProtocolError(refusedToolCallFailure(error, seenCalls.size > 0));}// A structured parameter rejection executed nothing; never downgrade mounted tools or a handled call.- if (optionalQuestionOnly && round === 0 && !streamed && !seenCalls.size && !abort.signal.aborted &&+ if (questionAllowed && round === 0 && tools.definitions.length && tools.definitions.every((definition) => definition === ASK_USER_TOOL_DEFINITION) && !streamed && !seenCalls.size && !abort.signal.aborted &&error instanceof UnsupportedChatToolsError && verdict.reason === "invalid_request") {- optionalQuestionOnly = false;tools.definitions.length = 0;continue;}diff --git a/server/testing/cua-driver-tools.ts b/server/testing/cua-driver-tools.tsindex 518bc61e12..6ce7cb0d9c 100644--- a/server/testing/cua-driver-tools.ts+++ b/server/testing/cua-driver-tools.ts@@ -41,21 +41,35 @@ export function syntheticToolNames(prefix: string, count: number): string[] {}const CATALOG_SERVER = `+import { existsSync } 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 = () => {+ if (after.every((path) => existsSync(path))) setTimeout(resolve, Number(process.env.CATALOG_START_MS ?? 0));+ else if (Date.now() - since > 30_000) {+ process.stderr.write("catalog server: never saw " + after.filter((path) => !existsSync(path)).join(", ") + "\\n");+ process.exit(1);+ } else setTimeout(check, 10);+ };+ check();+});createInterface({ input: process.stdin }).on("line", (line) => {const request = JSON.parse(line);- if (request.method === "initialize") reply(request.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} } });+ 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" } })) });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`. Remove `dir` when done. */-export function catalogServer(names: readonly string[]): { dir: string; server: { command: string; args: string[]; env: Record<string, string> } } {+/** A stdio MCP server, as a turn's integrations take it, that lists exactly `names`. It answers `initialize` once every file+ * in `after` exists, then `startMs` later; if they are not all there within 30 s it exits with an error, so it never+ * starts out of order. Remove `dir` when done. */+export function catalogServer(names: readonly string[], { startMs = 0, after = [] }: { startMs?: number; after?: readonly string[] } = {}): { dir: string; server: { command: string; args: string[]; env: Record<string, string> } } {const dir = mkdtempSync(join(tmpdir(), "omb-catalog-mcp-"));const script = join(dir, "catalog.mjs");writeFileSync(script, CATALOG_SERVER);- return { dir, server: { command: process.execPath, args: [script], env: { CATALOG_TOOLS: JSON.stringify(names) } } };+ return { dir, server: { command: process.execPath, args: [script], env: { CATALOG_TOOLS: JSON.stringify(names), CATALOG_START_MS: String(startMs), CATALOG_AFTER: JSON.stringify(after) } } };}