Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Fewer tokens per Claude request: defer more tools, Data guide only where used, run-specific text out of the cached prompt (#6200)
Milind Sonib945b7b98d83
diff --git a/docs/agents-tool-bridge.md b/docs/agents-tool-bridge.mdindex 9c8a3d60e5..e1aa009faa 100644--- a/docs/agents-tool-bridge.md+++ b/docs/agents-tool-bridge.md@@ -99,6 +99,10 @@ one line is logged naming the kind of error and nothing of what was read.Claude Code is not bridged when any of these holds:+- Its tool search is on (the default): the agents server then sends a few tools+ whole and the rest as names, which costs less than the bridge. For a proxy or+ model without tool search, set `ENABLE_TOOL_SEARCH=false` in the instance's+ environment to get the bridge back.- The bot inherits this machine's own Claude Code setup(`OMB_CLAUDE_INHERIT_USER_CONFIG=1`, or **Also use my Claude Code MCPservers**).diff --git a/evals/tool-choice/score.test.ts b/evals/tool-choice/score.test.tsindex c5a4f8908f..8057eb7aed 100644--- a/evals/tool-choice/score.test.ts+++ b/evals/tool-choice/score.test.ts@@ -1,6 +1,6 @@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 { CLAUDE_CHIEF_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";@@ -36,7 +36,7 @@ describe("tool-choice scoring", () => {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);+ expect(row.loaded.every((name) => CLAUDE_CHIEF_ALWAYS_LOADED_TOOL_NAMES.has(name)), row.profile).toBe(true);}});});diff --git a/scripts/control-omb.ts b/scripts/control-omb.tsindex a164e20e26..887219f2d4 100644--- a/scripts/control-omb.ts+++ b/scripts/control-omb.ts@@ -184,6 +184,8 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, datafor (const key of ["OMB_WARM_SUMMARY_TIME_SCALE", "OMB_WARM_SUMMARY"]) if (parentEnv[key]) childEnv[key] = parentEnv[key];// A headless server's usage caps (server/usage-caps.ts).for (const key of ["OMB_USAGE_CAP_DAILY_USD", "OMB_USAGE_CAP_MONTHLY_USD", "OMB_USAGE_CAP_DAILY_TOKENS", "OMB_USAGE_CAP_MONTHLY_TOKENS", "OMB_USAGE_CAP_STOPS"]) if (parentEnv[key]) childEnv[key] = parentEnv[key];+ // Claude Code's tool search (server/drivers/claude-tool-search.ts): a test turns it off to see a bridged Claude turn.+ if (parentEnv.ENABLE_TOOL_SEARCH) childEnv.ENABLE_TOOL_SEARCH = parentEnv.ENABLE_TOOL_SEARCH;// A loopback fake only: the key never reaches a real provider.const liveUrl = parentEnv.OMB_OPENAI_LIVE_URL?.trim() ?? "";if (/^http:\/\/127\.0\.0\.1:\d{1,5}$/.test(liveUrl)) {diff --git a/server/agents-bridge-switch.test.ts b/server/agents-bridge-switch.test.tsindex 7a3af60945..abe3935de5 100644--- a/server/agents-bridge-switch.test.ts+++ b/server/agents-bridge-switch.test.ts@@ -45,8 +45,8 @@ const folder = () => { const made = mkdtempSync(join(tmpdir(), "omb-bridge-switcafterAll(async () => { for (const made of folders) await removeTempDir(made); });/** A machine with no Claude settings anywhere. */const HOST: EngineHost = { home: folder(), managedPolicyFiles: [join(folder(), "managed-settings.json")] };-/** An engine the bridge is applied on: a current Claude CLI in a folder with no settings of its own. */-const CLAUDE: BridgeEngine = { driverKind: "claudeAgent", version: "2.1.232 (Claude Code)", cwd: folder() };+/** An engine the bridge is applied on: a current Claude CLI in a folder with no settings of its own, tool search off. */+const CLAUDE: BridgeEngine = { driverKind: "claudeAgent", version: "2.1.232 (Claude Code)", cwd: folder(), environment: { ENABLE_TOOL_SEARCH: "false" } };const agentsToolBridgeEnv = (...args: Parameters<typeof decide> extends [infer A, infer B, infer C, ...unknown[]] ? [A, B, C, NodeJS.ProcessEnv?, EngineHost?] : never) =>decide(args[0], args[1], args[2], args[3] ?? {}, args[4] ?? HOST);const agentsToolBridgeRefusal = (...args: Parameters<typeof refusal> extends [infer A, infer B, infer C, ...unknown[]] ? [A, B, C, NodeJS.ProcessEnv?, EngineHost?] : never) =>@@ -159,12 +159,39 @@ describe("which engines a turn is bridged on", () => {});describe("Claude Code's exceptions", () => {+ it("is not bridged while Claude Code's tool search defers the agents tools, whatever the switch says", () => {+ const searching: BridgeEngine = { ...CLAUDE, environment: {} };+ const deferred = "Claude Code defers the agents tools on this turn";+ // tool search is on unless something turns it off, so the saved switch and the operator's override both give way+ expect(agentsToolBridgeRefusal(ON, bot, searching, {})).toBe(deferred);+ expect(agentsToolBridgeRefusal({}, bot, searching, { OMB_AGENTS_TOOL_BRIDGE: "1" })).toBe(deferred);+ expect(agentsToolBridgeRefusal(ON, bot, { ...CLAUDE, environment: { ENABLE_TOOL_SEARCH: "auto" } }, {})).toBe(deferred);+ // the server's environment counts as the driver reads it, under the instance's own+ expect(agentsToolBridgeEnv(ON, bot, searching, { ENABLE_TOOL_SEARCH: "false" })).toEqual(on);+ expect(agentsToolBridgeEnv(ON, bot, { ...CLAUDE, environment: { ENABLE_TOOL_SEARCH: "true" } }, { ENABLE_TOOL_SEARCH: "false" })).toEqual(off);+ // and so do the launch folder's and the person's own Claude settings+ const cwd = folder();+ settings(join(cwd, ".claude", "settings.json"), { env: { ENABLE_TOOL_SEARCH: "false" } });+ expect(agentsToolBridgeEnv(ON, bot, { ...searching, cwd }, {})).toEqual(on);+ const home = folder();+ settings(join(home, ".claude", "settings.json"), { env: { ENABLE_TOOL_SEARCH: "0" } });+ expect(agentsToolBridgeEnv(ON, bot, searching, {}, { ...HOST, home })).toEqual(on);+ const configDir = folder();+ settings(join(configDir, "settings.json"), { env: { ENABLE_TOOL_SEARCH: "off" } });+ expect(agentsToolBridgeEnv(ON, bot, { ...searching, config: { configDir } }, {})).toEqual(on);+ // a model on this machine still gets the bridge by default: it reads the whole list on every turn+ const local = { id: "bot-local", modelSelection: { model: "ollama::qwen3.5:4b" } };+ expect(agentsToolBridgeRefusal({}, local, searching, {})).toBeNull();+ // another engine is not Claude Code's tool search+ expect(agentsToolBridgeEnv(ON, bot, { driverKind: "openai-compat" }, {})).toEqual(on);+ });+it("is not bridged when the bot inherits this machine's own Claude Code setup", () => {// settings the harness never sees may deny an agents tool by nameexpect(agentsToolBridgeEnv(ON, bot, CLAUDE, { OMB_CLAUDE_INHERIT_USER_CONFIG: "1" })).toEqual(off);- expect(agentsToolBridgeEnv(ON, bot, { ...CLAUDE, environment: { OMB_CLAUDE_INHERIT_USER_CONFIG: "1" } }, {})).toEqual(off);+ expect(agentsToolBridgeEnv(ON, bot, { ...CLAUDE, environment: { ...CLAUDE.environment, OMB_CLAUDE_INHERIT_USER_CONFIG: "1" } }, {})).toEqual(off);// the instance's environment is laid over the server's, as the driver lays it- expect(agentsToolBridgeEnv(ON, bot, { ...CLAUDE, environment: { OMB_CLAUDE_INHERIT_USER_CONFIG: "0" } }, { OMB_CLAUDE_INHERIT_USER_CONFIG: "1" })).toEqual(on);+ expect(agentsToolBridgeEnv(ON, bot, { ...CLAUDE, environment: { ...CLAUDE.environment, OMB_CLAUDE_INHERIT_USER_CONFIG: "0" } }, { OMB_CLAUDE_INHERIT_USER_CONFIG: "1" })).toEqual(on);// and the person's own Claude Code MCP servers are part of that setupexpect(agentsToolBridgeEnv({ features: { agentsToolBridge: true, claudeUserMcp: true } }, bot, CLAUDE, {})).toEqual(off);expect(agentsToolBridgeEnv({ features: { agentsToolBridge: true, claudeUserMcp: false } }, bot, CLAUDE, {})).toEqual(on);@@ -840,11 +867,15 @@ describe("the prompt of a bridged turn", () => {expect(AGENTS_TOOL_BRIDGE_PROMPT).not.toMatch(/\n/);});- it("sits in the stable half, so a warm engine is not relaunched by it turn after turn", () => {+ it("rides the volatile half, so a bot's bridged and unbridged runs share one cached prefix", () => {const first = buildSystemPrompt("You are Kiwi.", "Be brief.", parts, bridged);+ const unbridged = buildSystemPrompt("You are Kiwi.", "Be brief.", parts, { env: { OMB_AGENTS_TOOL_BRIDGE: "0" } });const later = buildSystemPrompt("You are Kiwi.", "Be brief.", parts.map((part) => part.id === "memory" ? { ...part, text: "\nMEMORY: the deploy script moved to tools/." } : part), bridged);- expect(first.stable).toContain(AGENTS_TOOL_BRIDGE_PROMPT);- expect(first.volatile).not.toContain(FIND_TOOL);+ expect(first.volatile).toContain(AGENTS_TOOL_BRIDGE_PROMPT);+ expect(first.stable).not.toContain(FIND_TOOL);+ expect(first.stable).toBe(unbridged.stable);+ // ahead of every other volatile section, as it sits right after the soul in the whole prompt+ expect(first.volatile.startsWith(AGENTS_TOOL_BRIDGE_PROMPT)).toBe(true);expect(later.stable).toBe(first.stable);expect(later.volatile).not.toBe(first.volatile);// and it is the same text for every bot and every turn that has itdiff --git a/server/agents-bridge-switch.ts b/server/agents-bridge-switch.tsindex fa70eaa6f5..fc1d77dbf2 100644--- a/server/agents-bridge-switch.ts+++ b/server/agents-bridge-switch.ts@@ -12,7 +12,8 @@ import { bridgedCallName } from "./agents-bridge-names.ts";import { TOOL_BRIDGE_ENV } from "./drivers/agents-bridge.ts";import { decodeInjectId } from "./drivers/local-inject.ts";import { onThisNetwork } from "./drivers/openai-compat.ts";-import { claudeCliSupports, parseClaudeCliVersion } from "./drivers/claude.ts";+import { claudeCliSupports, parseClaudeCliVersion, resolveClaudeConfigDir } from "./drivers/claude.ts";+import { claudeToolSearchOn, claudeToolSearchSetting } from "./drivers/claude-tool-search.ts";import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts";export { TOOL_BRIDGE_ENV };@@ -27,7 +28,8 @@ export const AGENTS_PROXY_ENV = { ...AGENTS_NODE_FLAG, [TOOL_BRIDGE_ENV]: "0" }type BridgeConfig = { features?: { agentsToolBridge?: boolean; claudeUserMcp?: boolean } };/** The workspace switch: `{"features": {"agentsToolBridge": true}}` in ~/.openmausbot/config.json, or- * OMB_AGENTS_TOOL_BRIDGE set to exactly "1" or "0", which wins over the saved setting. */+ * OMB_AGENTS_TOOL_BRIDGE set to exactly "1" or "0", which wins over the saved setting. Either way a Claude turn whose tool+ * search is on is not bridged (agentsToolBridgeRefusal); ENABLE_TOOL_SEARCH=false in the instance's environment restores it. */export function agentsToolBridgeEnabled(cfg: BridgeConfig, env: NodeJS.ProcessEnv = process.env): boolean {const override = env[TOOL_BRIDGE_ENV];if (override === "1") return true;@@ -271,6 +273,17 @@ export function engineBridgeRefusal(return "this engine keeps its own tool permissions";}+/** Whether a Claude turn on `engine` runs with tool search, so the agents server sends only a few tools whole and the rest as+ * names (claudeAgentsMount): fewer bytes than the bridge's own two tools and its prompt sentence, and every tool keeps its+ * own name. Read as the driver reads it, from the launch folder's settings, the person's own and the environment. */+function claudeDefersAgentsTools(engine: BridgeEngine | null | undefined, env: NodeJS.ProcessEnv, host: EngineHost = { home: homedir(), managedPolicyFiles: [] }): boolean {+ if (engine?.driverKind !== "claudeAgent") return false;+ const configDir = (engine.config as { configDir?: unknown } | undefined)?.configDir;+ const turnEnv: NodeJS.ProcessEnv = { ...env, ...engine.environment, HOME: host.home };+ if (typeof configDir === "string" && configDir.trim()) turnEnv.CLAUDE_CONFIG_DIR = resolveClaudeConfigDir(configDir, turnEnv);+ return claudeToolSearchOn(claudeToolSearchSetting(engine.cwd ?? host.home, turnEnv));+}+/** Why a turn of `bot` on `engine` is not bridged, or null: the one decision. Security: anything thrown* means no bridge, and the log names only the error's class and code, never its message (it may hold a* path or file content). */@@ -282,7 +295,9 @@ export function agentsToolBridgeRefusal(host?: EngineHost,): string | null {try {- if (!agentsToolBridgeEnabled(cfg, env) && (env[TOOL_BRIDGE_ENV] === "0" || !runsLocalModel(bot, engine))) return "the switch is off";+ const localModel = runsLocalModel(bot, engine);+ if (!agentsToolBridgeEnabled(cfg, env) && (env[TOOL_BRIDGE_ENV] === "0" || !localModel)) return "the switch is off";+ if (!localModel && claudeDefersAgentsTools(engine, env, host)) return "Claude Code defers the agents tools on this turn";// Security: selection gates match the name in the call, so any selection, even one that permits// everything or cannot be read, means no bridge.const selection = bot ? parseToolScope(bot.toolScope) : undefined;diff --git a/server/agents-bridge.e2e.test.ts b/server/agents-bridge.e2e.test.tsindex b0ca286e95..5cf090f30f 100644--- a/server/agents-bridge.e2e.test.ts+++ b/server/agents-bridge.e2e.test.ts@@ -25,7 +25,7 @@ import { hostTimeout } from "./testing/host-timeout.ts";import { childEnv } from "./testing/omb-env.ts";type McpServer = { command: string; args: string[]; env: Record<string, string> };-type Launched = { pid: number; systemPrompt: string; mcpConfig: { mcpServers: Record<string, McpServer> } };+type Launched = { pid: number; systemPrompt: string; systemPromptFile: string; mcpConfig: { mcpServers: Record<string, McpServer> } };type Answer = {id: number;result?: { tools?: BridgeTool[]; content?: Array<{ text: string }>; isError?: boolean };@@ -39,8 +39,9 @@ async function withFixture(run: (helpers: {/** What the fake engine was launched with for the turn just sent. */launched(): Promise<Launched>;// hang: the engine keeps its turn open until it is interrupted-}) => Promise<void>, engine: Record<string, string> = { FAKE_CLAUDE_MODE: "hang" }) {- const fixture = await launchVerificationServer({ ...process.env, ...engine });+}) => Promise<void>, engine: Record<string, string> = { FAKE_CLAUDE_MODE: "hang" }, toolSearch = "false") {+ // Claude Code's tool search defers the agents tools instead of bridging them, so a bridged Claude turn has it off.+ const fixture = await launchVerificationServer({ ...process.env, ENABLE_TOOL_SEARCH: toolSearch, ...engine });try {await run({api: async (method, path, body) => {@@ -104,6 +105,28 @@ const refusalOf = (answer: Answer): string => {return textOf(answer);};+it("defers the agents tools instead of bridging them while Claude Code's tool search is on, whatever the switch says", async () => {+ await withFixture(async ({ api, control, launched }) => {+ const { bot } = await control(["new-bot", "--name", "Deferred fixture"]);+ for (const [switched, text] of [[false, "Stay active."], [true, "Stay active again."]] as const) {+ if (switched) expect((await api("PATCH", "/api/config", { features: { agentsToolBridge: true } })).status).toBe(200);+ await control(["send", "--bot", bot.id, "--text", text]);+ const turn = await launched();+ const agents = turn.mcpConfig.mcpServers.agents!;+ expect(agents.env.OMB_AGENTS_TOOL_BRIDGE, `switch ${switched}`).toBe("0");+ expect(agents.env[DEFER_TOOLS_ENV], `switch ${switched}`).toBe("1");+ expect(turn.systemPrompt).not.toContain(AGENTS_TOOL_BRIDGE_PROMPT.trim());+ await withServer(agents, async (ask) => {+ const listed = (await ask("tools/list")).result!.tools! as Array<BridgeTool & { _meta?: Record<string, unknown> }>;+ expect(listed.some((tool) => tool._meta?.[ALWAYS_LOAD_META] === false)).toBe(true);+ expect(listed.map((tool) => tool.name)).not.toContain("find_tool");+ });+ await control(["interrupt", "--bot", bot.id]);+ await control(["wait", "--bot", bot.id, "--timeout", "30"]);+ }+ }, { FAKE_CLAUDE_MODE: "hang" }, "");+}, hostTimeout(60_000));+it("keeps a turn on the whole catalog until the switch is on, then mounts the bridge and says so, in a chat and in a room", async () => {await withFixture(async ({ api, control, launched }) => {const { bot } = await control(["new-bot", "--name", "Bridge fixture"]);@@ -114,13 +137,13 @@ it("keeps a turn on the whole catalog until the switch is on, then mounts the brconst before = await launched();const unbridged = before.mcpConfig.mcpServers.agents!;expect(unbridged.env.OMB_AGENTS_TOOL_BRIDGE).toBe("0");- // A Claude turn marks all but a few tools deferred (agents-claude-defer.ts); the bridge, once on, lists none so marked.- expect(unbridged.env[DEFER_TOOLS_ENV]).toBe("1");+ // With tool search off nothing is marked deferred (agents-claude-defer.ts).+ expect(unbridged.env[DEFER_TOOLS_ENV]).toBeUndefined();expect(before.systemPrompt).not.toContain("find_tool");let whole: BridgeTool[] = [];await withServer(unbridged, async (ask) => {const listed = (await ask("tools/list")).result!.tools! as Array<BridgeTool & { _meta?: Record<string, unknown> }>;- expect(listed.some((tool) => tool._meta?.[ALWAYS_LOAD_META] === false)).toBe(true);+ expect(listed.some((tool) => tool._meta?.[ALWAYS_LOAD_META] === false)).toBe(false);whole = listed.map(({ _meta: _marks, ...tool }) => tool);expect(whole.map((tool) => tool.name)).toEqual(expect.arrayContaining(["coordinate_bots", "trigger", "trigger_info", "session_search"]));expect(whole.map((tool) => tool.name)).not.toEqual(expect.arrayContaining(["find_tool"]));@@ -138,11 +161,14 @@ it("keeps a turn on the whole catalog until the switch is on, then mounts the brexpect(after.pid).not.toBe(before.pid);const bridged = after.mcpConfig.mcpServers.agents!;expect(bridged.env.OMB_AGENTS_TOOL_BRIDGE).toBe("1");- expect(after.systemPrompt).toContain(AGENTS_TOOL_BRIDGE_PROMPT);+ // it rides the first message's note, which is trimmed: the rule's leading space goes+ const rule = AGENTS_TOOL_BRIDGE_PROMPT.trim();+ expect(after.systemPrompt).toContain(rule);+ expect(after.systemPromptFile).not.toContain(rule);// the rest of the prompt still names its tools as it did; the one rule covers themfor (const prompt of [before.systemPrompt, after.systemPrompt]) expect(prompt).toContain("set it up with trigger action=create in this turn");// said once- expect(after.systemPrompt.split(AGENTS_TOOL_BRIDGE_PROMPT)).toHaveLength(2);+ expect(after.systemPrompt.split(rule)).toHaveLength(2);// a fixture bot is not a Chief of Staff, so create_bot is not one of its toolsexpect(bridged.env.OMB_CHIEF_OF_STAFF).toBe("0");@@ -200,7 +226,7 @@ it("keeps a turn on the whole catalog until the switch is on, then mounts the brexpect(textOf(await call(ask, "list_triggers", {}))).toMatch(/^This bot has no triggers\. Current time: /);});// the prompt this turn was given is still true of that mount: it speaks of the bridge tools only if they are listed- expect(after.systemPrompt).toContain(" If find_tool and use_tool are in your tool list, ");+ expect(after.systemPrompt).toContain("If find_tool and use_tool are in your tool list, ");await control(["interrupt", "--bot", bot.id]);await control(["wait", "--bot", bot.id, "--timeout", "30"]);@@ -212,7 +238,7 @@ it("keeps a turn on the whole catalog until the switch is on, then mounts the br// A room refuses widgets, pages and a computer pick, so its turn is not listed them.expect(room.mcpConfig.mcpServers.agents!.env).toMatchObject({ OMB_ROOM: "1", OMB_COMPUTER_SELECTION: "0" });expect(after.mcpConfig.mcpServers.agents!.env.OMB_ROOM).toBe("0");- expect(room.systemPrompt).toContain(AGENTS_TOOL_BRIDGE_PROMPT);+ expect(room.systemPrompt).toContain(rule);await control(["interrupt", "--channel", channel.id]);await control(["wait", "--channel", channel.id, "--timeout", "30"]);});diff --git a/server/data-prompt.test.ts b/server/data-prompt.test.tsnew file mode 100644index 0000000000..f45000eb90--- /dev/null+++ b/server/data-prompt.test.ts@@ -0,0 +1,56 @@+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import { DATA_DB_FILE } from "./data/engine.ts";+import { BUILT_IN_DATA_SYSTEM_PROMPT } from "./data/instructions.ts";+import { SHEET_FILE } from "./data/sheet.ts";+import { DATA_TOOLS_POINTER, ThreadChoices, botHasData, dataPrompts, mentionsDataWork } from "./data-prompt.ts";+import { removeTempDir } from "./testing/cleanup.ts";++const folders: string[] = [];+const folder = () => { const made = mkdtempSync(join(tmpdir(), "omb-data-prompt-")); folders.push(made); return made; };+afterAll(async () => { for (const made of folders) await removeTempDir(made); });++describe("the Data section of the prompt", () => {+ it("is asked for by words about files, sheets, SQL and charts, in any case", () => {+ for (const text of ["Load sales.CSV and chart revenue", "what's in this spreadsheet?", "run this SQL", "Plot it by month", "analyse my orders.xlsx", "Data tab"]) {+ expect(mentionsDataWork(text), text).toBe(true);+ }+ for (const text of ["Say hi.", "Remind me at noon"]) expect(mentionsDataWork(text), text).toBe(false);+ });++ it("knows a bot that has used Data by its database or Data sheet, without opening either", () => {+ const root = folder();+ const at = (botId: string) => join(root, botId);+ for (const botId of ["fresh", "loaded", "charted"]) mkdirSync(at(botId));+ writeFileSync(join(at("loaded"), DATA_DB_FILE), "");+ writeFileSync(join(at("charted"), SHEET_FILE), "{}");+ expect(botHasData("fresh", at)).toBe(false);+ expect(botHasData("missing", at)).toBe(false);+ expect(botHasData("loaded", at)).toBe(true);+ expect(botHasData("charted", at)).toBe(true);+ });++ it("is the guide where Data is in use and a one-line pointer elsewhere, chosen on a conversation's first turn and kept", () => {+ const prompt = dataPrompts({ hasData: (botId) => botId === "user-of-data" });+ expect(prompt("fresh", "t1", "Say hi.")).toBe(DATA_TOOLS_POINTER);+ expect(prompt("fresh", "t1", "Load q3.csv"), "a warm engine is not relaunched by it").toBe(DATA_TOOLS_POINTER);+ expect(prompt("fresh", "t2", "Load q3.csv")).toBe(BUILT_IN_DATA_SYSTEM_PROMPT);+ expect(prompt("fresh", "t2", "Thanks.")).toBe(BUILT_IN_DATA_SYSTEM_PROMPT);+ expect(prompt("user-of-data", "t3", "Say hi.")).toBe(BUILT_IN_DATA_SYSTEM_PROMPT);+ // the pointer names every tool the guide does, in far fewer bytes+ for (const tool of ["data_load", "data_describe", "data_sql", "data_show", "data_export"]) expect(DATA_TOOLS_POINTER).toContain(tool);+ expect(Buffer.byteLength(DATA_TOOLS_POINTER)).toBeLessThan(Buffer.byteLength(BUILT_IN_DATA_SYSTEM_PROMPT) / 5);+ });++ it("remembers a bounded number of conversations", () => {+ const threads = new ThreadChoices(2);+ threads.set("a", true);+ threads.set("b", false);+ threads.set("c", true);+ expect(threads.get("a")).toBeUndefined();+ expect(threads.get("b")).toBe(false);+ expect(threads.get("c")).toBe(true);+ });+});diff --git a/server/data-prompt.ts b/server/data-prompt.tsnew file mode 100644index 0000000000..b76dd29f37--- /dev/null+++ b/server/data-prompt.ts@@ -0,0 +1,65 @@+// The Data section of a bot's system prompt. The Data server is mounted on every turn its engine supports, so its tools+// are always there; its 1.2 KB guide is sent where Data is in use and a one-line pointer elsewhere. A conversation keeps+// the choice made on its first turn, so its cached prefix and its warm engine never change because of it.+import { existsSync } from "node:fs";+import { join } from "node:path";++import { botFolder } from "./bot-folder.ts";+import { BUILT_IN_DATA_SYSTEM_PROMPT } from "./data/instructions.ts";+import { DATA_DB_FILE } from "./data/engine.ts";+import { SHEET_FILE } from "./data/sheet.ts";++/** Where the guide is not sent: enough for the bot to know the tools are there. */+export const DATA_TOOLS_POINTER =+ " You have Data tools for tables, spreadsheets and charts (data_load, data_describe, data_sql, data_show, data_export); load them with tool search when needed.";++/** Words that ask for work the Data tools do: loading, querying or charting a file, a sheet or a database. */+export const DATA_WORK_TERMS = [+ "data", "csv", "tsv", "xlsx", "xls", "parquet", "ndjson", "json", "spreadsheet", "sheet", "excel", "sql", "duckdb",+ "database", "table", "query", "chart", "graph", "plot", "pivot", "analy", "dashboard",+] as const;++/** Whether the person's words, with any Data context they attached, ask for Data work. */+export function mentionsDataWork(text: string): boolean {+ const lower = text.toLowerCase();+ return DATA_WORK_TERMS.some((term) => lower.includes(term));+}++/** Whether the bot has used Data: its database or its Data sheet exists. Nothing is opened or created. */+export function botHasData(botId: string, folder: (botId: string) => string = botFolder): boolean {+ const dir = folder(botId);+ return existsSync(join(dir, DATA_DB_FILE)) || existsSync(join(dir, SHEET_FILE));+}++/** Each conversation's choice, made on its first turn here and kept, so its stable prompt never changes because of it;+ * capped so the map cannot grow with every thread. */+export class ThreadChoices {+ private readonly chosen = new Map<string, boolean>();+ private readonly max: number;+ constructor(max = 5_000) {+ this.max = max;+ }+ get(threadId: string): boolean | undefined {+ return this.chosen.get(threadId);+ }+ set(threadId: string, guide: boolean): void {+ this.chosen.delete(threadId);+ this.chosen.set(threadId, guide);+ if (this.chosen.size > this.max) this.chosen.delete(this.chosen.keys().next().value!);+ }+}++/** The server's one decision for a turn whose Data server is mounted: the guide or the pointer. The server's own+ * instructions and tools are there either way; a bot that has used Data gets the guide in every new conversation. */+export function dataPrompts(deps: { hasData?: (botId: string) => boolean; threads?: ThreadChoices } = {}) {+ const hasData = deps.hasData ?? ((botId: string) => botHasData(botId));+ const threads = deps.threads ?? new ThreadChoices();+ return (botId: string, threadId: string, text: string): string => {+ let guide = threads.get(threadId);+ if (guide === undefined) {+ guide = hasData(botId) || mentionsDataWork(text);+ threads.set(threadId, guide);+ }+ return guide ? BUILT_IN_DATA_SYSTEM_PROMPT : DATA_TOOLS_POINTER;+ };+}diff --git a/server/drivers/agents-claude-defer.test.ts b/server/drivers/agents-claude-defer.test.tsindex 1b991c4224..226df7ad2c 100644--- a/server/drivers/agents-claude-defer.test.ts+++ b/server/drivers/agents-claude-defer.test.ts@@ -5,14 +5,15 @@ 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 { ALWAYS_LOAD_META, CLAUDE_ALWAYS_LOADED_TOOL_NAMES, CLAUDE_CHIEF_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. */+/** The catalog wire test's default and fullest profiles (both a Chief's), and a bot that is not a Chief. */const PROFILES: Record<string, Record<string, string>> = {default: BASE,+ specialist: { ...BASE, OMB_CHIEF_OF_STAFF: "0" },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",@@ -22,8 +23,9 @@ 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 },+ default: { whole: 3855, deferred: 1209 },+ specialist: { whole: 1495, deferred: 1037 },+ fullest: { whole: 3855, deferred: 1546 },};const listed = (env: Record<string, string>) => agentsToolList(env).listed as Array<{ name: string; description: string; inputSchema: unknown; _meta?: Record<string, unknown> }>;@@ -33,9 +35,12 @@ 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);+ const loaded = env.OMB_CHIEF_OF_STAFF === "1" ? CLAUDE_CHIEF_ALWAYS_LOADED_TOOL_NAMES : CLAUDE_ALWAYS_LOADED_TOOL_NAMES;+ expect(tools.filter((tool) => !marked(tool)).map((tool) => tool.name).every((name) => loaded.has(name))).toBe(true);+ expect(tools.filter(marked).length).toBeGreaterThan(35);expect(tools.find((tool) => tool.name === "list_bots")?._meta, "a deferred list_bots loses to Claude Code's ListAgents").toBeUndefined();+ expect(marked(tools.find((tool) => tool.name === "coordinate_bots")!), "a Chief's hand-off needs no search first").toBe(env.OMB_CHIEF_OF_STAFF !== "1");+ for (const name of ["memory_update", "attach_file"]) expect(marked(tools.find((tool) => tool.name === name)!), name).toBe(true);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);}@@ -46,7 +51,7 @@ describe("agents tools deferred on a Claude turn", () => {...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([]);+ expect([...CLAUDE_CHIEF_ALWAYS_LOADED_TOOL_NAMES].filter((name) => !names.has(name))).toEqual([]);});it("keeps what a Claude turn sends up front within its budget", () => {@@ -85,7 +90,8 @@ describe("agents tools deferred on a Claude turn", () => {});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();+ expect(tools.find((tool) => tool.name === "memory_update")?._meta).toEqual({ [ALWAYS_LOAD_META]: false });+ expect(tools.find((tool) => tool.name === "list_bots")?._meta).toBeUndefined();} finally {await waitForExit(child, { signal: "SIGTERM" });}diff --git a/server/drivers/agents-claude-defer.ts b/server/drivers/agents-claude-defer.tsindex b3cc7d4d69..bd8f5afcc7 100644--- a/server/drivers/agents-claude-defer.ts+++ b/server/drivers/agents-claude-defer.ts@@ -3,26 +3,32 @@// 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. */+/** The proxy's switch, set by the Claude driver: "1" marks every tool outside claudeAlwaysLoaded 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. */+ * because a deferred list_bots loses to Claude Code's own ListAgents when the bot inherits this machine's setup. Tools a+ * turn calls only now and then (memory_update, attach_file, send_voice_note) are deferred: the prompt names them, and+ * one ToolSearch loads one when it is needed. */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",]);+/** A Chief hands work out on most turns: a deferred coordinate_bots costs every hand-off a ToolSearch request first. */+export const CLAUDE_CHIEF_ALWAYS_LOADED_TOOL_NAMES: ReadonlySet<string> = new Set([...CLAUDE_ALWAYS_LOADED_TOOL_NAMES, "coordinate_bots"]);+export const ALWAYS_LOAD_META = "anthropic/alwaysLoad";+/** The tools a Claude turn of this bot sends whole. */+export const claudeAlwaysLoaded = (chief: boolean): ReadonlySet<string> => chief ? CLAUDE_CHIEF_ALWAYS_LOADED_TOOL_NAMES : CLAUDE_ALWAYS_LOADED_TOOL_NAMES;+/** `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)+export function withDeferMarks<Tool extends { name: string; _meta?: Record<string, unknown> }>(tools: readonly Tool[], chief = false): Tool[] {+ const loaded = claudeAlwaysLoaded(chief);+ return tools.map((tool) => loaded.has(tool.name)? tool: { ...tool, _meta: { ...tool._meta, [ALWAYS_LOAD_META]: false } });}diff --git a/server/drivers/agents-mcp.ts b/server/drivers/agents-mcp.tsindex 7ab285b3b7..15932e4f19 100644--- a/server/drivers/agents-mcp.ts+++ b/server/drivers/agents-mcp.ts@@ -12,9 +12,10 @@ import { capToolListResult, toolLimitFromEnv } from "../tool-count-limit.ts";/** What the agents server lists for `env`, before any tool limit. */export function agentsToolList(env: NodeJS.ProcessEnv) {- const available = availableTools(catalogProfileFromEnv(env));+ const profile = catalogProfileFromEnv(env);+ const available = availableTools(profile);const bridge = env[TOOL_BRIDGE_ENV] === "1" ? createToolBridge(available) : undefined;- return { available, bridge, listed: bridge ? bridge.listed : env[DEFER_TOOLS_ENV] === "1" ? withDeferMarks(available) : available };+ return { available, bridge, listed: bridge ? bridge.listed : env[DEFER_TOOLS_ENV] === "1" ? withDeferMarks(available, profile.chief) : available };}export function agentsMcp(env: NodeJS.ProcessEnv): (msg: Json) => Promise<Json | undefined> {diff --git a/server/index.ts b/server/index.tsindex eb54c3a976..f971581d61 100644--- a/server/index.ts+++ b/server/index.ts@@ -96,7 +96,6 @@ import { chosenPlace, pickComputer } from "./computer-selection.ts";import * as boat from "./boat.ts"; import { keyHint, keyStatus, nestedKeyStatus, withoutKeyHints } from "./key-hint.ts";import { cloudComputerRpc } from "./cloud-computer-tools.ts"; import { createBoatRecovery } from "./boat-recovery.ts"; import { CLOUD_COMPUTER_PERSON_LINES, CLOUD_COMPUTER_RESTORING, RUN_COMPUTER_LINES } from "../shared/cloud-computer-recovery.ts"; import { boatReadiness } from "./boat-ready.ts"; import { createRunComputerGate } from "./host/cloud-computer-run-gate.ts"; import { cloudComputerDisk } from "./cloud-computer-disk.ts"; import { runComputerMemory } from "./host/cloud-computer-run-memory.ts";import { chartRenderer, compileChart, dataEngine, validateVegaLite } from "./data/deps.ts";-import { BUILT_IN_DATA_SYSTEM_PROMPT } from "./data/instructions.ts";import { DATA_INTERNAL_MCP_PATH, dataRpc } from "./data/rpc.ts";import { removeRetiredAppFiles } from "./retired-apps.ts"; import { createEmailRoutes } from "./routes/email.ts"; import { createEmailHost, EMAIL_INTERNAL_MCP_PATH, emailAccess } from "./email/host.ts"; import { createEmailService } from "./email/service.ts"; import { createPostizRoutes } from "./routes/postiz.ts"; import { createPostiz } from "./postiz/service.ts";import { createPhones } from "./host/phones.ts";@@ -337,7 +336,7 @@ import { generateThreadTitle, llmThreadTitlesEnabled } from "./thread-title-geneimport { engineCommandCpuMs, engineProcessExited, engineProcessGone, ENGINE_EXIT_STALL_MS, stallLimitMs, stallNotice, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts";import { TurnResources, type TurnOwner } from "./turn-resources.ts";import { createPhoneHold } from "./phone-screen/hold.ts"; import { createPhoneGate } from "./routes/phone-gate.ts";-import { endHoldUnlessOn, usbPhoneOffered, usbPhoneTakeoverEnabled } from "./phone-screen/flag.ts";+import { endHoldUnlessOn, usbPhoneOffered, usbPhoneTakeoverEnabled } from "./phone-screen/flag.ts"; import { dataPrompts } from "./data-prompt.ts";import { createPhoneScreenRoutes } from "./routes/phone-screen.ts";import {ensureWorkspace,@@ -2392,7 +2391,7 @@ function dataExportRoots(bot: { id: string; cwd?: string }): string[] {const downloads = join(homedir(), "Downloads");return [...(existsSync(downloads) ? [downloads] : []), ...(bot.cwd ? [bot.cwd] : []), workspaceDir(bot.id)];}-let dataUnavailableLogged = false;+let dataUnavailableLogged = false; const dataPrompt = dataPrompts();function dataIntegration(botId: string, turn: { threadId: string; generation: string }) {const unavailable = dataEngine.unavailable(); if (serverTurnedOff(store.bot(botId)?.toolsOff, "data")) return null;if (unavailable !== null) {@@ -8344,7 +8343,7 @@ async function beginTurn({ id: "composio", label: "Connected apps", text: integrations.composio ? composioSystemPrompt(liveBot?.connectorTools ?? bot.connectorTools) + describeConnectorScopes((liveBot ?? bot).connectorScopes) : "" },{ id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(liveBot ?? bot, lentMcp.lines(liveBot ?? bot, { botId: bot.id, threadId, generation: dispatchClaimId })) + teamConnections.prompt(threadId, dispatchClaimId, integrations) },{ id: "browser", label: "Browser", text: integrations.browser ? browserPromptFor(bot, Boolean(integrations.agents)) : "" },- { id: "data", label: "Data", text: integrations.data ? BUILT_IN_DATA_SYSTEM_PROMPT : "" },+ { id: "data", label: "Data", text: integrations.data ? dataPrompt(bot.id, threadId, providerText) : "" },{ id: "email", label: "Email", text: instance.adapter.capabilities.emailMcp === true ? emailHost.prompt(liveBot ?? bot) : "" }, { id: "meetings", label: "Meetings", text: meetingsUnavailablePrompt({ agentsTools: Boolean(integrations.agents), cloudComputer: boat.boatConfigured(cfg) }) }, toolsOffPart(liveBot ?? bot),...phones.promptParts(liveBot ?? bot, {mounted: Boolean(integrations.device), offered: instance.adapter.capabilities.deviceMcp === true, turn: { botId: bot.id, threadId, generation: dispatchClaimId },@@ -10122,7 +10121,7 @@ async function runClaimedGroupMemberTurn({ id: "plan", label: "Surface", text: surfacePrompt({ computer: roomTeamComputer ? "cloud" : roomVmTarget ? "vm" : surfaceOfComputerKind(roomComputerKind), browser: Boolean(integrations.browser) }, { note: roomPlan.note, cloudHome: Boolean(CLOUD_HOME), ownComputer: CLOUD_HOME && integrations.agents && lendingEnabled() ? sharedComputers.known(CLOUD_HOME_LENDER) : undefined }) },{ id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER), CLOUD_PERSONAL) : "" }, phoneLinkPart(),{ id: "browser", label: "Browser", text: integrations.browser ? browserPromptFor(bot, Boolean(integrations.agents)) : "" },- { id: "data", label: "Data", text: integrations.data ? BUILT_IN_DATA_SYSTEM_PROMPT : "" },+ { id: "data", label: "Data", text: integrations.data ? dataPrompt(readyBot.id, threadId, `${roomContext}\n${latestUser?.text ?? ""}`) : "" },{ id: "email", label: "Email", text: instance.adapter.capabilities.emailMcp === true ? emailHost.prompt(readyBot) : "" }, toolsOffPart(readyBot),...phones.promptParts(readyBot, {mounted: Boolean(integrations.device), offered: instance.adapter.capabilities.deviceMcp === true,diff --git a/server/system-prompt.test.ts b/server/system-prompt.test.tsindex f6a0b33b3c..444569d4c5 100644--- a/server/system-prompt.test.ts+++ b/server/system-prompt.test.ts@@ -137,10 +137,13 @@ describe("buildSystemPrompt", () => {{ id: "setup", label: "Setup", text: " Set yourself up." },{ id: "skill-instructions", label: "Skill instructions", text: " Use the deploy skill." },{ id: "routine-execution", label: "Routine execution", text: ROUTINE_EXECUTION_PROMPT },+ { id: "automation-reply", label: "Automation reply", text: AUTOMATION_REPLY_PROMPT },{ id: "webhook", label: "Webhook provenance", text: WEBHOOK_PROMPT },]);expect(built.volatile).toContain("Use the deploy skill.");expect(built.volatile).toContain(ROUTINE_EXECUTION_PROMPT);+ // a routine run that reports elsewhere reads the bot's own cached prefix+ expect(built.volatile).toContain(AUTOMATION_REPLY_PROMPT);expect(built.stable).toBe(`You are Kiwi. Set yourself up.${WEBHOOK_PROMPT}${REPLY_HABITS_PROMPT}`);});diff --git a/server/system-prompt.ts b/server/system-prompt.tsindex 94c53467e3..f7cd510067 100644--- a/server/system-prompt.ts+++ b/server/system-prompt.ts@@ -43,8 +43,11 @@ export function heavyPrompt(sections: readonly PromptSection[]): boolean {// at the computer, or not there) and what its words switched on.// Two per-turn sections stay stable on purpose: "setup" sits right after the standing instructions it overrides,// and "webhook" keeps its untrusted-data rule in the system prompt, out of reach of the payload it guards.+// Two more ride the volatile half so a bot's stable half is the same bytes across its runs: the bridge rule (on for some+// runs of a bot and not others) and an automation run's reply rule ("automation-reply"), which otherwise makes every+// routine run write a new cached prefix.const VOLATILE_SECTIONS = new Set(["memory", "mentions", "outstanding", "teammate-questions", "long-waits", "recent", "availability", "active-routines",- "plan", "assignment", "routine-execution", "skill-instructions", "playbooks", "device-place", "files"]);+ "plan", "assignment", "routine-execution", "automation-reply", "skill-instructions", "playbooks", "device-place", "files", "tool-bridge"]);/** In the stable half, so it is not sent again whenever availability changes, but no part of what a per-thread process is* keyed on: a warm process gets a changed roster as a note instead of a relaunch (SendTurnInput.systemRoster). */const ROSTER_SECTION = "roster";