Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(antigravity): name the tools a session leaves out, and test a second hand-off after a resume
luishron12363292208c685
diff --git a/server/comms.test.ts b/server/comms.test.tsindex ea16248e68..2d6792d670 100644--- a/server/comms.test.ts+++ b/server/comms.test.ts@@ -207,16 +207,11 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {chmodSync(antigravityCli, 0o755);chmodSync(antigravityHarness, 0o755);}- const antigravityProfile = join(- home,- ".openmausbot",- "providers",- "antigravity",- createHash("sha256").update("geminiAsker").digest("hex"),- "antigravity-acp",- );- mkdirSync(antigravityProfile, { recursive: true });- writeFileSync(join(antigravityProfile, "acp_token.json"), "{}\n");+ for (const instanceId of ["geminiAsker", "geminiDelegate"]) {+ const antigravityProfile = join(home, ".openmausbot", "providers", "antigravity", createHash("sha256").update(instanceId).digest("hex"), "antigravity-acp");+ mkdirSync(antigravityProfile, { recursive: true });+ writeFileSync(join(antigravityProfile, "acp_token.json"), "{}\n");+ }compat = createServer(async (req, res) => {for await (const _ of req) {}if (req.url?.endsWith("/models")) {@@ -277,6 +272,20 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {},config: { cli: antigravityCli, fullAuto: true },},+ // The Antigravity asker that hands work on with coordinate_bots, its process gone after each result's wake, so the+ // person's next turn resumes the session in a new one (session/resume), as after a restart.+ geminiDelegate: {+ driver: "antigravityAgent",+ environment: {+ FAKE_ACP_MODE: "delegate-peer",+ FAKE_ACP_AUTH_METHOD: "oauth-personal",+ FAKE_ACP_MODELS: "gemini-4-neon,gemini-4-pro",+ FAKE_ACP_MODES: "default,yolo",+ FAKE_ACP_EXIT_AFTER_WAKE: "1",+ FAKE_ACP_RPC_APPEND_FILE: join(home, "gemini-delegate-rpc.jsonl"),+ },+ config: { cli: antigravityCli, fullAuto: true },+ },// Hermes shape: keeps the first agents proxy it is offered for the life of the processpoolLister: {driver: "hermesAgent",@@ -623,6 +632,52 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {45_000,);+ it(+ "on Antigravity, hands on a second task from the person's next message after the first one's wake, a model switch and session/resume",+ async () => {+ await hideAll();+ const helper = await named("Helper", { modelSelection: HELPER });+ const shop = await named("Shop", { modelSelection: { instanceId: "geminiDelegate", model: "gemini-4-neon" } });+ const settled = (count: number) => waitUntil(async () => {+ const current = await bot(shop.id);+ const woke = current.messages.filter((m: any) => m.kind === "text" && m.role === "bot" && m.text === WOKE_WITH_RESULT).length;+ return woke >= count && !current.busy && !(await bot(helper.id)).busy;+ }, 45_000, `hand-off ${count} never settled`);++ expect((await api("POST", `/api/bots/${shop.id}/messages`, { text: "have @Helper do BRIEF_FIRST" })).status).toBe(202);+ await settled(1);+ // The person switches the conversation's model; the process that answered the wake is gone.+ expect((await api("PATCH", `/api/bots/${shop.id}`, { modelSelection: { instanceId: "geminiDelegate", model: "gemini-4-pro" } })).status).toBe(200);+ expect((await api("POST", `/api/bots/${shop.id}/messages`, { text: "now have @Helper do BRIEF_SECOND" })).status).toBe(202);+ await settled(2);++ // The conversation's own processes, those that answered a prompt: a process that only reads the model catalog is not one.+ const calls = readFileSync(join(home, "gemini-delegate-rpc.jsonl"), "utf8").trim().split("\n")+ .map((line) => JSON.parse(line) as { pid: number; method: string });+ const prompted = new Set(calls.filter((call) => call.method === "session/prompt").map((call) => call.pid));+ const setups = calls.filter((call) => prompted.has(call.pid) && (call.method === "session/new" || call.method === "session/resume"));+ expect(setups.map((call) => call.method)).toEqual(["session/new", "session/resume"]);+ expect(new Set(setups.map((call) => call.pid)).size).toBe(2);+ const current = await bot(shop.id);+ expect(current.modelSelection).toMatchObject({ instanceId: "geminiDelegate", model: "gemini-4-pro" });+ const delegated = current.messages.filter((m: any) => m.kind === "text" && m.role === "bot" && m.text?.startsWith("delegated:"));+ expect(delegated).toHaveLength(2);+ const requestIds = delegated.map((m: any) => /"requestId":"([\w-]+)"/.exec(m.text)?.[1]);+ expect(requestIds.every(Boolean)).toBe(true);+ expect(new Set(requestIds).size).toBe(2);+ expect(current.messages.some((m: any) => /unknown tool/i.test(m.text ?? ""))).toBe(false);++ const works = assignments(helper.id, shop.id);+ expect(works.map((work) => work.id).sort()).toEqual([...requestIds].sort());+ expect(works.map((work) => [work.text, work.status])).toEqual([["delegated task BRIEF_FIRST", "completed"], ["delegated task BRIEF_SECOND", "completed"]]);+ // Both from the same conversation of the parent.+ const parents = works.map((work) => rows().find((row) => row.id === work.parentId)!);+ expect(new Set(parents.map((parent) => `${parent.botId}/${parent.threadId}`)).size).toBe(1);+ expect(parents[0]!.botId).toBe(shop.id);+ },+ 120_000,+ );+it("keeps the asker's session when the teammate's result lands instead of rebuilding it",async () => {diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 537cc28f73..f3df6f3710 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -74,7 +74,7 @@ import { startupFailureRecoverable } from "./startup-recovery.ts";import { engineFailure, engineFailureKind } from "../engine-errors.ts";import { acpRuntimeFailure, acpStopFailure } from "./failure-words.ts";import { narrowsNativeTools, parseToolScope } from "../../../shared/tool-scope.ts";-import { acpMcpServers, type AcpMcpServer } from "../turn-mcp.ts"; import { acpOwnMcpTransport, acpSessionMcpServers, loopbackUnproxied } from "../own-mcp-http.ts"; import { acpToolOutput, acpToolProgress } from "../tool-progress.ts";+import { acpMcpServers, type AcpMcpServer } from "../turn-mcp.ts"; import { acpOwnMcpTransport, acpSessionMcpServers, loopbackUnproxied } from "../own-mcp-http.ts"; import { leftOutToolsNote } from "../session-tool-budget.ts"; import { acpToolOutput, acpToolProgress } from "../tool-progress.ts";import { learnedToolCountLimit, mcpToolBudget, retryUnderToolLimit } from "../../tool-count-limit.ts"; import { instanceEnvNames } from "../../bot-box/env.ts";import { learnedTextOnlyTools, learnTextOnlyTools, TEXT_ONLY_PROMPT_NOTE } from "../../mcp-text-only.ts"; import { isHermesReasoningReplay } from "./hermes-replay.ts";@@ -1121,6 +1121,8 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>if (liveSessionId !== null && session.sessionKey === liveSessionKey(sessionKey, heldSystem()) && (cursor === null || cursor === liveSessionId)) {break;}+ const sessionServers = () => acpSessionMcpServers(mcpServers, ownMcp, init, support.takesUnadvertisedHttpMcp, support.sessionToolBudget,+ (left) => { session.toolsLeftOut = () => leftOutToolsNote(left()); });const selectionParams = narrowsNativeTools(turn.toolScope)? support.toolScopeSessionParams!(turn, init, mcpServers.length > 0, { config: turnConfig, env, cwd }) : {};let loaded = false;@@ -1130,7 +1132,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>link: session.acp, sessionId: cursor, quietMs: support.loadReplayQuietMs?.(turn), replayed: () => session.sessionConfigResult ?? {},send: (receive) => request(support.resumeMethod === "resume" ? "session/resume" : "session/load",- { sessionId: cursor, cwd, mcpServers: support.mcpServersFromLaunch ? [] : acpSessionMcpServers(mcpServers, ownMcp, init, support.takesUnadvertisedHttpMcp, support.sessionToolBudget), ...selectionParams, ...support.sessionSetupParams?.(init, heldSystem()) },+ { sessionId: cursor, cwd, mcpServers: support.mcpServersFromLaunch ? [] : sessionServers(), ...selectionParams, ...support.sessionSetupParams?.(init, heldSystem()) },support.sessionSetupTimeoutMs ?? LOAD_SESSION_TIMEOUT, receive),receive: (result) => {if (result) {@@ -1173,7 +1175,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>promptTurn = { ...turn, text: recovery.text };rebuiltFromReplay = recovery.replayed;}- await sessionNewRetried(() => request("session/new", { cwd, mcpServers: support.mcpServersFromLaunch ? [] : acpSessionMcpServers(mcpServers, ownMcp, init, support.takesUnadvertisedHttpMcp, support.sessionToolBudget), ...selectionParams, ...support.sessionSetupParams?.(init, heldSystem()) }, support.sessionSetupTimeoutMs ?? NEW_SESSION_TIMEOUT, (result) => {+ await sessionNewRetried(() => request("session/new", { cwd, mcpServers: support.mcpServersFromLaunch ? [] : sessionServers(), ...selectionParams, ...support.sessionSetupParams?.(init, heldSystem()) }, support.sessionSetupTimeoutMs ?? NEW_SESSION_TIMEOUT, (result) => {session.sessionId = typeof result?.sessionId === "string" ? result.sessionId : null;session.sessionKey = liveSessionKey(sessionKey, heldSystem());receiveModelVariants(result, true);@@ -1281,11 +1283,11 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>if (expectedModeId !== undefined && readSessionModes(session.sessionConfigResult)?.currentModeId !== expectedModeId) throw new Error(`${support.displayName} changed mode before the prompt`);state.promptSent = true; clock.promptSent(Date.now());if (!support.promptUnreachedModel) acknowledge();- const promptIdleMs = promptIdleTimeoutMs();+ const promptIdleMs = promptIdleTimeoutMs(); const leftOutNote = session.toolsLeftOut?.();const quiet = startQuietWatch(threadId, session, current);const result = await request("session/prompt",- { sessionId, prompt: [{ type: "text", text: text + media.note }, ...imageBlocks, ...media.blocks, ...(contextNote ? [{ type: "text", text: contextNote }] : []), ...(textOnlyModel ? [{ type: "text", text: TEXT_ONLY_PROMPT_NOTE }] : [])] },+ { sessionId, prompt: [{ type: "text", text: text + media.note }, ...imageBlocks, ...media.blocks, ...(contextNote ? [{ type: "text", text: contextNote }] : []), ...(leftOutNote ? [{ type: "text", text: leftOutNote }] : []), ...(textOnlyModel ? [{ type: "text", text: TEXT_ONLY_PROMPT_NOTE }] : [])] },undefined,undefined,promptIdleMs,diff --git a/server/drivers/acp/turn-state.ts b/server/drivers/acp/turn-state.tsindex 1670755a03..777a274236 100644--- a/server/drivers/acp/turn-state.ts+++ b/server/drivers/acp/turn-state.ts@@ -61,6 +61,8 @@ export interface AcpSession {sessionKey: string | null;sessionId: string | null;sessionConfigResult: any;+ /** The line each prompt carries while this session's tool lists leave tools out to fit the engine's budget, read per prompt. */+ toolsLeftOut?: () => string | undefined;/** Monotonic counter incremented on live `current_mode_update` notifications so an in-flight `session/set_mode` response cannot overwrite a newer server update. */modeVersion: number;initResult: any;diff --git a/server/drivers/antigravity-coordination-tools.test.ts b/server/drivers/antigravity-coordination-tools.test.tsindex 6163435297..6badc13bba 100644--- a/server/drivers/antigravity-coordination-tools.test.ts+++ b/server/drivers/antigravity-coordination-tools.test.ts@@ -77,7 +77,7 @@ async function start(executable: string, dump: string, rpc: string) {instanceId: "antigravity-coordination", displayName: "Antigravity", enabled: true, config: { cli: executable, fullAuto: false },environment: {FAKE_ACP_AUTH_METHOD: "oauth-personal", FAKE_ACP_MODELS: "gemini-4-neon,gemini-4-pro", FAKE_ACP_AGENT_NAME: "Antigravity ACP Server",- FAKE_ACP_VERSION: "1.5.18", FAKE_ACP_MODES: "default,plan", FAKE_ACP_DUMP: dump, FAKE_ACP_RPC_APPEND_FILE: rpc,+ FAKE_ACP_VERSION: "1.5.18", FAKE_ACP_MODES: "default,plan", FAKE_ACP_DUMP: dump, FAKE_ACP_DUMP_PROMPT: "1", FAKE_ACP_RPC_APPEND_FILE: rpc,},});instances.push(instance);@@ -122,9 +122,25 @@ describe("a native Antigravity CLI thread over the session's tool budget", () =>const { turnId } = await instance.adapter.sendTurn({ threadId: "t-shop", text, cwd: directory, integrations, ...extra });expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).toMatchObject({ ok: true });};- const check = (sent: Sent[]) => {+ const note = () => (JSON.parse(readFileSync(`${dump}.prompt.json`, "utf8")) as Array<{ text?: string }>)+ .map((block) => block.text ?? "").find((text) => text.startsWith("[Tools left out]"));+ // `relaysAnswered` false: the turn was set up before any relay had answered and recorded its list, as only this fake+ // allows (the CLI lists every server's tools on session setup, before the prompt), so it can name only OpenMausBot's own.+ const check = (sent: Sent[], relaysAnswered = true) => {expect(sent.map((server) => server.name).sort()).toEqual(Object.keys(LISTS).sort());const lists = shown(sent);+ // The turn names what the lists left out, server by server, so the bot knows what it cannot call.+ const left = Object.entries(LISTS).filter(([server]) => relaysAnswered || ["agents", "browser", "data"].includes(server)).flatMap(([server, tools]) => {+ const kept = new Set(lists[server]!.map((tool) => tool.name));+ return tools.filter((tool) => !kept.has(tool.name)).map((tool) => `${server}/${tool.name}`);+ });+ const named = note() ?? "";+ for (const tool of left) {+ const [server, name] = tool.split("/");+ expect(named).toMatch(new RegExp(`(?:: |; )${server}: (?:[^;]*, )?${name}(?:[,;.]|$)`));+ }+ if (relaysAnswered && !left.length) expect(note()).toBeUndefined();+ for (const name of COORDINATION_TOOLS) expect(named).not.toMatch(new RegExp(`\\b${name}\\b`));for (const name of COORDINATION_TOOLS) expect(lists.agents!.map((tool) => tool.name)).toContain(name);// Counted as the CLI counts them, each tool by its own name.const all = Object.values(lists).flat();@@ -136,7 +152,7 @@ describe("a native Antigravity CLI thread over the session's tool budget", () =>// session/new: nothing recorded yet, so the person's servers are sized by a reserve.await turn("hello");expect(setups()).toEqual(["session/new"]);- check(sentNow());+ check(sentNow(), false);const sessionId = (recorder.events.find((event) => event.type === "session.started") as { sessionId: string }).sessionId;// A model switch in the same live session: its servers are the ones session/new sent.diff --git a/server/drivers/own-mcp-http.ts b/server/drivers/own-mcp-http.tsindex ef837cb62f..5b5fe00f26 100644--- a/server/drivers/own-mcp-http.ts+++ b/server/drivers/own-mcp-http.ts@@ -7,7 +7,7 @@// port is the box's bridge to the harness gate (bot-box/harness-gate.ts), which passes /api/internal/ only, and the box// keeps loopback out of its egress proxy (NO_PROXY).import { botBox } from "../bot-box/box.ts";-import { withSessionToolBudget } from "./session-tool-budget.ts";+import { withSessionToolBudget, type LeftOutTools } from "./session-tool-budget.ts";import { acpOwnServersOverHttp, ownMcpOverHttp, type AcpMcpServer } from "./turn-mcp.ts";/** "1" turns the URL form on for every engine that can take it; "0" keeps every engine on stdio proxies, the ACP agents@@ -79,10 +79,11 @@ export function acpAgentTakesHttpMcp(init: unknown): boolean {* the session's agent takes them, by its `initialize` answer or, for an agent that takes them without saying so, by* `takesUnadvertised`. Deciding here, after `initialize`, lets an agent's first session use the URL form too. An agent* with a session-wide budget for tool definitions (`toolBudget`, by its `initialize` answer) has every server OpenMausBot- * serves or relays share it out, by URL or stdio alike. */+ * serves or relays share it out, by URL or stdio alike, and `leftOut` is told what their lists leave out to fit it. */export function acpSessionMcpServers(servers: AcpMcpServer[], transport: AcpOwnMcpTransport, init: unknown,- takesUnadvertised?: (init: unknown) => boolean, toolBudget?: (init: unknown) => number | undefined): AcpMcpServer[] {+ takesUnadvertised?: (init: unknown) => boolean, toolBudget?: (init: unknown) => number | undefined, leftOut?: (left: () => LeftOutTools[]) => void): AcpMcpServer[] {const budget = toolBudget?.(init);- const shared = budget === undefined ? servers : withSessionToolBudget(servers, budget);+ if (budget === undefined) leftOut?.(() => []);+ const shared = budget === undefined ? servers : withSessionToolBudget(servers, budget, { leftOut });return transport === "advertised" && (acpAgentTakesHttpMcp(init) || takesUnadvertised?.(init) === true) ? acpOwnServersOverHttp(shared) : shared;}diff --git a/server/drivers/own-mcp-session-budget.ts b/server/drivers/own-mcp-session-budget.tsindex da5034c17b..ffb0192cf0 100644--- a/server/drivers/own-mcp-session-budget.ts+++ b/server/drivers/own-mcp-session-budget.ts@@ -12,7 +12,7 @@ import { PHONE_TOOLS } from "../phones/tools.ts";import type { HarnessMcpKind } from "../harness-mcp-request.ts";import { TOOL_SCHEMA_PROFILE_ENV } from "../tool-schema-profile.ts";import {- definitionListBytes, descriptionLevelFor, toolListShareProfile, withCompactSchemas, withDescriptionLevel, type ListedTool,+ definitionListBytes, descriptionLevelFor, fitToolListWithinShare, toolListShareProfile, withCompactSchemas, withDescriptionLevel, type ListedTool,} from "../tool-list-budget.ts";import { agentsToolList } from "./agents-mcp.ts";import { ownMcpOverHttp, type AcpMcpServer } from "./turn-mcp.ts";@@ -72,15 +72,23 @@ export function withOwnShare(server: AcpMcpServer, share: number): AcpMcpServer}/** `servers` with each of OpenMausBot's own servers given its share of `budget`; every other server as it was. */-export function withSessionToolShares(servers: AcpMcpServer[], budget: number, log: (line: string) => void = (line) => console.warn(line)): AcpMcpServer[] {+export function withSessionToolShares(servers: AcpMcpServer[], budget: number, log: (line: string) => void = (line) => console.warn(line),+ leftOut?: (left: () => Array<{ server: string; tools: string[] }>) => void): AcpMcpServer[] {const own = servers.map((server) => ({ server, tools: ownServerToolList(server) })).filter((entry) => entry.tools !== null);- if (!own.length) return servers;+ if (!own.length) {+ leftOut?.(() => []);+ return servers;+ }const { shares, bytes, fits } = sessionToolShares(own.map(({ tools }) => tools!), budget);if (!fits) {const others = servers.filter((server) => !own.some((entry) => entry.server === server)).map((server) => server.name);log(`[mcp] this session's own MCP tools (${own.map(({ server }) => server.name).join(", ")}) come to ${bytes} bytes at their shortest, ${bytes - budget} over the ${budget}-byte tool budget; each server leaves out its least important tools to fit its share${others.length ? ` (${others.join(", ")} not counted)` : ""}`);}const shareOf = new Map(own.map(({ server }, index) => [server, shares[index]!]));+ leftOut?.(fits ? () => [] : () => own.flatMap(({ server, tools }) => {+ const { left } = fitToolListWithinShare(tools!, shareOf.get(server)!);+ return left.length ? [{ server: server.name, tools: left }] : [];+ }));return servers.map((server) => {const share = shareOf.get(server);return share === undefined ? server : withOwnShare(server, share);diff --git a/server/drivers/session-tool-budget.ts b/server/drivers/session-tool-budget.tsindex 504c5ce4a1..8762e3faf1 100644--- a/server/drivers/session-tool-budget.ts+++ b/server/drivers/session-tool-budget.ts@@ -10,7 +10,7 @@ import { createHash } from "node:crypto";import { join } from "node:path";import { DATA_DIR } from "../config.ts";-import { toolListFloorBytes, type ListedTool } from "../tool-list-budget.ts";+import { fitToolListWithinShare, toolListFloorBytes, type ListedTool } from "../tool-list-budget.ts";import { readRecordedToolList, TOOL_LIST_RECORD_ENV, TOOL_LIST_SHARE_ENV } from "../tool-list-share.ts";import { ownServerToolList, sessionToolShares, withOwnShare, withSessionToolShares } from "./own-mcp-session-budget.ts";import type { AcpMcpServer } from "./turn-mcp.ts";@@ -33,6 +33,30 @@ export interface SessionBudgetOptions {/** Where relays record the lists they relay. */recordsDir?: string;log?: (line: string) => void;+ /** Told, on every setup, how to read the tools each server's list leaves out to fit its share: none when the session fits.+ * Read it when needed: a relay's list is known once the relay has answered and recorded it. */+ leftOut?: (left: () => LeftOutTools[]) => void;+}++/** The tools one server of a session leaves out of its list to fit its share. */+export interface LeftOutTools { server: string; tools: string[] }++/** What `lists` leave out under `shares`, by server, as each list's own fit chooses (fitToolListWithinShare). */+export function leftOutTools(lists: ReadonlyArray<{ server: string; tools: readonly ListedTool[] | number; share: number | undefined; record?: string }>): LeftOutTools[] {+ return lists.flatMap(({ server, tools: planned, share, record }) => {+ // A relay set aside a reserve is sized by the list it recorded since, once it has answered.+ const tools = typeof planned === "number" && record ? readRecordedToolList(record) ?? planned : planned;+ if (typeof tools === "number" || share === undefined) return [];+ const { left } = fitToolListWithinShare(tools, share);+ return left.length ? [{ server, tools: left }] : [];+ });+}++/** The line a turn carries while its session's lists leave tools out, so the bot knows what it cannot call and why. */+export function leftOutToolsNote(left: readonly LeftOutTools[]): string | undefined {+ if (!left.length) return undefined;+ return `[Tools left out] To fit this engine's limit on tool definitions, this session does not list: ${left.map(({ server, tools }) => `${server}: ${tools.join(", ")}`).join("; ")}. `+ + "They cannot be called here. If the task needs one, tell the person which, and that turning off a server this bot does not need brings it back.";}export function toolListRecordPath(recordsDir: string, botId: string, server: string): string {@@ -66,7 +90,7 @@ type Planned =export function withSessionToolBudget(servers: AcpMcpServer[], budget: number, options: SessionBudgetOptions = {}): AcpMcpServer[] {const env = options.env ?? process.env;const log = options.log ?? ((line: string) => console.warn(line));- if (env[SESSION_TOOL_BUDGET_ENV] === "0") return withSessionToolShares(servers, budget, log);+ if (env[SESSION_TOOL_BUDGET_ENV] === "0") return withSessionToolShares(servers, budget, log, options.leftOut);const recordsDir = options.recordsDir ?? join(DATA_DIR, "tool-list-records");const botId = servers.map((server) => ("command" in server ? valueOf(server.env, "OMB_BOT_ID") : undefined)).find(Boolean) ?? "";const planned: Planned[] = servers.map((server) => {@@ -82,11 +106,14 @@ export function withSessionToolBudget(servers: AcpMcpServer[], budget: number, oconst reserve = Math.max(UNKNOWN_LIST_RESERVE, Math.floor((budget - known) / unknown.length));for (const entry of unknown) if (entry.kind === "relay") entry.tools = reserve;}- if (!planned.some((entry) => entry.kind !== "other")) return servers;+ if (!planned.some((entry) => entry.kind !== "other")) {+ options.leftOut?.(() => []);+ return servers;+ }const others = planned.filter((entry) => entry.kind === "other");const sized = planned.filter((entry) => entry.kind !== "other");- const lists = [...sized.map((entry) => entry.tools), ...others.map(() => UNKNOWN_LIST_RESERVE)];- const { shares, bytes, fits } = sessionToolShares(lists, budget);+ const sizes = [...sized.map((entry) => entry.tools), ...others.map(() => UNKNOWN_LIST_RESERVE)];+ const { shares, bytes, fits } = sessionToolShares(sizes, budget);if (!fits) {log(`[mcp] this session's MCP tools (${sized.map((entry) => entry.server.name).join(", ")}) come to ${bytes} bytes at their shortest, ${bytes - budget} over the ${budget}-byte tool budget; each server leaves out its least important tools to fit its share`);}@@ -96,6 +123,15 @@ export function withSessionToolBudget(servers: AcpMcpServer[], budget: number, oif (refused.length) log(`[mcp] ${entry.server.name}: the engine refuses ${refused.length} tool(s) whose name as mcp_${entry.server.name}_<tool> is over 64 characters or not [a-zA-Z0-9_-]: ${refused.join(", ")}`);}const shareOf = new Map(sized.map((entry, index) => [entry.server, shares[index]!]));+ const lists = sized.map((entry) => ({ server: entry.server.name, tools: entry.tools, share: shareOf.get(entry.server), record: entry.kind === "relay" ? entry.record : undefined }));+ // Once every list is known what they leave out is settled; until then a relay that answers since is counted.+ let settled: LeftOutTools[] | undefined;+ options.leftOut?.(() => {+ if (settled) return settled;+ const left = leftOutTools(lists);+ if (lists.every((list) => typeof list.tools !== "number")) settled = left;+ return left;+ });return planned.map((entry) => {const share = shareOf.get(entry.server);if (share === undefined || entry.kind === "other") return entry.server;diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex 98b75b0f02..049652e97b 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -80,6 +80,7 @@// FAKE_ACP_OMIT_MODEL_VALUE when the live model equals this id, the model option has no currentValue// (Copilot CLI 1.0.105 does this for auto)// FAKE_ACP_EXIT_ON_MODEL the process exits when set_config_option selects this model+// FAKE_ACP_EXIT_AFTER_WAKE=1 the process exits once it has answered a hand-off result's wake turn// FAKE_ACP_HANG_ON_MODEL set_config_option never answers a switch to this model, as a stuck account can; other requests// are still answered// FAKE_ACP_VARIANTS JSON map model -> {id?, currentValue?, options} of ACP select values@@ -1222,6 +1223,12 @@ function handle(msg: any) {if (process.env.FAKE_ACP_DUMP) {writeFileSync(`${process.env.FAKE_ACP_DUMP}.mcp.json`, JSON.stringify(msg.params?.mcpServers ?? []));}+ // Antigravity's session/resume takes the session's servers again, as session/new does.+ if (Array.isArray(msg.params?.mcpServers)) {+ const offered = offeredAgents(msg.params.mcpServers);+ agentsMcp = mode === "list-peers" ? agentsMcp ?? offered : offered;+ sessionMcp = acceptedMcp(msg.params.mcpServers);+ }const opts = configOptions();const mdls = sessionModels();const sm = sessionModesPayload();@@ -1666,6 +1673,8 @@ function handle(msg: any) {},});complete();+ // As a CLI the app restarts between turns: the next turn resumes the session in a new process.+ if (process.env.FAKE_ACP_EXIT_AFTER_WAKE === "1") setTimeout(() => process.exit(0), 50);return;}if (mode === "chief-delegate" && agentsMcp && promptText.includes("CHECK_STATUS")) {@@ -1839,9 +1848,11 @@ function handle(msg: any) {return;}if (mode === "delegate-peer" && agentsMcp) {+ // A turn whose text names BRIEF_<word> hands on that task, so two of the person's requests are two briefs.+ const named = [...promptText.matchAll(/\bBRIEF_\w+/g)].at(-1)?.[0];void driveMcp(agentsMcp, [{ name: "list_bots", args: () => ({}) },- handoffCall("delegated task", { reason: "followup", doneWhen: "the export opens in Numbers" }),+ handoffCall(named ? `delegated task ${named}` : "delegated task", { reason: "followup", doneWhen: "the export opens in Numbers" }),]).then((reply) => {out({ jsonrpc: "2.0", method: "session/update", params: { update: { sessionUpdate: "agent_message_chunk", content: { text: `delegated: ${reply}` } } } });