Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(antigravity): keep the coordination tools when a session is over the CLI's tool budget
luishron123a7adf58a494d
diff --git a/server/drivers/antigravity-coordination-tools.test.ts b/server/drivers/antigravity-coordination-tools.test.tsnew file mode 100644index 0000000000..6163435297--- /dev/null+++ b/server/drivers/antigravity-coordination-tools.test.ts@@ -0,0 +1,163 @@+// A native Antigravity CLI thread whose servers are over the CLI's session tool budget even at their shortest, as a bot+// with the person's own servers beside OpenMausBot's: the CLI drops the session's largest tools first, so the session's+// lists must leave out tools themselves, never a coordination tool, on session/new, on session/resume after a restart, on+// a turn in the live session and after a model switch.+import { chmodSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, describe, expect, it, vi } from "vitest";++import { TOOL_LIST as BROWSER_TOOLS } from "../browser/tools.ts";+import { ensureDirs } from "../config.ts";+import type { ProviderInstance } from "../contracts.ts";+import { DATA_TOOLS } from "../data/tools.ts";+import { fitToolList } from "../mcp-tool-schema.ts";+import { SPAWNED_PROXIES } from "../proxy-paths.ts";+import { AGENTS_ENV_HEADER, TOOL_SHARE_HEADER } from "../routes/own-mcp-http-path.ts";+import { removeTempDir } from "../testing/cleanup.ts";+import { cliDrops } from "../testing/cli-tool-drop.ts";+import { recordEvents } from "../testing/events.ts";+import { EXECUTOR_LIKE_TOOLS } from "../testing/executor-like-tools.ts";+import { whopLikeCatalog } from "../testing/whop-like-catalog.ts";+import { workspaceAppsLikeCatalog } from "../testing/workspace-apps-like-catalog.ts";+import {+ ANTIGRAVITY_CLI_TOOL_BUDGET, ANTIGRAVITY_CLI_TOOL_LIMIT, COORDINATION_TOOLS, definitionListBytes, fitToolListToShare, toolListFloorBytes, toolsForShareProfile, type ListedTool,+} from "../tool-list-budget.ts";+import { TOOL_LIST_SHARE_ENV, toolsForSessionShare } from "../tool-list-share.ts";+import { TOOL_SCHEMA_PROFILE_ENV, toolSchemaProfile } from "../tool-schema-profile.ts";+import { agentsToolList } from "./agents-mcp.ts";+import { AntigravityDriver } from "./antigravity.ts";++vi.hoisted(() => { process.env.OMB_ANTIGRAVITY_NATIVE_CLI = "1"; });++const FAKE_ACP = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-acp-cli.ts");+const HARNESS = "http://127.0.0.1:8799";+const BOT = { OMB_HARNESS_URL: HARNESS, OMB_COMMS_TOKEN: "synthetic-comms", OMB_BOT_ID: "shop", OMB_THREAD_ID: "t-shop", OMB_CHIEF_OF_STAFF: "0", OMB_COMPUTER_SELECTION: "1" };+const gemini = toolSchemaProfile("gemini")!;++/** What each server really lists: OpenMausBot's own catalogs, and the person's servers after the gemini profile. */+const LISTS: Record<string, readonly ListedTool[]> = {+ agents: agentsToolList(BOT).listed as ListedTool[],+ browser: BROWSER_TOOLS,+ data: DATA_TOOLS as readonly ListedTool[],+ composio: fitToolList(workspaceAppsLikeCatalog(), gemini) as ListedTool[],+ shop: fitToolList(whopLikeCatalog().slice(0, 30), gemini) as ListedTool[],+ ts: fitToolList(EXECUTOR_LIKE_TOOLS, gemini) as ListedTool[],+};++type Sent = { name: string; headers?: Array<{ name: string; value: string }>; env?: Array<{ name: string; value: string }> };+const header = (server: Sent, name: string) => server.headers?.find((entry) => entry.name === name)?.value;+const envOf = (server: Sent) => Object.fromEntries((server.env ?? []).map(({ name, value }) => [name, value]));++/** Each list as the CLI is shown it under the servers a session setup sent, every relay answering (and recording) its own. */+function shown(sent: Sent[]): Record<string, ListedTool[]> {+ return Object.fromEntries(sent.map((server) => {+ const tools = LISTS[server.name]!;+ if (server.name === "agents") {+ const settings = JSON.parse(Buffer.from(header(server, AGENTS_ENV_HEADER)!, "base64url").toString("utf8")) as Record<string, string>;+ return [server.name, [...toolsForShareProfile(tools, settings[TOOL_SCHEMA_PROFILE_ENV])]];+ }+ const own = header(server, TOOL_SHARE_HEADER);+ return [server.name, own !== undefined ? [...toolsForShareProfile(tools, own)] : toolsForSessionShare(tools, envOf(server)) as ListedTool[]];+ }));+}+const flat = (lists: Record<string, ListedTool[]>) => Object.entries(lists).flatMap(([server, tools]) => tools.map((tool) => ({ ...tool, name: `${server}/${tool.name}` })));++const scratch: string[] = [];+const instances: ProviderInstance[] = [];+afterEach(async () => {+ for (const instance of instances.splice(0)) await instance.dispose();+ while (scratch.length) await removeTempDir(scratch.pop()!);+});++async function start(executable: string, dump: string, rpc: string) {+ ensureDirs();+ const instance = await AntigravityDriver.create({+ 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,+ },+ });+ instances.push(instance);+ return instance;+}++describe("a native Antigravity CLI thread over the session's tool budget", () => {+ it("the case is real: left to the CLI, a session this size loses coordinate_bots", () => {+ const lists = Object.values(LISTS);+ expect(lists.reduce((sum, tools) => sum + toolListFloorBytes(tools), 0)).toBeGreaterThan(ANTIGRAVITY_CLI_TOOL_BUDGET + 8_000);+ // Every tool kept and each list at its shortest: what the app showed before it chose what to leave out.+ const share = Math.floor(ANTIGRAVITY_CLI_TOOL_BUDGET / lists.length);+ const unchosen = Object.fromEntries(Object.entries(LISTS).map(([server, tools]) => [server, fitToolListToShare(tools, share).tools]));+ expect(cliDrops(flat(unchosen), ANTIGRAVITY_CLI_TOOL_BUDGET + definitionListBytes(flat(unchosen)) - definitionListBytes(Object.values(unchosen).flat())))+ .toContain("agents/coordinate_bots");+ });++ it("keeps every coordination tool on session/new, after a model switch, on session/resume after a restart, and in the live session after it", async () => {+ const directory = mkdtempSync(join(tmpdir(), "omb-agy-coordination-"));+ scratch.push(directory);+ const executable = join(directory, "antigravity");+ writeFileSync(executable, `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(FAKE_ACP)} "$@"\n`);+ chmodSync(executable, 0o755);+ const dump = join(directory, "dump.json");+ const rpc = join(directory, "rpc.jsonl");+ const integrations = {+ agents: { command: process.execPath, args: [SPAWNED_PROXIES.agents], env: { ...BOT } },+ browser: { command: process.execPath, args: [SPAWNED_PROXIES.harnessMcp, "browser"], env: { OMB_HARNESS_URL: HARNESS, OMB_MCP_TOKEN_BROWSER: "synthetic-browser" } },+ data: { command: process.execPath, args: [SPAWNED_PROXIES.harnessMcp, "data"], env: { OMB_HARNESS_URL: HARNESS, OMB_MCP_TOKEN_DATA: "synthetic-data" } },+ composio: { command: process.execPath, args: [SPAWNED_PROXIES.connectors], env: { OMB_BOT_ID: "shop", OMB_CONNECTOR_UPSTREAM_URL: "https://connectors.invalid/mcp" } },+ custom: { shop: { command: "npx", args: ["-y", "shop-mcp"], env: {} }, ts: { command: "npx", args: ["-y", "ts-mcp"], env: {} } },+ };+ // The thread's own calls: a session the driver opens elsewhere to read the model catalog is not one.+ const setups = () => readFileSync(rpc, "utf8").trim().split("\n").map((line) => JSON.parse(line) as { method: string; cwd: string })+ .filter((call) => call.cwd === realpathSync(directory)).map((call) => call.method)+ .filter((method) => method === "session/new" || method === "session/resume" || method === "session/set_model");+ const sentNow = () => JSON.parse(readFileSync(`${dump}.mcp.json`, "utf8")) as Sent[];++ let instance = await start(executable, dump, rpc);+ let recorder = recordEvents(instance.adapter);+ const turn = async (text: string, extra: { model?: string; resumeCursor?: string } = {}) => {+ 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[]) => {+ expect(sent.map((server) => server.name).sort()).toEqual(Object.keys(LISTS).sort());+ const lists = shown(sent);+ 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();+ expect(definitionListBytes(all)).toBeLessThanOrEqual(ANTIGRAVITY_CLI_TOOL_LIMIT);+ expect(cliDrops(all, ANTIGRAVITY_CLI_TOOL_LIMIT)).toEqual([]);+ return lists;+ };++ // 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());+ 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.+ await turn("on the other model", { model: "gemini-4-pro", resumeCursor: sessionId });+ expect(setups().filter((method) => method !== "session/set_model")).toEqual(["session/new"]);+ check(sentNow());++ // A restart: session/resume with every relay's record in place, so every share is sized again.+ await instance.dispose();+ instances.splice(0);+ instance = await start(executable, dump, rpc);+ recorder = recordEvents(instance.adapter);+ await turn("after the restart", { resumeCursor: sessionId });+ expect(setups().filter((method) => method !== "session/set_model")).toEqual(["session/new", "session/resume"]);+ const resumed = sentNow();+ expect(Number(envOf(resumed.find((server) => server.name === "shop")!)[TOOL_LIST_SHARE_ENV])).toBeGreaterThan(0);+ const lists = check(resumed);++ // A third turn in the resumed live session: no new setup, the same lists.+ await turn("third", { resumeCursor: sessionId });+ expect(setups().filter((method) => method !== "session/set_model")).toEqual(["session/new", "session/resume"]);+ expect(shown(sentNow())).toEqual(lists);+ }, 120_000);+});diff --git a/server/drivers/own-mcp-session-budget.test.ts b/server/drivers/own-mcp-session-budget.test.tsindex 4ea13b3adf..3b0164996a 100644--- a/server/drivers/own-mcp-session-budget.test.ts+++ b/server/drivers/own-mcp-session-budget.test.ts@@ -161,7 +161,7 @@ describe("sharing out a session's budget", () => {it("logs one line when the session cannot fit, by how much, and which servers it did not count", () => {const logged: string[] = [];withSessionToolShares([agentsServer(FULLEST), ...["browser", "data", "computer", "email", "device"].map(harnessServer), notes], 40_000, (line) => logged.push(line));- expect(logged).toEqual([expect.stringMatching(/^\[mcp\] this session's own MCP tools \(agents, browser, data, computer, email, device\) come to (\d+) bytes at their shortest, \d+ over the 40000-byte tool budget; the engine leaves out its largest tools first \(notes not counted\)$/)]);+ expect(logged).toEqual([expect.stringMatching(/^\[mcp\] this session's own MCP tools \(agents, browser, data, computer, email, device\) come to (\d+) bytes at their shortest, \d+ over the 40000-byte tool budget; each server leaves out its least important tools to fit its share \(notes not counted\)$/)]);expect(withSessionToolShares([notes], 40_000, (line) => logged.push(line))).toEqual([notes]);expect(logged).toHaveLength(1);});diff --git a/server/drivers/own-mcp-session-budget.ts b/server/drivers/own-mcp-session-budget.tsindex 51b47bb440..da5034c17b 100644--- a/server/drivers/own-mcp-session-budget.ts+++ b/server/drivers/own-mcp-session-budget.ts@@ -78,7 +78,7 @@ export function withSessionToolShares(servers: AcpMcpServer[], budget: number, lconst { 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; the engine leaves out its largest tools first${others.length ? ` (${others.join(", ")} not counted)` : ""}`);+ 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]!]));return servers.map((server) => {diff --git a/server/drivers/session-tool-budget.test.ts b/server/drivers/session-tool-budget.test.tsindex c52644b6f7..c286d52bf9 100644--- a/server/drivers/session-tool-budget.test.ts+++ b/server/drivers/session-tool-budget.test.ts@@ -16,7 +16,7 @@ import { cliDrops } from "../testing/cli-tool-drop.ts";import { whopLikeCatalog } from "../testing/whop-like-catalog.ts";import { workspaceAppsLikeCatalog } from "../testing/workspace-apps-like-catalog.ts";import {- ANTIGRAVITY_CLI_TOOL_BUDGET, definitionListBytes, toolListFloorBytes, toolsForShareProfile, type ListedTool,+ ANTIGRAVITY_CLI_TOOL_BUDGET, ANTIGRAVITY_CLI_TOOL_LIMIT, COORDINATION_TOOLS, definitionListBytes, toolListFloorBytes, toolsForShareProfile, type ListedTool,} from "../tool-list-budget.ts";import { TOOL_LIST_RECORD_ENV, TOOL_LIST_SHARE_ENV, toolsForSessionShare } from "../tool-list-share.ts";import { TOOL_SCHEMA_PROFILE_ENV, toolSchemaProfile } from "../tool-schema-profile.ts";@@ -107,7 +107,7 @@ describe("the session's tool budget over every server", () => {}});- it("a session that cannot fit even at its shortest keeps every tool, says by how much, and leaves the CLI the largest to drop", () => {+ it("a session that cannot fit even at its shortest leaves out its servers' least important tools itself, never a coordination tool", () => {const recordsDir = mkdtempSync(join(tmpdir(), "stb-"));const big = [...session, workspace];LISTS.workspace = fitToolList(whopLikeCatalog().slice(0, 120), gemini) as ListedTool[];@@ -115,8 +115,12 @@ describe("the session's tool budget over every server", () => {shown(plan(big, recordsDir).planned);const { planned, logged } = plan(big, recordsDir);const lists = shown(planned);- expect(flat(lists)).toHaveLength(Object.values(OWN).flat().length + LISTS.composio!.length + LISTS.workspace.length);- expect(logged).toEqual([expect.stringMatching(/^\[mcp\] this session's MCP tools \(agents, browser, data, composio, workspace\) come to \d+ bytes at their shortest, \d+ over the 55000-byte tool budget; the engine leaves out its largest tools first$/)]);+ expect(flat(lists).length).toBeLessThan(Object.values(OWN).flat().length + LISTS.composio!.length + LISTS.workspace.length);+ for (const name of COORDINATION_TOOLS) expect(lists.agents!.map((tool) => tool.name)).toContain(name);+ const all = Object.values(lists).flat();+ expect(definitionListBytes(all)).toBeLessThanOrEqual(ANTIGRAVITY_CLI_TOOL_LIMIT);+ expect(cliDrops(all, ANTIGRAVITY_CLI_TOOL_LIMIT)).toEqual([]);+ expect(logged).toEqual([expect.stringMatching(/^\[mcp\] this session's MCP tools \(agents, browser, data, composio, workspace\) come to \d+ bytes at their shortest, \d+ over the 55000-byte tool budget; each server leaves out its least important tools to fit its share$/)]);} finally {LISTS.workspace = fitToolList(whopLikeCatalog().slice(0, 30), gemini) as ListedTool[];}diff --git a/server/drivers/session-tool-budget.ts b/server/drivers/session-tool-budget.tsindex 012a4c78ad..504c5ce4a1 100644--- a/server/drivers/session-tool-budget.ts+++ b/server/drivers/session-tool-budget.ts@@ -88,7 +88,7 @@ export function withSessionToolBudget(servers: AcpMcpServer[], budget: number, oconst lists = [...sized.map((entry) => entry.tools), ...others.map(() => UNKNOWN_LIST_RESERVE)];const { shares, bytes, fits } = sessionToolShares(lists, 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; the engine leaves out its largest tools first`);+ 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`);}if (others.length) log(`[mcp] ${others.map((entry) => entry.server.name).join(", ")}: not relayed by OpenMausBot, so not fitted to the session's tool budget (${UNKNOWN_LIST_RESERVE} bytes set aside each)`);for (const entry of sized) {diff --git a/server/harness-mcp-proxy.test.ts b/server/harness-mcp-proxy.test.tsindex d80d23da7d..c3ba581429 100644--- a/server/harness-mcp-proxy.test.ts+++ b/server/harness-mcp-proxy.test.ts@@ -53,10 +53,10 @@ describe("harness MCP capability proxy", () => {const tool = { name: "data_sql", description: "Run SQL. It reads the bot's tables.", inputSchema: { type: "object", additionalProperties: true, properties: { sql: { type: "string", description: "One statement." } } } };payload = { result: { tools: [tool], instructions: "DuckDB" } };await expect(harnessMcpRequest(frame("tools/list"), { ...connection("data"), schemaProfile: "moonshot" })).resolves.toEqual({ jsonrpc: "2.0", id: 1, result: { tools: [tool], instructions: "DuckDB" } });- await expect(harnessMcpRequest(frame("tools/list"), { ...connection("data"), schemaProfile: "listShare:100" })).resolves.toEqual({ jsonrpc: "2.0", id: 1, result: {+ await expect(harnessMcpRequest(frame("tools/list"), { ...connection("data"), schemaProfile: "listShare:150" })).resolves.toEqual({ jsonrpc: "2.0", id: 1, result: {instructions: "DuckDB", tools: [{ name: "data_sql", description: tool.description, inputSchema: { type: "object", properties: { sql: { type: "string" } } } }] } });payload = { result: { content: [{ type: "text", text: "1 row" }] } };- await expect(harnessMcpRequest(frame("tools/call", { name: "data_sql", arguments: { sql: "select 1" } }), { ...connection("data"), schemaProfile: "listShare:100" }))+ await expect(harnessMcpRequest(frame("tools/call", { name: "data_sql", arguments: { sql: "select 1" } }), { ...connection("data"), schemaProfile: "listShare:150" })).resolves.toEqual({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: "1 row" }] } });});diff --git a/server/tool-list-budget.test.ts b/server/tool-list-budget.test.tsindex edb9d7f344..c785db8901 100644--- a/server/tool-list-budget.test.ts+++ b/server/tool-list-budget.test.ts@@ -4,7 +4,8 @@ import fullAgents from "./drivers/agents-catalog-goldens/full.tools-list.json" wimport { compactAdvertisedSchema } from "./advertised-schema.ts";import { cliDrops } from "./testing/cli-tool-drop.ts";import {- cutText, definitionBytes, withCompactSchemas, withDescriptionLevel, definitionListBytes, fitToolListToShare, PROTECTED_TOOLS, TOOL_DESCRIPTION_FLOOR, TOOL_DESCRIPTION_MIN, toolListShare, toolListShareProfile,+ ANTIGRAVITY_CLI_TOOL_BUDGET, ANTIGRAVITY_CLI_TOOL_LIMIT, COORDINATION_TOOLS, cutText, definitionBytes, fitToolListWithinShare, toolKeepRank, toolListLimit,+ withCompactSchemas, withDescriptionLevel, definitionListBytes, fitToolListToShare, PROTECTED_TOOLS, TOOL_DESCRIPTION_FLOOR, TOOL_DESCRIPTION_MIN, toolListShare, toolListShareProfile,toolsForShareProfile, toolsListResultForShareProfile, type ListedTool,} from "./tool-list-budget.ts";@@ -126,8 +127,8 @@ describe("fitting a list into its share", () => {expect(toolsListResultForShareProfile({ error: "x" }, toolListShareProfile(1))).toEqual({ error: "x" });const logged: string[] = [];const fitted = toolsListResultForShareProfile(result, toolListShareProfile(14_000), (line) => logged.push(line)) as { tools: ListedTool[] };- expect(names(fitted.tools)).toEqual(names(agents));- expect(logged).toEqual([expect.stringMatching(/^tool list is \d+ bytes at its shortest, \d+ over its 14000-byte share of the session's tool budget$/)]);+ expect(names(fitted.tools)).toEqual(names(fitToolListWithinShare(agents, 14_000).tools));+ expect(logged).toEqual([expect.stringMatching(/^tool list is over its 14000-byte share of the session's tool budget even at its shortest: left out \d+ tool\(s\) so the engine does not choose, \w+/)]);// The same list under the same share again, as every request of a turn builds it: the fitted list reused, no second line.expect(toolsForShareProfile(structuredClone(agents), toolListShareProfile(14_000), (line) => logged.push(line))).toBe(fitted.tools);expect(logged).toHaveLength(1);@@ -207,3 +208,30 @@ describe("fitting a list into its share", () => {});});});++describe("a list over its share even at its shortest", () => {+ const share = 14_000;++ it("leaves out tools itself, the least important first, never a coordination tool, until the CLI has nothing to drop", () => {+ const fitted = fitToolListWithinShare(agents, share);+ expect(fitted.left.length).toBeGreaterThan(0);+ expect(fitted.bytes).toBeLessThanOrEqual(toolListLimit(share));+ expect(cliDrops(fitted.tools, toolListLimit(share))).toEqual([]);+ for (const name of COORDINATION_TOOLS) expect(names(fitted.tools)).toContain(name);+ // A protected tool goes only once every other tool has.+ const keptPlain = fitted.tools.filter((tool) => toolKeepRank(tool.name) === 0);+ if (fitted.left.some((name) => PROTECTED_TOOLS.includes(name))) expect(keptPlain).toEqual([]);+ // What is kept is in the order given, and what is left out is named in that order too.+ expect(names(fitted.tools)).toEqual(names(agents).filter((name) => !fitted.left.includes(name)));+ expect(fitted.left).toEqual(names(agents).filter((name) => fitted.left.includes(name)));+ });++ it("leaves nothing out while it is within the CLI's own limit, and keeps the coordination tools at any share", () => {+ const shortest = fitToolListToShare(agents, 1).bytes;+ const near = Math.ceil((shortest * ANTIGRAVITY_CLI_TOOL_BUDGET) / ANTIGRAVITY_CLI_TOOL_LIMIT);+ expect(fitToolListToShare(agents, near).fits).toBe(false);+ expect(fitToolListWithinShare(agents, near).left).toEqual([]);+ const tiny = fitToolListWithinShare(agents, 1);+ expect(names(tiny.tools)).toEqual(names(agents).filter((name) => COORDINATION_TOOLS.includes(name)));+ });+});diff --git a/server/tool-list-budget.ts b/server/tool-list-budget.tsindex d162c462b9..e7c4900cde 100644--- a/server/tool-list-budget.ts+++ b/server/tool-list-budget.ts@@ -5,8 +5,10 @@// bytes, on 1.5.18 up to about 56,780, about 38 more per further tool. There is no limit for one tool: with many tools// the cut only looks like one, since every tool over some size goes. A session's servers share out// ANTIGRAVITY_CLI_TOOL_BUDGET and each fits its list into its share, least loss first: the schema compacted, then its-// annotations, shorter parameter descriptions, shorter tool descriptions, and last nested fields. No tool is left out,-// no name or required field changes, and every call is still checked against the tool's own full schema.+// annotations, shorter parameter descriptions, shorter tool descriptions, and last nested fields. Only a list that is over+// its share even then leaves tools out, and it chooses them itself, the least important first, so the CLI never drops one+// that the bot must keep. No name or required field changes, and every call is still checked against the tool's own full+// schema.import { compactAdvertisedSchema } from "./advertised-schema.ts";import { itemsOf, schemaBytes } from "./tool-schema-profile.ts";@@ -16,6 +18,16 @@ export type ListedTool = { name: string; description?: string; inputSchema?: unk/** Below the CLI's drop point, with room for its per-path overhead and the person's own servers. */export const ANTIGRAVITY_CLI_TOOL_BUDGET = 55_000;+/** The most a session's tools came to that the CLI kept whole in every measurement: one tool alone on 1.5.17 (56,608), more+ * with more tools. A list leaves tools out only past its share's part of this, so a session a little over the budget+ * loses nothing the CLI would have kept. */+export const ANTIGRAVITY_CLI_TOOL_LIMIT = 56_600;++/** What a list with `share` of ANTIGRAVITY_CLI_TOOL_BUDGET may come to before it leaves tools out. */+export function toolListLimit(share: number): number {+ return Math.floor((share * ANTIGRAVITY_CLI_TOOL_LIMIT) / ANTIGRAVITY_CLI_TOOL_BUDGET);+}+/** The value of OMB_TOOL_SCHEMA_PROFILE that gives a server its share of a session's budget, in bytes. */const SHARE_PREFIX = "listShare:";@@ -42,6 +54,16 @@ export function definitionListBytes(tools: readonly ListedTool[]): number {* fit these are made smaller still. */export const PROTECTED_TOOLS: readonly string[] = ["coordinate_bots", "start_thread", "show_html", "trigger", "memory_update", "attach_file"];+/** Tools a list never leaves out, however far over its share: a bot that loses them cannot reach its team or read the+ * rest of a long result. */+export const COORDINATION_TOOLS: readonly string[] = ["coordinate_bots", "assignment_status", "list_bots", "list_room_targets", "post_to_thread", "tool_result_read"];++/** The order a list over its share leaves tools out in: a lower rank first, Infinity never. */+export function toolKeepRank(name: string): number {+ if (COORDINATION_TOOLS.includes(name)) return Infinity;+ return PROTECTED_TOOLS.includes(name) ? 1 : 0;+}+/** Tool descriptions are cut to this many characters before any is cut further. */export const TOOL_DESCRIPTION_FLOOR = 120;@@ -195,9 +217,11 @@ function smallest<T extends ListedTool>(tool: T): T {return { ...tool, description, inputSchema: withTopLevelFields(tool.inputSchema) };}+const FLOOR_LEVEL: DescriptionLevel = { parameters: 0, tools: TOOL_DESCRIPTION_MIN, annotations: true, topLevelOnly: true };+/** What `tools` come to at the deepest cut there is, protected tools kept whole. */export function toolListFloorBytes(tools: readonly ListedTool[]): number {- return definitionListBytes(withDescriptionLevel(withCompactSchemas(tools), { parameters: 0, tools: TOOL_DESCRIPTION_MIN, annotations: true, topLevelOnly: true }));+ return definitionListBytes(withDescriptionLevel(withCompactSchemas(tools), FLOOR_LEVEL));}export interface FittedToolList<T> { tools: T[]; bytes: number; from: number; level: DescriptionLevel; fits: boolean }@@ -219,6 +243,39 @@ export function fitToolListToShare<T extends ListedTool>(tools: readonly T[], shreturn { tools: fitted, bytes: definitionListBytes(fitted), from, level, fits };}+export interface ToolListWithinShare<T> extends FittedToolList<T> {+ /** The names of the tools left out, in the order given. */+ left: string[];+}++/** `tools` fitted into `share` bytes as fitToolListToShare does; when even their shortest is over toolListLimit(share),+ * without the tools of lowest toolKeepRank, the largest first within a rank, until the rest is within it at its shortest.+ * The engine then has nothing to leave out itself. `left` is empty while the list is within that limit. */+export function fitToolListWithinShare<T extends ListedTool>(tools: readonly T[], share: number): ToolListWithinShare<T> {+ const whole = fitToolListToShare(tools, share);+ const limit = toolListLimit(share);+ if (whole.fits || whole.bytes <= limit) return { ...whole, left: [] };+ const floor = withDescriptionLevel(withCompactSchemas(tools), FLOOR_LEVEL).map((tool, index) => ({ index, bytes: definitionBytes(tool), rank: toolKeepRank(tool.name) }));+ let total = floor.reduce((sum, entry) => sum + entry.bytes, 0);+ const left = new Set<number>();+ for (const entry of floor.filter((candidate) => candidate.rank !== Infinity).sort((a, b) => a.rank - b.rank || b.bytes - a.bytes || a.index - b.index)) {+ if (total <= limit) break;+ left.add(entry.index);+ total -= entry.bytes;+ }+ const kept = fitToolListToShare(tools.filter((_, index) => !left.has(index)), share);+ return { ...kept, from: whole.from, left: tools.filter((_, index) => left.has(index)).map((tool) => tool.name) };+}++/** The log line for a list over its share, or undefined when it fit. */+export function overShareNote(fitted: ToolListWithinShare<ListedTool>, share: number): string | undefined {+ if (fitted.left.length) {+ return `tool list is over its ${share}-byte share of the session's tool budget even at its shortest: left out ${fitted.left.length} tool(s) so the engine does not choose, ${fitted.left.join(", ")}`+ + (fitted.bytes > toolListLimit(share) ? `; still ${fitted.bytes - share} bytes over` : "");+ }+ return fitted.fits ? undefined : `tool list is ${fitted.bytes} bytes at its shortest, ${fitted.bytes - share} over its ${share}-byte share of the session's tool budget`;+}+/** A tools/list `tools` array under OMB_TOOL_SCHEMA_PROFILE `profile`: fitted when the profile is a share, else as it came. */export function toolsForShareProfile<T extends ListedTool>(tools: readonly T[], profile: unknown, log?: (line: string) => void): readonly T[] {const share = toolListShare(profile);@@ -227,8 +284,9 @@ export function toolsForShareProfile<T extends ListedTool>(tools: readonly T[],const key = `${share}\0${JSON.stringify(tools)}`;const known = FITTED.get(key);if (known) return known as T[];- const fitted = fitToolListToShare(tools, share);- if (!fitted.fits) log?.(`tool list is ${fitted.bytes} bytes at its shortest, ${fitted.bytes - share} over its ${share}-byte share of the session's tool budget`);+ const fitted = fitToolListWithinShare(tools, share);+ const note = overShareNote(fitted, share);+ if (note) log?.(note);if (FITTED.size >= FITTED_KEPT) FITTED.delete(FITTED.keys().next().value!);FITTED.set(key, fitted.tools);return fitted.tools;diff --git a/server/tool-list-share.test.ts b/server/tool-list-share.test.tsindex abfecaa923..c16f2a2868 100644--- a/server/tool-list-share.test.ts+++ b/server/tool-list-share.test.ts@@ -5,7 +5,9 @@ import { describe, expect, it } from "vitest";import { createToolListNormalizer } from "./mcp-tool-schema.ts";import { workspaceAppsLikeCatalog } from "./testing/workspace-apps-like-catalog.ts";-import { definitionListBytes, type ListedTool } from "./tool-list-budget.ts";+import {+ ANTIGRAVITY_CLI_TOOL_BUDGET, ANTIGRAVITY_CLI_TOOL_LIMIT, definitionListBytes, fitToolListToShare, toolListLimit, type ListedTool,+} from "./tool-list-budget.ts";import {readRecordedToolList, TOOL_LIST_RECORD_ENV, TOOL_LIST_SHARE_ENV, toolsForSessionShare, toolsListResultForSessionShare,} from "./tool-list-share.ts";@@ -36,11 +38,22 @@ describe("a relayed server's share of the session's tool budget", () => {});});- it("says by how much a list is over its share at its shortest, and still lists every tool", () => {+ it("says by how much a list is over its share at its shortest, and lists every tool while it is within the CLI's own limit", () => {const logged: string[] = [];- const fitted = toolsForSessionShare(apps, { [TOOL_LIST_SHARE_ENV]: "5000" }, (line) => logged.push(line));+ const shortest = fitToolListToShare(apps as ListedTool[], 1).bytes;+ const share = Math.ceil((shortest * ANTIGRAVITY_CLI_TOOL_BUDGET) / ANTIGRAVITY_CLI_TOOL_LIMIT);+ const fitted = toolsForSessionShare(apps, { [TOOL_LIST_SHARE_ENV]: String(share) }, (line) => logged.push(line));expect(names(fitted)).toEqual(names(apps));- expect(logged).toEqual([expect.stringMatching(/^tool list is \d+ bytes at its shortest, \d+ over its 5000-byte share of the session's tool budget$/)]);+ expect(logged).toEqual([`tool list is ${shortest} bytes at its shortest, ${shortest - share} over its ${share}-byte share of the session's tool budget`]);+ });++ it("past that, leaves out its largest tools itself and names them, so the CLI drops none of another server's", () => {+ const logged: string[] = [];+ const fitted = toolsForSessionShare(apps, { [TOOL_LIST_SHARE_ENV]: "5000" }, (line) => logged.push(line)) as ListedTool[];+ expect(fitted.length).toBeLessThan(apps.length);+ expect(definitionListBytes(fitted)).toBeLessThanOrEqual(toolListLimit(5_000));+ expect(names(fitted)).toEqual(names(apps).filter((name) => names(fitted).includes(name)));+ expect(logged).toEqual([expect.stringMatching(/^tool list is over its 5000-byte share of the session's tool budget even at its shortest: left out \d+ tool\(s\) so the engine does not choose, [A-Z_]+/)]);});it("records the list it relays, before its share, for the next session to size", () => {diff --git a/server/tool-list-share.ts b/server/tool-list-share.tsindex f7c07b78b9..42c3f0c561 100644--- a/server/tool-list-share.ts+++ b/server/tool-list-share.ts@@ -1,11 +1,12 @@// A relayed MCP server's part of a session's tool budget, for the servers OpenMausBot relays but does not serve:// connected apps and the person's own servers. The session gives each relay its share in bytes and a file to record// the list it relays; the relay fits what it lists into the share, and the record sizes the share the next session-// gives it.+// gives it. A list over its share even at its shortest leaves out tools itself, so no relay takes the session past the+// CLI's budget and has the CLI drop another server's tools.import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";import { dirname } from "node:path";-import { fitToolListToShare, type ListedTool } from "./tool-list-budget.ts";+import { fitToolListWithinShare, overShareNote, type ListedTool } from "./tool-list-budget.ts";export const TOOL_LIST_SHARE_ENV = "OMB_TOOL_LIST_SHARE";export const TOOL_LIST_RECORD_ENV = "OMB_TOOL_LIST_RECORD";@@ -53,8 +54,9 @@ export function toolsForSessionShare(tools: readonly unknown[], env: Record<striif (!tools.every(isTool)) return [...tools];if (path) record(path, tools);if (share === undefined) return [...tools];- const fitted = fitToolListToShare(tools, share);- if (!fitted.fits) log?.(`tool list is ${fitted.bytes} bytes at its shortest, ${fitted.bytes - share} over its ${share}-byte share of the session's tool budget`);+ const fitted = fitToolListWithinShare(tools, share);+ const note = overShareNote(fitted, share);+ if (note) log?.(note);return fitted.tools;}