Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Windows: the computer tools start reliably instead of being skipped
milind-soni8f845c95ae76
diff --git a/server/chat-notices.ts b/server/chat-notices.tsindex 826523adb0..9a70f5b7b7 100644--- a/server/chat-notices.ts+++ b/server/chat-notices.ts@@ -137,6 +137,7 @@ export const CHAT_NOTICE = {"chat.notice.computerDesktopOnly": "Only the OpenMausBot app on this computer can let a bot use it. Open the app here, or let the bot work in its own browser or on a cloud desktop instead.","chat.notice.computerPermissionsThenRestart": "OpenMausBot can't use this computer yet — make sure OpenMausBot has the permissions it asks for, then restart it","chat.notice.computerNotReadyDetail": "OpenMausBot can't use this computer yet — {reason}",+ "chat.notice.computerToolsDidNotStart": "The tools for this computer did not start this time ({reason}). It is still linked to this bot; send your message again in a moment.","chat.notice.computerNotReadyMacPermission": "OpenMausBot can't use this computer yet — {reason}. Relaunch OpenMausBot after granting the missing macOS permission.","chat.notice.computerSystemUnsupported": "bots can't use this computer on this system — choose another place for this bot to work","chat.notice.computerAiUnsupported": "this bot's AI can't use this computer — pick another AI for this bot, or choose another place for it to work",diff --git a/server/drivers/chat-host-computer.test.ts b/server/drivers/chat-host-computer.test.tsnew file mode 100644index 0000000000..8e1e6d1dfc--- /dev/null+++ b/server/drivers/chat-host-computer.test.ts@@ -0,0 +1,138 @@+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+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 { chatToolNoticeLines, mountChatTools, type ChatToolSession } from "./chat-mcp-tools.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;+ 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 };+ let buffer = "";+ process.stdin.setEncoding("utf8");+ process.stdin.on("data", (chunk) => {+ buffer += chunk;+ let newline;+ while ((newline = buffer.indexOf("\\n")) !== -1) {+ const message = JSON.parse(buffer.slice(0, newline));+ buffer = buffer.slice(newline + 1);+ if (MODE === "silent") continue;+ if (message.method === "initialize") setTimeout(() => {+ writeFileSync(ANSWERED, "1");+ reply(message, { protocolVersion: "2024-11-05", capabilities: { tools: {} } });+ }, Number(DELAY_MS ?? 0));+ 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 }] });+ }+ });+`;++const dirs: string[] = [];+const sessions: ChatToolSession[] = [];+const controller = new AbortController();+let script = "";++beforeEach(() => {+ const dir = mkdtempSync(join(tmpdir(), "omb-host-computer-"));+ dirs.push(dir);+ script = join(dir, "fake-computer.mjs");+ writeFileSync(script, FAKE);+ vi.spyOn(console, "warn").mockImplementation(() => {});+});++afterEach(async () => {+ vi.restoreAllMocks();+ await Promise.all(sessions.splice(0).map((session) => session.close().catch(() => {})));+ for (const dir of dirs.splice(0)) rmSync(dir, { force: true, recursive: true });+});++/** This desktop's computer as the gate hands it over: the driver it reaches is `driver`, the turn's capability its own. */+function computer(driver: string, env: Record<string, string> = {}) {+ const answered = join(dirs[0]!, `answered-${randomUUID()}`);+ return {+ answered,+ server: {+ command: process.execPath, args: [script], scope: "local-computer" as const, platform: "win32" as const,+ env: { OMB_CUA_COMMAND: driver, OMB_CUA_ARGS: '["mcp"]', OMB_CUA_PLATFORM: "win32", OMB_CONTROL_TOKEN: randomUUID(), ANSWERED: answered, ...env },+ },+ };+}++async function mount(server: ReturnType<typeof computer>["server"], startup: { ms: number; hostComputerMs: number }) {+ const session = await mountChatTools({ localComputer: server }, controller.signal, true, undefined, undefined, undefined, undefined, undefined, undefined, startup);+ sessions.push(session);+ return session;+}++const names = (session: ChatToolSession) => session.definitions.map((definition) => definition.function.name);++describe("this desktop's own computer in a chat turn", () => {+ it("gets longer to start on Windows, and its tools are shared by every turn on the same driver", () => {+ expect(hostComputerStartupMs("win32")).toBe(45_000);+ expect(hostComputerStartupMs("darwin")).toBe(20_000);+ expect(hostComputerStartupMs("linux")).toBe(20_000);+ const one = computer("C:\\cua-driver.exe").server, two = computer("C:\\cua-driver.exe").server;+ expect(one.env.OMB_CONTROL_TOKEN).not.toBe(two.env.OMB_CONTROL_TOKEN);+ expect(hostComputerKey(one)).toBe(hostComputerKey(two));+ expect(hostComputerKey(one)).not.toBe(hostComputerKey({ ...one, env: { ...one.env, OMB_CUA_ARGS: '["mcp","--embedded"]' } }));+ });++ it("is not skipped when it starts slower than the turn's budget, and the next turn lists it at once and waits at its first call", async () => {+ const driver = `slow-${randomUUID()}`;+ const first = computer(driver, { DELAY_MS: "1500" });+ const cold = await mount(first.server, { ms: 150, hostComputerMs: 20_000 });+ expect(cold.skipped).toEqual([]);+ expect(names(cold)).toEqual(["computer_write"]);++ const second = computer(driver, { DELAY_MS: "1500" });+ const warm = await mount(second.server, { ms: 150, hostComputerMs: 20_000 });+ expect(existsSync(second.answered)).toBe(false);+ expect(warm.skipped).toEqual([]);+ expect(names(warm)).toEqual(["computer_write"]);+ await expect(warm.execute("computer_write", { value: "x" }, controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:x" });+ expect(existsSync(second.answered)).toBe(true);+ });++ it("says through a tool, never by leaving it out, that it did not start, and tells the person", async () => {+ const session = await mount(computer(`dead-${randomUUID()}`, { MODE: "silent" }).server, { ms: 150, hostComputerMs: 400 });+ expect(session.skipped).toEqual([]);+ expect(names(session)).toEqual([HOST_COMPUTER_STAND_IN]);+ expect(session.definitions[0]!.function.description).toContain("did not start this time (MCP startup timed out)");+ expect(session.view(HOST_COMPUTER_STAND_IN, {})).toMatchObject({ ask: false });+ const result = await session.execute(HOST_COMPUTER_STAND_IN, {}, controller.signal);+ expect(result.ok).toBe(false);+ expect(result.text).toContain("nothing needs linking or connecting");+ expect(chatToolNoticeLines(session)).toEqual([expect.objectContaining({ text: { key: "chat.notice.computerToolsDidNotStart", params: { reason: "MCP startup timed out" } } })]);+ });++ it("after a failed start, waits for the next one through the stand-in and then lists the real tools beside the runtime's own", async () => {+ const driver = `flaky-${randomUUID()}`;+ await mount(computer(driver, { MODE: "silent" }).server, { ms: 150, hostComputerMs: 400 });+ const starting = computer(driver, { DELAY_MS: "1200" });+ const session = await mount(starting.server, { ms: 150, hostComputerMs: 20_000 });+ expect(existsSync(starting.answered)).toBe(false);+ expect(names(session)).toEqual([HOST_COMPUTER_STAND_IN]);+ expect(session.definitions[0]!.function.description).toContain("still starting");+ expect(session.hostComputerFailure).toBeUndefined();+ const runtime = { type: "function" as const, function: { name: "ask_user", description: "Ask", parameters: { type: "object" } } };+ session.definitions.push(runtime);++ await expect(session.execute(HOST_COMPUTER_STAND_IN, {}, controller.signal)).resolves.toEqual({ ok: true, text: HOST_COMPUTER_READY });+ expect(names(session)).toEqual(["computer_write", "ask_user"]);+ await expect(session.execute("computer_write", { value: "y" }, controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:y" });+ });++ it("answers a call on the last start's tools with why this start failed, and the turn goes on", async () => {+ const driver = `lost-${randomUUID()}`;+ await mount(computer(driver).server, { ms: 5_000, hostComputerMs: 20_000 });+ const session = await mount(computer(driver, { MODE: "silent" }).server, { ms: 150, hostComputerMs: 600 });+ expect(names(session)).toEqual(["computer_write"]);+ const result = await session.execute("computer_write", { value: "z" }, controller.signal);+ expect(result).toMatchObject({ ok: false, text: expect.stringContaining("did not start this time (MCP startup timed out)") });+ expect(() => session.validate("computer_write", { value: "z" })).not.toThrow();+ });+});diff --git a/server/drivers/chat-host-computer.ts b/server/drivers/chat-host-computer.tsnew file mode 100644index 0000000000..90bf074ef6--- /dev/null+++ b/server/drivers/chat-host-computer.ts@@ -0,0 +1,95 @@+// This desktop's own computer for the Chat Completions runtime: its tools are listed even when its helper is slow to+// start, and a turn whose helper did not start says so through a tool instead of having no computer tools.+import { noticeFailure } from "../chat-notices.ts";++const HOST_COMPUTER_STARTUP_MS = 20_000;+/** Windows: each turn starts the gate proxy as Electron and cua-driver.exe behind it, beside every other built-in;+ * a cold start there (Defender scanning both executables on a busy disk) runs well past the general budget. */+const WINDOWS_HOST_COMPUTER_STARTUP_MS = 45_000;++/** How long this computer's helper gets to start; past the turn's own budget it starts in the background. */+export function hostComputerStartupMs(platform: NodeJS.Platform = process.platform): number {+ return platform === "win32" ? WINDOWS_HOST_COMPUTER_STARTUP_MS : HOST_COMPUTER_STARTUP_MS;+}++/** Tool name, under the "computer" server, the model sees while the computer's real tools are not listed. */+export const HOST_COMPUTER_STAND_IN = "computer_tools_status";++type Server = { command: string; args: string[]; env: Record<string, string> };++/** The driver behind the turn's gate, never the turn's own capability, so every turn on the same driver shares it. */+export function hostComputerKey(server: Server): string {+ const { OMB_CUA_COMMAND, OMB_CUA_ARGS, OMB_CUA_PLATFORM } = server.env;+ return JSON.stringify(OMB_CUA_COMMAND === undefined ? [server.command, server.args] : [OMB_CUA_COMMAND, OMB_CUA_ARGS ?? "", OMB_CUA_PLATFORM ?? ""]);+}++const lastListed = new Map<string, unknown[]>();+const lastFailed = new Set<string>();++export type HostComputerStart =+ | { state: "listed"; tools: unknown[] }+ /** Slow this turn: its last start's tools are listed, and a call waits for `ready`. */+ | { state: "pending"; tools: unknown[]; ready: Promise<void> }+ /** Slow with no earlier list to show: the stand-in waits for `ready`. */+ | { state: "starting"; ready: Promise<unknown[]> }+ | { state: "failed"; reason: string };++function reasonOf(error: unknown): string {+ return error instanceof Error && error.message ? error.message : "its helper did not start";+}++/** Waits for the listing up to `turnMs` once this driver has listed or failed before; on its first start, for the+ * whole listing, which `list` bounds by hostComputerStartupMs. */+export async function startHostComputer(key: string, list: (include: (tool: unknown) => boolean) => Promise<unknown[]>,+ include: (tool: unknown) => boolean, turnMs: number, signal: AbortSignal): Promise<HostComputerStart> {+ const seen: unknown[] = [];+ const listing = list((tool) => { seen.push(tool); return include(tool); }).then((tools) => {+ lastListed.set(key, seen);+ lastFailed.delete(key);+ return tools;+ }, (error: unknown) => {+ if (!signal.aborted) lastFailed.add(key);+ throw error;+ });+ listing.catch(() => {});+ const cached = lastListed.get(key);+ let timer: ReturnType<typeof setTimeout> | undefined;+ const late = cached || lastFailed.has(key) ? new Promise<undefined>((resolve) => { timer = setTimeout(resolve, turnMs, undefined); }) : new Promise<undefined>(() => {});+ const outcome = await Promise.race([listing.then((tools) => ({ tools }), (error: unknown) => ({ error })), late]);+ clearTimeout(timer);+ if (outcome && "tools" in outcome) return { state: "listed", tools: outcome.tools };+ if (outcome) return { state: "failed", reason: reasonOf(outcome.error) };+ console.warn("chat-mcp: this computer's tools are still starting; the turn goes on and its first computer call waits for them");+ if (cached) return { state: "pending", tools: cached.filter(include), ready: listing.then(() => undefined) };+ return { state: "starting", ready: listing };+}++/** The cause, waiting for `ready` unless the turn or the call is stopped first; undefined once it has started. */+export function hostComputerFailure(ready: Promise<unknown>, signal: AbortSignal): Promise<string | undefined> {+ return new Promise((resolve, reject) => {+ if (signal.aborted) return reject(new Error("MCP operation cancelled"));+ const stop = () => reject(new Error("MCP operation cancelled"));+ signal.addEventListener("abort", stop, { once: true });+ ready.then(() => resolve(undefined), (error: unknown) => resolve(reasonOf(error))).finally(() => signal.removeEventListener("abort", stop));+ });+}++const NEVER_LINK = "This computer is already linked to you; nothing needs linking or connecting, so never ask the person to link it.";++export function hostComputerDidNotStart(reason: string): string {+ return `The tools for this computer did not start this time (${reason}). ${NEVER_LINK} Tell the person they did not start and to send the message again in a moment.`;+}++export const HOST_COMPUTER_READY = "The tools for this computer are ready and listed for your next step.";++export function hostComputerStandIn(reason?: string) {+ const description = reason === undefined+ ? `The tools for this computer (the person's own computer) are still starting. Call this before any step on this computer: it waits for them, then lists them for your next step. ${NEVER_LINK}`+ : `${hostComputerDidNotStart(reason)} Call this for the same answer.`;+ return { type: "function" as const, function: { name: HOST_COMPUTER_STAND_IN, description, parameters: { type: "object", properties: {}, additionalProperties: false } } };+}++/** For the person: their computer's tools did not start at the start of this turn. */+export function hostComputerNotice(reason: string | undefined) {+ return reason === undefined ? undefined : noticeFailure("chat.notice.computerToolsDidNotStart", { reason });+}diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex f44b396560..ed0cbaea4f 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -333,7 +333,6 @@ describe("Chat MCP session", () => {describe("a built-in the turn can go on without", () => {const broken = `if (message.method === "tools/list") { process.stdout.write('{"result":1}\\n'); continue; }`;it.each([- ["computer", "hostComputer"],["browser", "browser"],["email", "email"],["device", "device"],@@ -342,9 +341,7 @@ describe("Chat MCP session", () => {const warn = vi.spyOn(console, "warn").mockImplementation(() => {});try {const dead = fixture(broken), agents = fixture();- // This desktop's own computer is the optional one; a Local VM is not (below).- const integrations = key === "hostComputer" ? { localComputer: { ...dead.server, scope: "local-computer" as const } } : { [key]: dead.server };- const session = await mountChatTools({ ...integrations, agents: agents.server } as SendTurnInput["integrations"], dead.controller.signal, true);+ const session = await mountChatTools({ [key]: dead.server, agents: agents.server } as SendTurnInput["integrations"], dead.controller.signal, true);sessions.push(session);expect(session.skipped).toEqual([{ server, reason: expect.stringMatching(/MCP/) }]);expect(chatToolNotices(session).join(" ")).toContain(`MCP server "${server}" was skipped for this turn`);@@ -451,10 +448,12 @@ describe("Chat MCP session", () => {});describe("how long a server gets to start", () => {- it("is about half a minute on a Cloud home and eight seconds elsewhere", () => {- expect(mcpStartupMs({ OMB_CLOUD_ROLE: "home" })).toBe(30_000);- expect(mcpStartupMs({ OMB_CLOUD_ROLE: "team" })).toBe(30_000);- expect(mcpStartupMs({})).toBe(8_000);+ it("is about half a minute on a Cloud home, twenty seconds on Windows and eight seconds elsewhere", () => {+ expect(mcpStartupMs({ OMB_CLOUD_ROLE: "home" }, "win32")).toBe(30_000);+ expect(mcpStartupMs({ OMB_CLOUD_ROLE: "team" }, "linux")).toBe(30_000);+ expect(mcpStartupMs({}, "win32")).toBe(20_000);+ expect(mcpStartupMs({}, "darwin")).toBe(8_000);+ expect(mcpStartupMs({}, "linux")).toBe(8_000);});// tools/list needs a budget that outlasts the child's own start, or the overrun would land in initialize.@@ -1142,17 +1141,18 @@ describe("Chat MCP startup budgets", () => {}});- it("still gives a command server 8 seconds", async () => {+ it("still gives a command server its own budget: 8 seconds, or 20 on Windows", async () => {vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });try {const f = fixture(`if (message.method === "tools/list") return;`);const mounting = watch(f.mount());const listed = () => { try { return f.read().calls.some((call) => call.method === "tools/list"); } catch { return false; } };await untilReal(listed);- await vi.advanceTimersByTimeAsync(7_900);+ // The deadline runs on the real clock from the spawn, so a loaded runner has already spent some of it.+ await vi.advanceTimersByTimeAsync(mcpStartupMs() - 3_000);expect(mounting.done).toBe(false);- await vi.advanceTimersByTimeAsync(200);- // stopped at 8 seconds: well short of the 30 a URL server gets+ await vi.advanceTimersByTimeAsync(3_100);+ // stopped at its budget: short of the 30 seconds a URL server getsawait settleWithin(1_000, () => mounting.done);expect(mounting.error).toBeUndefined();expect(mounting.value?.skipped).toEqual([{ server: "audit", reason: expect.stringMatching(/timed out/) }]);diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex d9a7865f8f..585c2b2dcc 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -22,9 +22,12 @@ import { REMOTE_MCP_STARTUP_MS, remoteMcpSpec } from "../mcp-http.ts";import { compileToolSchema, schemaProblems, serverToolValidator, type ServerToolCheck } from "../mcp-schema-validator.ts";import { fitToolList, withoutDanglingReferences } from "../mcp-tool-schema.ts";import { listsComputerTool } from "../computer-tool-list.ts";+import { HOST_COMPUTER_READY, hostComputerDidNotStart, hostComputerFailure, hostComputerKey, hostComputerNotice, hostComputerStandIn, hostComputerStartupMs, startHostComputer,+ type HostComputerStart } from "./chat-host-computer.ts";import { READ_OPEN_PAGE_ONLY, readsAroundBrowser } from "../browser-tool-shape.ts";import { capToolList, learnToolCountLimit, shareToolBudget, toolCountLimitFromError } from "../tool-count-limit.ts";import type { ToolSchemaProfile } from "../tool-schema-profile.ts";+import type { ServerText } from "../../shared/server-text.ts";import { allowsTool, canUseMcpServer, parseToolScope, type ToolScope } from "../../shared/tool-scope.ts";import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";import { CHAT_TOOL_LIMIT, type ToolBudget } from "../../shared/tool-budget.ts";@@ -50,6 +53,8 @@ export interface ChatToolSession {trimmed: TrimmedChatMcpServer[];merged: MergedChatMcpServers[];budget: ToolBudget;+ /** Why this desktop's own computer did not start for this turn; its tools are then reached through a stand-in. */+ hostComputerFailure?: string;/** Lists the turn's tools again within `limit`, after a provider refused that many; started servers keep running. */refit(limit: number): Promise<void>;validate(name: string, args: unknown): void;@@ -61,13 +66,16 @@ export interface ChatToolSession {type Server = { command: string; args: string[]; env: Record<string, string> };/** `required`: a server the turn must not run without (see `mustHave` in mountChatTools). */-type RegisteredTool = { client: ChatMcpClient; server: string; launch: string; builtInBrowser: boolean; agents: boolean; hostComputer: boolean; required: boolean; name: string; schema: ValidateFunction; searched: boolean };+type RegisteredTool = { client: ChatMcpClient; server: string; launch: string; builtInBrowser: boolean; agents: boolean; hostComputer: boolean; required: boolean; name: string; schema: ValidateFunction; searched: boolean;+ /** Listed from this computer's last start while this one finishes: a call waits for it. */ ready?: Promise<void> };function chatToolName(server: string, tool: string): string {return `${server}_${tool}`.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64) || "mcp_tool";}const STARTUP_MS = 8_000;/** A small Cloud home that is busy can take this long to load Node and a server's own imports. */const CLOUD_STARTUP_MS = 30_000;+/** Windows starts each built-in as its own Electron process, all at once, and scans each new executable first. */+const WINDOWS_STARTUP_MS = 20_000;const STARTUP_TIMED_OUT = "MCP startup timed out";const REQUEST_TIMED_OUT = "MCP request timed out; execution outcome may be uncertain";/** How much of a server's stderr is kept, and how much of its last line is ever shown. */@@ -77,8 +85,8 @@ const STDERR_TAIL_CHARS = 4_000, STDERR_LINE_CHARS = 300;const OPTIONAL_BUILT_INS: ReadonlySet<string> = new Set(["computer", "browser", "composio", OWN_APPS_SERVER, "data", "email", "device"]);/** How long a server that runs a command gets to start here. */-export function mcpStartupMs(env: Record<string, string | undefined> = process.env): number {- return cloudRole(env) ? CLOUD_STARTUP_MS : STARTUP_MS;+export function mcpStartupMs(env: Record<string, string | undefined> = process.env, platform: NodeJS.Platform = process.platform): number {+ return cloudRole(env) ? CLOUD_STARTUP_MS : platform === "win32" ? WINDOWS_STARTUP_MS : STARTUP_MS;}const DEFAULT_CALL_MS = 10 * 60_000;const FRAME_BYTES = 2 * 1024 * 1024;@@ -347,6 +355,12 @@ export function chatToolNotices(session: Pick<ChatToolSession, "skipped" | "trim];}+/** chatToolNotices, then this computer's own line, worded for the person's language. */+export function chatToolNoticeLines(session: ChatToolSession): Array<{ message: string; text?: ServerText }> {+ const computer = hostComputerNotice(session.hostComputerFailure);+ return [...chatToolNotices(session).map((message) => ({ message })), ...(computer ? [computer] : [])];+}+function preview(bytes: Buffer): string {let end = OUTPUT_BYTES;while ((bytes[end] & 0xc0) === 0x80) end -= 1;@@ -492,9 +506,11 @@ 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. */+ * `toolLimit` is the most tools the provider takes in one request, ask_user included; null when it takes any number.+ * `startup` replaces the start budgets of mcpStartupMs and hostComputerStartupMs. */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): Promise<ChatToolSession> {+ schemaProfile?: ToolSchemaProfile, resultFolder?: string, scrub: (text: string) => string = redactSecretsInText, toolLimit: number | null = CHAT_TOOL_LIMIT,+ startup: { ms?: number; hostComputerMs?: number } = {}): Promise<ChatToolSession> {const parsed = parseToolScope(toolScope);if (!parsed.ok) throw new Error(parsed.error);const scope = parsed.scope;@@ -518,7 +534,10 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]// desktop's own): without the VM's tools the model would do the work some other way, outside the VM. Such a server that// can't start, lists no tools, or fails during the turn ends the turn, as every server did before.const mustHave = (descriptor: Server) => descriptor === agentsServer || (descriptor === integrations?.localComputer && integrations?.localComputer?.scope !== "local-computer");- const startupMs = mcpStartupMs();+ const startupMs = startup.ms ?? mcpStartupMs();+ const hostComputerMs = Math.max(startupMs, startup.hostComputerMs ?? hostComputerStartupMs());+ let standIn: { definition: ChatToolDefinition; origin: ToolOrigin; ready?: Promise<unknown[]>; reason?: string } | undefined;+ let hostComputerFailed: string | undefined;const builtIns = servers.length;const besideBrowser = servers.some(([, descriptor]) => descriptor === integrations?.browser);const merged: MergedChatMcpServers[] = [];@@ -579,7 +598,8 @@ 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) || staged.some((entry) => entry.definition.function.name === candidate));+ 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));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");@@ -615,7 +635,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]directory = undefined;trimmed.length = 0;Object.assign(budget, { limit, listed: 0, servers: [] });- const room = limit === null ? Infinity : Math.max(0, limit - RUNTIME_TOOLS);+ const room = limit === null ? Infinity : Math.max(0, limit - RUNTIME_TOOLS - (standIn ? 1 : 0));const wanted = [...offeredTools, ...configured].reduce((sum, server) => sum + server.tools.length, 0);const searchRoom = configured.some((server) => server.tools.length) && wanted > room ? DIRECTORY_TOOL_COUNT : 0;// The agents server keeps its whole list first; configured servers fit in what the built-ins leave.@@ -629,6 +649,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]}register(origin, tools);}+ if (standIn) definitions.push(standIn.definition);const direct = directServers(configured.map(({ origin, tools }) => ({ name: origin.server, tools: tools.length })), room - definitions.length);const searched: typeof configured = [];for (const server of configured) {@@ -674,14 +695,17 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]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 tools = await client.tools(signal, include, searchable.has(name) ? REMOTE_MCP_STARTUP_MS : startupMs, observers.get(name));- if (!tools.length && scope === undefined && descriptor === integrations?.localComputer) throw new Error("The Local VM listed no tools");+ 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, startupMs, signal) : undefined;+ const tools = host ? (host.state === "listed" || host.state === "pending" ? host.tools : []) : await client.tools(signal, include, searchable.has(name) ? REMOTE_MCP_STARTUP_MS : startupMs, 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: descriptor === integrations?.localComputer && integrations?.localComputer?.scope === "local-computer", required: index < builtIns && mustHave(descriptor), searched: searchable.has(name) };- return { origin, tools };+ 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()) {if (signal.aborted || closed) throw aborted();@@ -690,6 +714,13 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]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"}`);}+ const host = mount.value.host;+ if (host?.state === "starting" || host?.state === "failed") {+ const reason = host.state === "failed" ? host.reason : undefined;+ if (reason !== undefined) { hostComputerFailed = reason; console.warn(`chat-mcp: this computer's tools did not start for this turn: ${reason}`); await mount.value.origin.client.close().catch(() => {}); }+ standIn = { definition: hostComputerStandIn(reason), origin: mount.value.origin, ...(host.state === "starting" ? { ready: host.ready } : { reason }) };+ continue;+ }if (index < builtIns) {offeredTools.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) });continue;@@ -717,6 +748,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]};const validate = (name: string, args: unknown) => {if (closed || signal.aborted) throw new ChatToolSessionError("MCP session closed");+ if (name === standIn?.definition.function.name) return;const listedAs = directoryNames.get(name);if (listedAs) {const call = listedAs === CALL_TOOL ? searchedCall(args) : undefined;@@ -740,6 +772,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]return { title: chatToolName(tool.server, runs), input: object(args.arguments) ? args.arguments : {}, ask: true, ...(grant ? { grant } : {}) };};const view = (name: string, args: Record<string, unknown>): ChatToolCallView => {+ if (name === standIn?.definition.function.name) return { title: name, input: args, ask: false };if (directoryNames.has(name)) {const call = directoryNames.get(name) === CALL_TOOL ? searchedCall(args) : undefined;return call ? viewOf(call.tool, call.args, chatToolName(call.tool.server, call.tool.name)) : { title: name, input: args, ask: false };@@ -749,6 +782,8 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]};const run = async (tool: RegisteredTool, args: Record<string, unknown>, callSignal: AbortSignal): Promise<ChatToolResult> => {try {+ const failure = tool.ready && await hostComputerFailure(tool.ready, AbortSignal.any([signal, callSignal]));+ if (failure !== undefined) return { ok: false, text: hostComputerDidNotStart(failure) };const result = await tool.client.call("tools/call", { name: tool.name, arguments: args }, AbortSignal.any([signal, callSignal]), callTimeoutMs, true);if (signal.aborted || callSignal.aborted) throw aborted();if (!object(result) || !Array.isArray(result.content) || (result.isError !== undefined && typeof result.isError !== "boolean")) throw new Error("MCP tool returned an invalid result; execution outcome may be uncertain");@@ -783,8 +818,33 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]}};const answer = (result: DirectoryResult): ChatToolResult => ({ text: boundedText(result.content.map((part) => part.text).join("\n")), ok: result.isError !== true });+ /** Waits for this computer's start, then lists its tools in the stand-in's place, keeping the runtime's own tools. */+ const awaitHostComputer = async (callSignal: AbortSignal): Promise<ChatToolResult> => {+ const waiting = standIn!;+ if (!waiting.ready) return { ok: false, text: hostComputerDidNotStart(waiting.reason!) };+ let tools: unknown[] = [];+ const failure = await hostComputerFailure(waiting.ready.then((listed) => { tools = listed; }), AbortSignal.any([signal, callSignal])).catch(async (error: unknown) => {+ await close().catch(() => {});+ throw new ChatToolSessionError(error instanceof Error ? error.message : "MCP operation cancelled");+ });+ if (failure !== undefined) {+ if (standIn === waiting) {+ Object.assign(waiting, { ready: undefined, reason: failure });+ waiting.definition.function.description = hostComputerStandIn(failure).function.description;+ }+ return { ok: false, text: hostComputerDidNotStart(failure) };+ }+ if (standIn !== waiting) return { ok: true, text: HOST_COMPUTER_READY };+ const runtime = definitions.filter((definition) => !registered.has(definition.function.name) && !directoryNames.has(definition.function.name)+ && definition !== waiting.definition);+ standIn = undefined;+ offeredTools.push({ origin: waiting.origin, tools: checkedTools(tools, waiting.origin.server) });+ await layout(budget.limit);+ definitions.push(...runtime);+ return { ok: true, text: HOST_COMPUTER_READY };+ };return {- definitions, skipped, trimmed, merged, budget, validate, view, close,+ definitions, skipped, trimmed, merged, budget, validate, view, close, ...(hostComputerFailed !== undefined ? { hostComputerFailure: hostComputerFailed } : {}),async refit(limit) {if (closed || signal.aborted) throw new ChatToolSessionError("MCP session closed");await layout(limit);@@ -792,6 +852,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]async execute(name, args, callSignal) {validate(name, args);if (callSignal.aborted) { await close(); throw aborted(); }+ if (name === standIn?.definition.function.name) return awaitHostComputer(callSignal);const listedAs = directoryNames.get(name);if (!listedAs) return run(registered.get(name)!, args, callSignal);if (listedAs === SEARCH_TOOL) return answer(await directory!.search(args));diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 8dd6a8128d..48187a7cf2 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, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";+import { ChatToolSessionError, chatToolNoticeLines, 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";@@ -611,7 +611,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)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));noteToolBudget(turn.botId, tools.budget);- for (const message of chatToolNotices(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });+ for (const { message, text } of chatToolNoticeLines(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message), ...(text ? { text } : {}) });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.diff --git a/src/locales/en.json b/src/locales/en.jsonindex ba57e75465..d6b6cc2354 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -10158,6 +10158,7 @@"chat.notice.computerDesktopOnly": "Only the OpenMausBot app on this computer can let a bot use it. Open the app here, or let the bot work in its own browser or on a cloud desktop instead.","chat.notice.computerPermissionsThenRestart": "OpenMausBot can't use this computer yet — make sure OpenMausBot has the permissions it asks for, then restart it","chat.notice.computerNotReadyDetail": "OpenMausBot can't use this computer yet — {reason}",+ "chat.notice.computerToolsDidNotStart": "The tools for this computer did not start this time ({reason}). It is still linked to this bot; send your message again in a moment.","chat.notice.computerNotReadyMacPermission": "OpenMausBot can't use this computer yet — {reason}. Relaunch OpenMausBot after granting the missing macOS permission.","chat.notice.computerSystemUnsupported": "bots can't use this computer on this system — choose another place for this bot to work","chat.notice.computerAiUnsupported": "this bot's AI can't use this computer — pick another AI for this bot, or choose another place for it to work",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex a4e94fc4b4..f079c59620 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10080,6 +10080,7 @@"chat.notice.computerDesktopOnly": "Só o app OpenMausBot neste computador pode permitir que um bot o use. Abra o app aqui ou deixe o bot trabalhar no próprio navegador ou em um desktop na nuvem.","chat.notice.computerPermissionsThenRestart": "O OpenMausBot ainda não consegue usar este computador. Confira se o OpenMausBot tem as permissões que pede e reinicie o app.","chat.notice.computerNotReadyDetail": "O OpenMausBot ainda não consegue usar este computador. Motivo: {reason}",+ "chat.notice.computerToolsDidNotStart": "As ferramentas deste computador não iniciaram desta vez ({reason}). Ele continua vinculado a este bot; envie sua mensagem de novo daqui a pouco.","chat.notice.computerNotReadyMacPermission": "O OpenMausBot ainda não consegue usar este computador. Motivo: {reason}. Abra o OpenMausBot novamente depois de conceder a permissão do macOS que falta.","chat.notice.computerSystemUnsupported": "Os bots não podem usar este computador neste sistema. Escolha outro lugar para este bot trabalhar","chat.notice.computerAiUnsupported": "A IA deste bot não pode usar este computador. Escolha outra IA ou outro lugar para o bot trabalhar",