Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Revert "Merge pull request #6144 from AdityaUmale/fix/mail-1a1e0db7-chat-mcp-background-start"
milind-sonibef56e0a2bf0
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex 5622371815..f44b396560 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, joinLateChatTools, mcpStartupMs, mountChatTools, trimmedToolsNotice, type ChatToolDefinition, 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";@@ -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 { existsSync, readFileSync, writeFileSync } from "node:fs";+ import { writeFileSync } from "node:fs";import { spawn } from "node:child_process";const receipt = process.env.RECEIPT;const schema = ${JSON.stringify(toolSchema)};@@ -1489,134 +1489,3 @@ 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, true, 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 ae6ec9a82f..d9a7865f8f 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -52,9 +52,6 @@ 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>;- /** Mounted with `background`: lists the turn's tools again with the servers that finished starting since the last call.- * The lines say which were skipped and what the tool limit did; undefined when no server finished starting. */- 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;@@ -341,24 +338,11 @@ export async function refitChatTools(session: ChatToolSession, error: unknown, kreturn toolLimitNotices(session);}-/** Between rounds, lists the tools of the servers that finished starting in the background, the runtime's own `runtime`- * definitions kept after them. The lines say what changed; undefined when nothing 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(skippedServerNotice),+ ...session.skipped.map(({ server, reason }) => `MCP server "${server}" was skipped for this turn: ${reason}`),...toolLimitNotices(session),];}@@ -508,13 +492,9 @@ export function directServers(servers: ReadonlyArray<{ name: string; tools: numb/** Under `schemaProfile` the model reads each tool's schema fitted to its provider; calls are still checked against the full one.* A tool result over 50KB is saved whole in `resultFolder`, the bot's working folder, after `scrub` masks secrets (see savedOrBounded).- * `toolLimit` is the most tools the provider takes in one request, ask_user included; null when it takes any number.- * With `background`, setup waits only for the agents server, a computer and the built-in browser; the rest keep starting- * and are listed by `join` once they have. Without the agents server, setup waits for every one. `onSettled` hears each- * server's name once it has listed its tools or failed, and `join` would take it in. */+ * `toolLimit` is the most tools the provider takes in one request, ask_user included; null when it takes any number. */export async function mountChatTools(integrations: SendTurnInput["integrations"], signal: AbortSignal, computerUse = false, toolScope?: ToolScope, callTimeoutMs: number = DEFAULT_CALL_MS,- schemaProfile?: ToolSchemaProfile, resultFolder?: string, scrub: (text: string) => string = redactSecretsInText, toolLimit: number | null = CHAT_TOOL_LIMIT,- background = false, onSettled?: (server: string) => void): Promise<ChatToolSession> {+ schemaProfile?: ToolSchemaProfile, resultFolder?: string, scrub: (text: string) => string = redactSecretsInText, toolLimit: number | null = CHAT_TOOL_LIMIT): Promise<ChatToolSession> {const parsed = parseToolScope(toolScope);if (!parsed.ok) throw new Error(parsed.error);const scope = parsed.scope;@@ -585,13 +565,6 @@ 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 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) {@@ -606,17 +579,13 @@ 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 = assigned.get(origin.client)?.get(tool.name)- ?? uniqueName(chatToolName(origin.server, tool.name), (candidate) => reserved.has(candidate) || registered.has(candidate) || staged.some((entry) => entry.definition.function.name === candidate));+ const name = uniqueName(chatToolName(origin.server, tool.name), (candidate) => registered.has(candidate) || 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);- const names = assigned.get(tool.client) ?? new Map<string, string>();- assigned.set(tool.client, names.set(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.@@ -675,9 +644,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]const entries: CatalogTool[] = [];for (const { origin, tools } of searched) {for (const { tool, schema } of tools) {- 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);+ const name = uniqueName(chatToolName(origin.server, tool.name), (candidate) => catalog.has(candidate));catalog.set(name, { ...origin, name: tool.name, schema });entries.push({ ...tool, name });}@@ -687,44 +654,17 @@ 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 = 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);+ const name = uniqueName(chatToolName(DIRECTORY_SERVER, tool.name as string), (candidate) => registered.has(candidate) || directoryNames.has(candidate));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;};- type Mounted = { origin: ToolOrigin; tools: Awaited<ReturnType<ChatMcpClient["tools"]>> };- 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; }- 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) });- continue;- }- 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> => {+ 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);@@ -742,20 +682,21 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]const origin: ToolOrigin = { client, server: name, launch, builtInBrowser: descriptor === integrations?.browser, agents: descriptor === agentsServer,hostComputer: descriptor === integrations?.localComputer && integrations?.localComputer?.scope === "local-computer", required: index < builtIns && mustHave(descriptor), searched: searchable.has(name) };return { origin, tools };- });- const settled = mounts.map((mount, index) => mount.then((value) => { outcomes[index] = { status: "fulfilled", value }; },- (reason: unknown) => { outcomes[index] = { status: "rejected", reason }; }).then(() => 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 which- // of the two is listed first.- 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 = !background || !servers.some(([, descriptor]) => descriptor === agentsServer);- await Promise.all(settled.filter((_, index) => waitAll || waited(index)));- await absorb();+ }));+ 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) && !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) {+ offeredTools.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) });+ continue;+ }+ 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); }+ }await layout(toolLimit);if (signal.aborted || closed) throw aborted();} catch (error) { await close(); throw error; }@@ -848,15 +789,6 @@ 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;- const limitBefore = toolLimitNotices({ trimmed, budget });- if (!await absorb()) return undefined;- await layout(budget.limit);- const limitAfter = toolLimitNotices({ trimmed, budget });- return [...skipped.slice(skippedBefore).map(skippedServerNotice), ...(limitAfter.join("\n") === limitBefore.join("\n") ? [] : 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 12f456352d..0f2fc674c6 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, vi } from "vitest";+import { afterEach, describe, expect, it } from "vitest";import { ensureDirs, NATIVE_DIR } from "../config.ts";import { BUILT_IN_DATA_SYSTEM_PROMPT } from "../data/instructions.ts";@@ -103,31 +103,8 @@ 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[10] = (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();});@@ -1514,67 +1491,18 @@ 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[], options: Parameters<typeof catalogServer>[1] = {}) {- const { dir, server } = catalogServer(names, options);+ function catalog(names: readonly string[]) {+ const { dir, server } = catalogServer(names);cleanups.push(() => removeTempDir(dir));return server;}- 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);+ 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,});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 6a374b7731..ec270218a1 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, joinLateChatTools, mountChatTools, refitChatTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";+import { ChatToolSessionError, chatToolNotices, mountChatTools, refitChatTools, 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,10 +606,11 @@ 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 : turn.integrations, abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,- toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model), true);+ toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model));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);@@ -622,11 +623,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)messages.push({ role: "user", content: unread.join("\n\n") });deliveredAsides.push(...unread);}- // Servers still starting when the turn began join once they have, never after 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, resized = false;+ let attempt = 0;+ let resized = false;let completion: Completion;for (;;) {let streamed = false;@@ -674,9 +673,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)} catch (value) {const error = asError(value);const verdict = classifyError(error);- // 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) {+ // 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) {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" });@@ -709,8 +708,9 @@ 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 (questionAllowed && round === 0 && tools.definitions.length && tools.definitions.every((definition) => definition === ASK_USER_TOOL_DEFINITION) && !streamed && !seenCalls.size && !abort.signal.aborted &&+ if (optionalQuestionOnly && round === 0 && !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 6ce7cb0d9c..518bc61e12 100644--- a/server/testing/cua-driver-tools.ts+++ b/server/testing/cua-driver-tools.ts@@ -41,35 +41,21 @@ 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") void started().then(() => reply(request.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} } }));+ if (request.method === "initialize") 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`. 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> } } {+/** 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> } } {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), CATALOG_START_MS: String(startMs), CATALOG_AFTER: JSON.stringify(after) } } };+ return { dir, server: { command: process.execPath, args: [script], env: { CATALOG_TOOLS: JSON.stringify(names) } } };}