Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Wait in tests on the session's own word that a server's tools are in hand
AdityaUmale867794f954b8
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex 2c8c3baf1e..5622371815 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -1493,8 +1493,8 @@ 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, toolLimit?: number) => {- const session = await mountChatTools(integrations, signal, false, undefined, undefined, undefined, undefined, undefined, toolLimit, true);+ 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;};@@ -1506,10 +1506,20 @@ describe("Chat MCP servers starting in the background", () => {return join(dir, "go");};const catalog = (tools: readonly string[], after: readonly string[] = []) => {- const { dir, ready, server } = catalogServer(tools, { after });+ const { dir, server } = catalogServer(tools, { after });dirs.push(dir);- return { ready, server };+ 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;@@ -1544,15 +1554,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 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);+ // 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);@@ -1562,13 +1571,14 @@ describe("Chat MCP servers starting in the background", () => {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]);+ 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);+ 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);@@ -1581,12 +1591,13 @@ describe("Chat MCP servers starting in the background", () => {// 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 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);+ 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" });diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex 9aeded7c1e..ae6ec9a82f 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -510,10 +510,11 @@ export function directServers(servers: ReadonlyArray<{ name: string; tools: numb* 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. */+ * 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. */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): Promise<ChatToolSession> {+ background = false, onSettled?: (server: string) => void): Promise<ChatToolSession> {const parsed = parseToolScope(toolScope);if (!parsed.ok) throw new Error(parsed.error);const scope = parsed.scope;@@ -743,7 +744,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]return { origin, tools };});const settled = mounts.map((mount, index) => mount.then((value) => { outcomes[index] = { status: "fulfilled", value }; },- (reason: unknown) => { outcomes[index] = { status: "rejected", reason }; }));+ (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.diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.tsindex 959fcb6bf9..c8c90d53fe 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,28 @@ 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, at most 10 s, until the turn's tool session has `server` in hand. */+async function settledServer(server: string) {+ for (const since = Date.now(); !mountSettled.servers.has(server) && Date.now() - since < 10_000;) 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();});@@ -1505,21 +1525,20 @@ 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", () => {- const readyOf = new WeakMap<object, string>();function catalog(names: readonly string[], options: Parameters<typeof catalogServer>[1] = {}) {- const { dir, ready, server } = catalogServer(names, options);+ const { dir, server } = catalogServer(names, options);cleanups.push(() => removeTempDir(dir));- readyOf.set(server, ready);return server;}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)),+ 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 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 }) };+ 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 () => {@@ -1528,8 +1547,8 @@ describe("a turn with the person's Windows computer, the built-in browser and thconst f = await fixture(async (_body, response, round) => {if (round > 1) return answer(response);firstAt = Date.now();- // 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));+ // 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();@@ -1546,9 +1565,9 @@ describe("a turn with the person's Windows computer, the built-in browser and thconst 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.+ // The slow server starts, and the turn has its tools in hand, 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));+ await settledServer("notes");return sse(response, [chunk({ tool_calls: [toolCall("agents_agent_1", "{}")] }, "tool_calls")]);}if ((body.tools?.length ?? 0) <= 6) return answer(response);diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex be11fd0502..a086198c49 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -679,8 +679,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)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 refit = streamed || (seenCalls.size && !joined) || abort.signal.aborted ? undefined : await refitChatTools(tools, error, chatToolLimitKey(options.apiUrl, model), [ASK_USER_TOOL_DEFINITION]);- if (refit) {+ 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" });diff --git a/server/testing/cua-driver-tools.ts b/server/testing/cua-driver-tools.tsindex a84688dbce..3ef35fde51 100644--- a/server/testing/cua-driver-tools.ts+++ b/server/testing/cua-driver-tools.ts@@ -41,7 +41,7 @@ export function syntheticToolNames(prefix: string, count: number): string[] {}const CATALOG_SERVER = `-import { existsSync, writeFileSync } from "node:fs";+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 ?? "[]");@@ -53,20 +53,16 @@ const started = (since = Date.now()) => new Promise((resolve) => {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: {} } }));- 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 }] });+ 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 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, after = [] }: { startMs?: number; after?: readonly string[] } = {}): { dir: string; ready: 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 (at most 10 s), then `startMs` later. 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");- const ready = join(dir, "ready");writeFileSync(script, CATALOG_SERVER);- 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 } } };+ return { dir, server: { command: process.execPath, args: [script], env: { CATALOG_TOOLS: JSON.stringify(names), CATALOG_START_MS: String(startMs), CATALOG_AFTER: JSON.stringify(after) } } };}