Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Defer all but a few agents tools on Claude turns
milind-sonic294c63257b3
diff --git a/evals/README.md b/evals/README.mdindex 07c56ca3aa..1bbe1eb983 100644--- a/evals/README.md+++ b/evals/README.md@@ -63,6 +63,12 @@ bridge, a shorter description, a removed built-in.Each case is one real turn on your account, so name the cases you need. It is closed unless `OMB_EVAL_LIVE=1`, never runs in CI, and its data folder is temporary. Add `OMB_AGENTS_TOOL_BRIDGE=1 OMB_EVAL_LIVE_PASS_ENV=OMB_AGENTS_TOOL_BRIDGE` to try the bridge. Only the scoring has an offline test.+On Claude with tool search on, a turn sends a few agents tools whole and the rest by name only, so the model has to look them up with ToolSearch. Ten cases that check it still finds them:++ --only remember-this,daily-automation,jobs-per-pull-request,publish-a-page,ask-me-which-day,which-triggers,ask-the-chief,show-a-chart,what-did-we-decide,tell-the-team++`--context` runs no model and prints the bytes a Claude turn sends of the agents tools up front, whole against deferred.+## Tier 3 — opt-in live-model smokeLive-model runs never execute by default: `pnpm eval --live` prints one skip line and exits 0 unless the gate is open.diff --git a/evals/tool-choice/cases.json b/evals/tool-choice/cases.jsonindex 883a885340..9929a3d248 100644--- a/evals/tool-choice/cases.json+++ b/evals/tool-choice/cases.json@@ -10,5 +10,9 @@{ "id": "ask-the-chief", "tools": ["coordinate_bots"], "text": "Frag MausBot, ob der Zugang zum Postfach schon hinterlegt ist.", "why": "Asked a teammate for a login." },{ "id": "give-a-password", "tools": ["request_credential"], "text": "I need to give you the mailbox password for [email protected] so you can read mail. How do I hand it over safely?", "why": "Had to hand over a secret." },{ "id": "log-in-for-me", "tools": ["request_sign_in", "fill_login"], "text": "Log in to bookkeeping.example.com for me and tell me when you're in.", "why": "Asked to sign in at a site." },- { "id": "remember-this", "tools": ["memory_update"], "text": "Remember that invoices always go to [email protected].", "why": "Asked to remember a fact." }+ { "id": "remember-this", "tools": ["memory_update"], "text": "Remember that invoices always go to [email protected].", "why": "Asked to remember a fact." },+ { "id": "daily-automation", "tools": ["trigger"], "text": "Every weekday at 8:00, send me a short summary of my unread email.", "why": "Asked for something that runs every day." },+ { "id": "jobs-per-pull-request", "tools": ["start_thread"], "text": "Open two separate jobs on yourself: one reviews pull request 12, the other pull request 13.", "why": "Asked for independent jobs, each its own thread." },+ { "id": "publish-a-page", "tools": ["publish_page", "publish_app"], "text": "Make a one-paragraph web page saying the office is closed on Friday and publish it to a link I can share.", "why": "Asked for a page at a public link." },+ { "id": "ask-me-which-day", "tools": ["ask_user", "create_options_card"], "text": "Before you book the call, ask me whether I prefer Tuesday or Thursday, with both as choices.", "why": "Asked to be asked, with options." }]diff --git a/evals/tool-choice/context.ts b/evals/tool-choice/context.tsnew file mode 100644index 0000000000..d03930716b--- /dev/null+++ b/evals/tool-choice/context.ts@@ -0,0 +1,27 @@+import { DEFER_TOOLS_ENV, claudeUpFrontBytes } from "../../server/drivers/agents-claude-defer.ts";+import { agentsToolList } from "../../server/drivers/agents-mcp.ts";++const BASE = { OMB_BOT_ID: "bot-context", OMB_CHIEF_OF_STAFF: "1", OMB_COMPUTER_SELECTION: "1" };+/** A Chief's direct chat with nothing extra, and with every switch the catalog has. */+export const CONTEXT_PROFILES: Record<string, Record<string, string>> = {+ default: BASE,+ fullest: {+ ...BASE, OMB_SKILL_AUTHORING_ENABLED: "1", OMB_SHARED_COMPUTERS_ENABLED: "1", OMB_VOICE_NOTES: "1", OMB_X_RESEARCH: "1", OMB_RESEARCH: "1",+ OMB_TEAM_PEOPLE: "1", OMB_IMAGE_GENERATION: "1", OMB_APP_HOSTING: "1",+ },+};++/** Bytes of the agents server a Claude turn sends before any search, every tool whole against all but a few deferred. */+export function contextSizes() {+ return Object.entries(CONTEXT_PROFILES).map(([profile, env]) => {+ const whole = agentsToolList(env).listed;+ const deferred = agentsToolList({ ...env, [DEFER_TOOLS_ENV]: "1" }).listed;+ return {+ profile,+ tools: whole.length,+ loaded: deferred.filter((tool) => !("_meta" in tool)).map((tool) => tool.name),+ before: claudeUpFrontBytes(whole),+ after: claudeUpFrontBytes(deferred),+ };+ });+}diff --git a/evals/tool-choice/run-tool-choice.ts b/evals/tool-choice/run-tool-choice.tsindex e85ce47e15..3c112b840e 100644--- a/evals/tool-choice/run-tool-choice.ts+++ b/evals/tool-choice/run-tool-choice.ts@@ -6,11 +6,13 @@//// Each case is one real model turn on your account: never in CI, closed unless OMB_EVAL_LIVE=1. For the bridge, add// OMB_AGENTS_TOOL_BRIDGE=1 OMB_EVAL_LIVE_PASS_ENV=OMB_AGENTS_TOOL_BRIDGE. Everything else is a temporary data folder.+// --context runs no model: it prints what a Claude turn sends of the agents tools up front, whole against deferred.import { mkdirSync, readFileSync, writeFileSync } from "node:fs";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import { loadLiveInstance } from "../live/run-live.ts";import { spawnLiveServer } from "../live/live-server.ts";+import { contextSizes } from "./context.ts";import { scoreCase, summarize, type CaseScore, type ToolChoiceCase } from "./score.ts";const HERE = dirname(fileURLToPath(import.meta.url));@@ -18,6 +20,13 @@ const HERE = dirname(fileURLToPath(import.meta.url));interface Row { id: string; score: CaseScore; calls: string[]; reply: string; costUsd?: number; inputTokens?: number; done: boolean }async function main(): Promise<void> {+ if (process.argv.includes("--context")) {+ for (const row of contextSizes()) {+ console.log(`${row.profile}: ${row.tools} tools; up front ${row.before.total} bytes whole, ${row.after.total} deferred `+ + `(${row.after.whole} for ${row.loaded.join(", ")}, ${row.after.deferred} of deferred names)`);+ }+ return;+ }if (process.env.OMB_EVAL_LIVE !== "1") {console.log("tool-choice eval: skipped (set OMB_EVAL_LIVE=1; each case is one real model turn)");return;diff --git a/evals/tool-choice/score.test.ts b/evals/tool-choice/score.test.tsindex 6f3a325875..c5a4f8908f 100644--- a/evals/tool-choice/score.test.ts+++ b/evals/tool-choice/score.test.ts@@ -1,5 +1,7 @@import { readFileSync } from "node:fs";import { describe, expect, it } from "vitest";+import { CLAUDE_ALWAYS_LOADED_TOOL_NAMES } from "../../server/drivers/agents-claude-defer.ts";+import { contextSizes } from "./context.ts";import { bareToolName, scoreCase, summarize, type ToolChoiceCase } from "./score.ts";describe("tool-choice scoring", () => {@@ -30,4 +32,11 @@ describe("tool-choice scoring", () => {expect(item.why.length, item.id).toBeGreaterThan(0);}});++ it("measures the deferred agents tools against the whole list, with no model", () => {+ for (const row of contextSizes()) {+ expect(row.after.total, row.profile).toBeLessThan(row.before.total / 5);+ expect(row.loaded.every((name) => CLAUDE_ALWAYS_LOADED_TOOL_NAMES.has(name)), row.profile).toBe(true);+ }+ });});diff --git a/server/drivers/agents-claude-defer.test.ts b/server/drivers/agents-claude-defer.test.tsnew file mode 100644index 0000000000..1b991c4224--- /dev/null+++ b/server/drivers/agents-claude-defer.test.ts@@ -0,0 +1,93 @@+import { spawn } from "node:child_process";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { WATCHER_OPTIONS_CARD_BOT_ID } from "../../shared/options-card.ts";+import { waitForExit } from "../testing/cleanup.ts";+import { TOOL_BRIDGE_ENV } from "./agents-bridge.ts";+import { ALWAYS_LOAD_META, CLAUDE_ALWAYS_LOADED_TOOL_NAMES, DEFER_TOOLS_ENV, claudeUpFrontBytes } from "./agents-claude-defer.ts";+import { agentsToolList } from "./agents-mcp.ts";++const PROXY_SOURCE = join(dirname(fileURLToPath(import.meta.url)), "agents-proxy.ts");+const BASE = { OMB_BOT_ID: "bot-defer", OMB_CHIEF_OF_STAFF: "1", OMB_COMPUTER_SELECTION: "1", OMB_SKILL_AUTHORING_ENABLED: "0", OMB_SHARED_COMPUTERS_ENABLED: "0", OMB_VOICE_NOTES: "0" };+/** The catalog wire test's default and fullest profiles. */+const PROFILES: Record<string, Record<string, string>> = {+ default: BASE,+ fullest: {+ ...BASE, OMB_SKILL_AUTHORING_ENABLED: "1", OMB_SHARED_COMPUTERS_ENABLED: "1", OMB_VOICE_NOTES: "1", OMB_X_RESEARCH: "1", OMB_RESEARCH: "1",+ OMB_TEAM_PEOPLE: "1", OMB_IMAGE_GENERATION: "1", OMB_APP_HOSTING: "1",+ },+};+const DEFER = { [DEFER_TOOLS_ENV]: "1" };++/** Bytes Claude Code sends up front for the agents server when the budget was last set; each may move at most 2%. */+const UP_FRONT_BASELINE: Record<string, { whole: number; deferred: number }> = {+ default: { whole: 4514, deferred: 1186 },+ fullest: { whole: 5308, deferred: 1494 },+};++const listed = (env: Record<string, string>) => agentsToolList(env).listed as Array<{ name: string; description: string; inputSchema: unknown; _meta?: Record<string, unknown> }>;+const marked = (tool: { _meta?: Record<string, unknown> }) => tool._meta?.[ALWAYS_LOAD_META] === false;++describe("agents tools deferred on a Claude turn", () => {+ it("marks every tool outside the always-loaded set, and nothing without the switch or behind the bridge", () => {+ for (const env of Object.values(PROFILES)) {+ const tools = listed({ ...env, ...DEFER });+ expect(tools.filter((tool) => !marked(tool)).map((tool) => tool.name).every((name) => CLAUDE_ALWAYS_LOADED_TOOL_NAMES.has(name))).toBe(true);+ expect(tools.filter(marked).length).toBeGreaterThan(40);+ expect(tools.find((tool) => tool.name === "list_bots")?._meta, "a deferred list_bots loses to Claude Code's ListAgents").toBeUndefined();+ expect(listed(env).some((tool) => tool._meta !== undefined)).toBe(false);+ expect(listed({ ...env, ...DEFER, [TOOL_BRIDGE_ENV]: "1" }).some((tool) => tool._meta !== undefined)).toBe(false);+ }+ });++ it("names only real catalog tools as always loaded", () => {+ const names = new Set([+ ...listed(PROFILES.fullest!).map((tool) => tool.name),+ ...listed({ ...BASE, OMB_BOT_ID: WATCHER_OPTIONS_CARD_BOT_ID }).map((tool) => tool.name),+ ]);+ expect([...CLAUDE_ALWAYS_LOADED_TOOL_NAMES].filter((name) => !names.has(name))).toEqual([]);+ });++ it("keeps what a Claude turn sends up front within its budget", () => {+ const measured = Object.fromEntries(Object.entries(PROFILES).map(([name, env]) => {+ const { whole, deferred } = claudeUpFrontBytes(listed({ ...env, ...DEFER }));+ return [name, { whole, deferred }];+ }));+ for (const [name, baseline] of Object.entries(UP_FRONT_BASELINE)) {+ for (const key of ["whole", "deferred"] as const) {+ const ratio = measured[name]![key] / baseline[key];+ expect(ratio, `${name} ${key}: ${measured[name]![key]} bytes against ${baseline[key]}`).toBeGreaterThanOrEqual(0.98);+ expect(ratio, `${name} ${key}: ${measured[name]![key]} bytes against ${baseline[key]}`).toBeLessThanOrEqual(1.02);+ }+ expect(measured[name]!.whole).toBeLessThan(8_000);+ }+ });++ it("puts the marks on the proxy's tools/list wire", async () => {+ const inherited = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("OMB_")));+ const child = spawn(process.execPath, [PROXY_SOURCE], {+ env: { ...inherited, OMB_HARNESS_URL: "http://127.0.0.1:9", OMB_COMMS_TOKEN: "unused", OMB_TURN_DEPTH: "0", ...BASE, ...DEFER },+ stdio: ["pipe", "pipe", "inherit"],+ });+ try {+ const line = await new Promise<string>((resolve, reject) => {+ let buffer = "";+ child.stdout.setEncoding("utf8");+ child.stdout.on("data", (chunk: string) => {+ buffer += chunk;+ const newline = buffer.indexOf("\n");+ if (newline !== -1) resolve(buffer.slice(0, newline));+ });+ child.on("error", reject);+ child.on("exit", (code) => reject(new Error(`agents proxy exited (${code}) before answering tools/list`)));+ child.stdin.write('{"jsonrpc":"2.0","id":1,"method":"tools/list"}\n');+ });+ const tools = (JSON.parse(line) as { result: { tools: Array<{ name: string; _meta?: Record<string, unknown> }> } }).result.tools;+ expect(tools.find((tool) => tool.name === "trigger")?._meta).toEqual({ [ALWAYS_LOAD_META]: false });+ expect(tools.find((tool) => tool.name === "memory_update")?._meta).toBeUndefined();+ } finally {+ await waitForExit(child, { signal: "SIGTERM" });+ }+ });+});diff --git a/server/drivers/agents-claude-defer.ts b/server/drivers/agents-claude-defer.tsnew file mode 100644index 0000000000..b3cc7d4d69--- /dev/null+++ b/server/drivers/agents-claude-defer.ts@@ -0,0 +1,41 @@+// Claude Code 2.1.285 and later keep a tool behind its ToolSearch when the server lists it with+// `_meta["anthropic/alwaysLoad"]: false`, even though its --mcp-config server is `alwaysLoad`; the server-level flag+// still makes the CLI connect the server before the first request (checked on 2.1.321). An older CLI ignores the mark+// and loads every tool, and with tool search off every tool loads whatever the mark says.++/** The proxy's switch, set by the Claude driver: "1" marks every tool outside CLAUDE_ALWAYS_LOADED_TOOL_NAMES deferred. */+export const DEFER_TOOLS_ENV = "OMB_AGENTS_DEFER_TOOLS";++/** Sent whole on every Claude request: tools most turns call, or must call without a search first. list_bots stays+ * because a deferred list_bots loses to Claude Code's own ListAgents when the bot inherits this machine's setup. */+export const CLAUDE_ALWAYS_LOADED_TOOL_NAMES: ReadonlySet<string> = new Set([+ "tool_result_read",+ "list_bots",+ "attach_file",+ "memory_update",+ "message_person",+ "send_voice_note",+ "create_options_card",+]);++export const ALWAYS_LOAD_META = "anthropic/alwaysLoad";++/** `tools` with every tool outside the always-loaded set marked deferred. */+export function withDeferMarks<Tool extends { name: string; _meta?: Record<string, unknown> }>(tools: readonly Tool[]): Tool[] {+ return tools.map((tool) => CLAUDE_ALWAYS_LOADED_TOOL_NAMES.has(tool.name)+ ? tool+ : { ...tool, _meta: { ...tool._meta, [ALWAYS_LOAD_META]: false } });+}++/** What Claude Code 2.1.321 sends up front for these tools/list entries: a loaded tool whole, as+ * {name, description, input_schema}, and a deferred one as its name on a line of a reminder. */+export function claudeUpFrontBytes(tools: ReadonlyArray<{ name: string; description?: string; inputSchema?: unknown; _meta?: Record<string, unknown> }>, prefix = "mcp__agents__") {+ let whole = 0;+ let deferred = 0;+ for (const tool of tools) {+ const name = `${prefix}${tool.name}`;+ if (tool._meta?.[ALWAYS_LOAD_META] === false) deferred += Buffer.byteLength(`${name}\n`, "utf8");+ else whole += Buffer.byteLength(JSON.stringify({ name, description: tool.description, input_schema: tool.inputSchema }), "utf8");+ }+ return { whole, deferred, total: whole + deferred };+}diff --git a/server/drivers/agents-mcp.ts b/server/drivers/agents-mcp.tsindex fabf19c7d8..7ab285b3b7 100644--- a/server/drivers/agents-mcp.ts+++ b/server/drivers/agents-mcp.ts@@ -4,6 +4,7 @@import { resolveAgentsCall } from "../../shared/agents-tool-names.ts";import { TOOL_BRIDGE_ENV, createToolBridge } from "./agents-bridge.ts";import { availableTools, catalogProfileFromEnv } from "./agents-catalog.ts";+import { DEFER_TOOLS_ENV, withDeferMarks } from "./agents-claude-defer.ts";import { callTool, capResult, toolCallContextFromEnv } from "./agents-call.ts";import { sendToolReceipt } from "./agents-timing.ts";import type { Json } from "./agents-client.ts";@@ -13,7 +14,7 @@ import { capToolListResult, toolLimitFromEnv } from "../tool-count-limit.ts";export function agentsToolList(env: NodeJS.ProcessEnv) {const available = availableTools(catalogProfileFromEnv(env));const bridge = env[TOOL_BRIDGE_ENV] === "1" ? createToolBridge(available) : undefined;- return { available, bridge, listed: bridge ? bridge.listed : available };+ return { available, bridge, listed: bridge ? bridge.listed : env[DEFER_TOOLS_ENV] === "1" ? withDeferMarks(available) : available };}export function agentsMcp(env: NodeJS.ProcessEnv): (msg: Json) => Promise<Json | undefined> {diff --git a/server/drivers/claude-tool-search.ts b/server/drivers/claude-tool-search.tsindex 923c085a42..d5cb8a52dd 100644--- a/server/drivers/claude-tool-search.ts+++ b/server/drivers/claude-tool-search.ts@@ -11,11 +11,13 @@// over its own process environment, so a value in the project's or the person's .claude settings// would beat one set on the process; settings passed with --settings beat both.//-// OpenMausBot's own small servers stay loaded (`alwaysLoad` in claude.ts): `ogb` (approvals and-// questions) and `agents` (bots, rooms, jobs), plus the browser when the turn plans to browse.+// OpenMausBot's own servers stay `alwaysLoad` (claude.ts), so the CLI connects them before the first request:+// `ogb` (approvals and questions), `agents` (bots, rooms, jobs) and the browser when the turn plans to browse. With+// tool search on, `agents` sends only a few tools whole and marks the rest deferred (agents-claude-defer.ts).import { readFileSync, statSync } from "node:fs";import { homedir } from "node:os";import { basename, dirname, join, resolve } from "node:path";+import { DEFER_TOOLS_ENV } from "./agents-claude-defer.ts";/** Only a regular file this small is read: a FIFO would hold the server's one thread. */const FILE_MAX_BYTES = 1024 * 1024;@@ -116,3 +118,21 @@ export function claudeToolSearchSetting(cwd: string, env: NodeJS.ProcessEnv): st}return claudeToolSearchValue(env.ENABLE_TOOL_SEARCH);}++/** Claude Code 2.1.321's reading of a turn's ENABLE_TOOL_SEARCH: off for auto:N with N of 100 or more, and for a+ * false-like word; on for anything else. */+export function claudeToolSearchOn(value: string): boolean {+ if (value.startsWith("auto:")) {+ const percent = claudeInteger(value.slice("auto:".length));+ return Number.isNaN(percent) || percent < 100;+ }+ return !["0", "false", "no", "off"].includes(value.trim().toLowerCase());+}++/** The agents server as a Claude turn mounts it: always connected before the first request, and with tool search on,+ * all but a few of its tools deferred. */+export function claudeAgentsMount<Server extends { env?: Record<string, string> }>(server: Server, toolSearch: string): Server & { alwaysLoad: true } {+ return claudeToolSearchOn(toolSearch)+ ? { ...server, env: { ...server.env, [DEFER_TOOLS_ENV]: "1" }, alwaysLoad: true }+ : { ...server, alwaysLoad: true };+}diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.tsindex a2a6d25095..f5438be081 100644--- a/server/drivers/claude.test.ts+++ b/server/drivers/claude.test.ts@@ -40,6 +40,7 @@ import { ephemeralWorkspaceTokenPath } from "../workspace-backup-policy.ts";import { registerPathDir, resetPathCacheForTests } from "../env-path.ts";import * as procs from "../procs.ts";import * as localInject from "./local-inject.ts";+import { DEFER_TOOLS_ENV } from "./agents-claude-defer.ts";const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-claude-cli.ts");const dumpedPid = (dump: string): number => JSON.parse(readFileSync(dump, "utf8")).pid;@@ -1350,8 +1351,9 @@ describe("ClaudeDriver turns (fake CLI)", () => {expect(seen.mcpConfig.mcpServers.agents).toMatchObject({alwaysLoad: true,args: ["/fake/agents-proxy.js"],- env: { OMB_BOT_ID: "b1", OMB_COMMS_TOKEN: "tok" },+ env: { OMB_BOT_ID: "b1", OMB_COMMS_TOKEN: "tok", [DEFER_TOOLS_ENV]: "1" },});+ expect(seen.env.CLAUDE_CODE_DISABLE_CRON, "a deferred trigger must not lose to CronCreate").toBe("1");expect(JSON.stringify(seen.argv)).not.toContain("tok");const allowed = seen.argv[seen.argv.indexOf("--allowedTools") + 1];expect(allowed).toContain("mcp__agents");@@ -2027,18 +2029,20 @@ describe("ClaudeDriver turns (fake CLI)", () => {const turn = async (text: string, cwd?: string) => {const { turnId } = await instance.adapter.sendTurn({threadId: "t-tool-search-off", text, ...(cwd ? { cwd } : {}),- integrations: { composio: { command: process.execPath, args: ["/fake/composio.js"], env: {} } },+ integrations: { composio: { command: process.execPath, args: ["/fake/composio.js"], env: {} }, agents: { command: process.execPath, args: ["/fake/agents.js"], env: {} } },});await recorder.until((e) => e.type === "turn.completed" && e.turnId === turnId);- return JSON.parse(readFileSync(dump, "utf8")) as { pid: number; settings: { env: Record<string, string> } };+ return JSON.parse(readFileSync(dump, "utf8")) as { pid: number; settings: { env: Record<string, string> }; mcpConfig: { mcpServers: Record<string, { alwaysLoad?: boolean; env?: Record<string, string> }> } };};// The turn leaves the account's settings out (--setting-sources project), so the choice travels in --settings.const off = await turn("hi");expect(off.settings.env.ENABLE_TOOL_SEARCH).toBe("false");+ expect(off.mcpConfig.mcpServers.agents, "without tool search every agents tool loads whole, as before").toEqual({ command: process.execPath, args: ["/fake/agents.js"], env: {}, alwaysLoad: true });writeFileSync(path, JSON.stringify({ env: { ENABLE_TOOL_SEARCH: "auto" } }));const on = await turn("again");expect(on.settings.env.ENABLE_TOOL_SEARCH).toBe("true");+ expect(on.mcpConfig.mcpServers.agents).toEqual({ command: process.execPath, args: ["/fake/agents.js"], env: { [DEFER_TOOLS_ENV]: "1" }, alwaysLoad: true });expect(on.pid).not.toBe(off.pid);// The bot's project settings beat the account's.const project = join(scratch, "project-off");diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 35786bd2d8..ecd034448e 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -18,7 +18,7 @@ import { botSettingsFor, folderSettingsEnv, withBotSettings } from "./claude-botimport { claudeBilling, claudeCallUsage } from "./claude-billing.ts";import { claudeAuthFailure, claudeAuthRecovery, claudeOAuthExpired } from "./claude-auth-recovery.ts"; import { AWS_CREDENTIAL_ENV_KEYS, bedrockResultError, withBedrockCredentialError } from "./claude-bedrock-aws.ts";import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, currentEngineCatalog, endpointModelCatalog, withCliVersionGate } from "./claude-model-extras.ts";-import { claudeToolSearchSetting } from "./claude-tool-search.ts"; import { claudeDisabledNativeSkillRules, unusableBuiltIns } from "./claude-unusable-tools.ts"; import { EMAIL_READ_TOOL_NAMES } from "../../shared/email.ts";+import { claudeAgentsMount, claudeToolSearchSetting } from "./claude-tool-search.ts"; import { claudeDisabledNativeSkillRules, unusableBuiltIns } from "./claude-unusable-tools.ts"; import { EMAIL_READ_TOOL_NAMES } from "../../shared/email.ts";import { claudeElicitations } from "./claude-elicitation.ts"; import { spawnContractDiff } from "./claude-spawn-contract.ts";import { readCostHistory, recordCostState } from "./claude-cost-history.ts";import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";@@ -1082,10 +1082,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {};if (!controlsHost) allowed.push("mcp__computer");}+ const cwd = turn.cwd ?? homedir(), toolSearch = claudeToolSearchSetting(cwd, turnEnvironment);// Pre-allowed, or the CLI's own ListAgents look-alike shadows it.if (turn.integrations?.agents) {- // Claude waits for always-loaded tools before building the prompt.- mcpServers.agents = { ...turn.integrations.agents, alwaysLoad: true };+ mcpServers.agents = claudeAgentsMount(turn.integrations.agents, toolSearch);allowed.push("mcp__agents");}if (turn.integrations?.phone) {@@ -1173,16 +1173,14 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {// in the packaged app process.execPath is Electron — run the helper as nodeif (process.versions.electron) env.ELECTRON_RUN_AS_NODE = "1";}- const cwd = turn.cwd ?? homedir();// Every MCP server without alwaysLoad loads on demand behind ToolSearch (claude-tool-search.ts).- const toolSearch = claudeToolSearchSetting(cwd, env);const own: Record<string, unknown> = { ...authSettings, env: { ...authSettings.env, ENABLE_TOOL_SEARCH: toolSearch, ...(isolated ? CLAUDE_OWN_MEMORY_OFF : {}) } };// Project-only settings still find the personal memory via ancestors when the bot lives under HOME.if (isolated) own.claudeMdExcludes = [join(homedir(), ".claude", "CLAUDE.md")];if (hooks) own.hooks = claudeHookSettings(HOOK_HELPER_PATH);if (turn.guestConfined) own.permissions = GUEST_CLAUDE_PERMISSIONS;- // Approvals and browser credentials expire at the turn boundary; native background workers must not outlive it.- env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS = "1";+ // Approvals and browser credentials expire at the turn boundary; native background workers and cron jobs must not outlive it.+ env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS = env.CLAUDE_CODE_DISABLE_CRON = "1";// Never for a guest: --restricted leaves project settings out, and a hook is a command. The MCP output limit comes after, so one the bot set there is kept.const botSettings = turn.guestConfined ? {} : botSettingsFor(turn.botSettingsFile, cwd, env); limitUngatedOutput(env, mcpServers, botOwned, turn.integrations?.customResultBudgets, (botSettings.env as Record<string, unknown> | undefined)?.MAX_MCP_OUTPUT_TOKENS ?? (turn.guestConfined ? undefined : folderSettingsEnv(cwd, "MAX_MCP_OUTPUT_TOKENS", projectSettingsOnly)));const settings = withBotSettings(botSettings, own);diff --git a/server/mcp-gate.test.ts b/server/mcp-gate.test.tsindex c511a7cb3e..a41c3b6fba 100644--- a/server/mcp-gate.test.ts+++ b/server/mcp-gate.test.ts@@ -420,6 +420,13 @@ createInterface({ input: process.stdin }).on("line", (line) => {expect(JSON.parse(await nextLine()).result).toEqual(catalog);});+ it("keeps each listed tool's _meta through a tool selection, so a deferred tool stays deferred", async () => {+ const read = { name: "read", inputSchema: { type: "object" }, _meta: { "anthropic/alwaysLoad": false } };+ start({ tools: [read, { name: "write", inputSchema: { type: "object" } }] }, selected, LISTING_UPSTREAM);+ send({ jsonrpc: "2.0", id: 1, method: "tools/list" });+ expect(JSON.parse(await nextLine()).result).toEqual({ tools: [read] });+ });+describe("shaping an oversized result", () => {const products = Array.from({ length: 300 }, (_, i) => ({ id: `p${i}`, name: `Bar ${i}`, price: 100 + i, blurb: "x".repeat(300) }));const full = JSON.stringify({ nextOffset: "1", products });diff --git a/server/turn-prompt-budget.test.ts b/server/turn-prompt-budget.test.tsnew file mode 100644index 0000000000..10364dc452--- /dev/null+++ b/server/turn-prompt-budget.test.ts@@ -0,0 +1,95 @@+// Pins the bytes of OpenMausBot's own prompt text a turn carries: the fixed sections of a bot's system prompt, what a+// Claude turn appends with --append-system-prompt-file, and what a Codex turn sets as developer instructions. Each may+// move at most 2% either way (lower a number to lock in a win); a bigger change moves its baseline by hand.+import { describe, expect, it } from "vitest";+import { chiefOfStaffSystemPrompt } from "./chief-of-staff.ts";+import { codexDeveloperInstructions, syncCodexInstructions } from "./drivers/codex-instructions.ts";+import { volatileContextNote, withVolatileNote } from "./drivers/prompt-split.ts";+import { meetingsUnavailablePrompt } from "./meetings/prompt.ts";+import { REPLY_HABITS_PROMPT } from "./reply-habits.ts";+import { setupSystemPrompt } from "./setup-mode.ts";+import {+ AGENTS_TOOL_BRIDGE_PROMPT, CREDENTIAL_PROMPT, PROFILE_PROMPT, SIGN_IN_PROMPT, TEAM_MEMORY_PROMPT, TRIGGER_PROMPT, botPersona, buildSystemPrompt,+ computerPrompt, longCommandsPrompt, type ComputerPromptKind, type PromptPart,+} from "./system-prompt.ts";++const BOT = { id: "bot-budget", name: "Kiwi" };++/** The fixed parts every direct chat with the agents tools carries, in the order the harness builds them. */+function directChatParts(setup: boolean): PromptPart[] {+ return [+ { id: "setup", label: "Setup", text: setupSystemPrompt(setup, { skills: true, connectedApps: { state: "available" } }) },+ { id: "meetings", label: "Meetings", text: meetingsUnavailablePrompt({ agentsTools: true, cloudComputer: false }) },+ { id: "credential", label: "Credentials", text: CREDENTIAL_PROMPT },+ { id: "routine", label: "Triggers", text: TRIGGER_PROMPT },+ { id: "profile", label: "Profile changes", text: PROFILE_PROMPT },+ { id: "team-memory", label: "Team memory", text: TEAM_MEMORY_PROMPT },+ ];+}++const KINDS: ComputerPromptKind[] = ["vm-private", "vm-shared", "box", "vps", "local"];++async function measured(): Promise<Record<string, number>> {+ const bytes = (text: string) => Buffer.byteLength(text, "utf8");+ const chat = buildSystemPrompt(botPersona(BOT), "", directChatParts(false));+ const setup = buildSystemPrompt(botPersona(BOT), "", directChatParts(true));+ const chief = chiefOfStaffSystemPrompt(BOT.id, [{ ...BOT, chiefOfStaff: true }] as never, true, undefined, [] as never);+ let resumed = "";+ await syncCodexInstructions("budget", "native-budget", chat.stable, "", true, async (_method, params) => {+ resumed = (params as { items: Array<{ content: Array<{ text: string }> }> }).items[0]!.content[0]!.text;+ return {};+ });+ return {+ "reply-habits": bytes(REPLY_HABITS_PROMPT),+ "tool-bridge": bytes(AGENTS_TOOL_BRIDGE_PROMPT),+ "sign-in": bytes(SIGN_IN_PROMPT),+ "chief-of-staff": bytes(chief),+ ...Object.fromEntries(directChatParts(true).map((part) => [part.id, bytes(part.text)])),+ ...Object.fromEntries(KINDS.map((kind) => [`computer:${kind}`, bytes(computerPrompt(kind) + longCommandsPrompt(kind))])),+ "claude:direct-chat": bytes(chat.stable),+ "claude:setup-chat": bytes(setup.stable),+ "claude:volatile-note": bytes(withVolatileNote("", "x", true)) - 1,+ "codex:direct-chat": bytes(codexDeveloperInstructions({}, chat.stable)),+ "codex:setup-chat": bytes(codexDeveloperInstructions({}, setup.stable)),+ "codex:resumed-instructions": bytes(resumed) - bytes(chat.stable),+ "codex:volatile-note": bytes(volatileContextNote("x", false)) - 1,+ };+}++/** Bytes when the budget was last set. */+const PROMPT_BUDGET_BASELINE: Record<string, number> = {+ "reply-habits": 2855,+ "tool-bridge": 593,+ "sign-in": 2552,+ "chief-of-staff": 4975,+ "setup": 2396,+ "meetings": 300,+ "credential": 1027,+ "routine": 3367,+ "profile": 1016,+ "team-memory": 286,+ "computer:vm-private": 5783,+ "computer:vm-shared": 5778,+ "computer:box": 4382,+ "computer:vps": 5026,+ "computer:local": 5335,+ "claude:direct-chat": 8895,+ "claude:setup-chat": 11291,+ "claude:volatile-note": 178,+ "codex:direct-chat": 8895,+ "codex:setup-chat": 11291,+ "codex:resumed-instructions": 213,+ "codex:volatile-note": 97,+};++describe("OpenMausBot's prompt text per turn", () => {+ it("stays within its pinned budget", async () => {+ const now = await measured();+ expect(Object.keys(now).sort()).toEqual(Object.keys(PROMPT_BUDGET_BASELINE).sort());+ for (const [name, baseline] of Object.entries(PROMPT_BUDGET_BASELINE)) {+ const ratio = now[name]! / baseline;+ expect(ratio, `${name}: ${now[name]} bytes against ${baseline}`).toBeGreaterThanOrEqual(0.98);+ expect(ratio, `${name}: ${now[name]} bytes against ${baseline}`).toBeLessThanOrEqual(1.02);+ }+ });+});