Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat: 将 bot 自身用量并入 usage_limits
Zhehui Bi198b011f2744
diff --git a/docs/usage-caps.md b/docs/usage-caps.mdindex d5fca45ea7..5647f08725 100644--- a/docs/usage-caps.md+++ b/docs/usage-caps.md@@ -28,6 +28,19 @@ subscription sign-in, or with unpriced models, cap tokens.Days and months are UTC, as the usage ledger's are. The reset time is shownin the server's own time zone.+## Reading usage from a bot++`usage_limits` reports AI account subscription quotas when called without+arguments. With `scope: "bot"`, it reads this bot's settled tokens, estimated+cost and usage cap headroom. The UTC period defaults to `today` and also+supports `month`. Pass `thread: "this"` to limit the usage totals to the+current conversation.++The tool includes exact cap totals only when the calling turn can read all+usage counted toward that cap. If `capsComplete` is false, some cap totals+are unavailable in the conversation. A running turn can still read visible+headroom and the reset time after a cap is reached.+## What a reached cap stops`stops` chooses, for all caps together:diff --git a/server/bot-usage.e2e.test.ts b/server/bot-usage.e2e.test.tsnew file mode 100644index 0000000000..5a1a5267de--- /dev/null+++ b/server/bot-usage.e2e.test.ts@@ -0,0 +1,70 @@+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { expect, it } from "vitest";++import { launchVerificationServer, runControlOmb, type VerificationServer } from "../scripts/control-omb.ts";+import { createHarnessClient } from "./drivers/agents-client.ts";+import { callUsageLimitsTool } from "./drivers/agents-usage-tool.ts";+import { removeTempDir } from "./testing/cleanup.ts";+import { hostTimeout } from "./testing/host-timeout.ts";+import { appendUsage } from "./usage-ledger.ts";++it("reads actual headroom through an active turn's capability, even once the cap is reached", async () => {+ const folder = mkdtempSync(join(tmpdir(), "omb-bot-usage-e2e-"));+ const gate = join(folder, "finish");+ let fixture: VerificationServer | undefined;+ try {+ fixture = await launchVerificationServer({ FAKE_CLAUDE_MODE: "slow", FAKE_CLAUDE_SLOW_FINISH_GATE: gate });+ const { info: { url, dataDir }, fixtureDumpPath } = fixture;+ const request = (path: string, init: RequestInit = {}) => fetch(url + path, { ...init, headers: { "content-type": "application/json", origin: url, ...init.headers } });+ const create = async (name: string) => {+ const response = await request("/api/bots", { method: "POST", body: JSON.stringify({ name }) });+ expect(response.status).toBe(201);+ return (await response.json() as { bot: { id: string; threadId: string } }).bot;+ };+ const scout = await create("Scout");+ const peer = await create("Peer");+ const now = new Date();+ const nextMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1));+ for (const at of [now, nextMonth]) for (const bot of [scout, peer]) {+ expect(await appendUsage(dataDir, {+ at: at.toISOString(), botId: bot.id, botName: "Fixture", threadId: bot.threadId, instanceId: "test-account",+ driverKind: "claude", model: "fixture", input: bot === scout ? 10 : 30, output: 2, costUsd: 0.01, trigger: { kind: "owner" },+ })).toBe(true);+ }+ const setCap = async (monthlyTokens: number) => {+ const response = await request("/api/usage/caps", { method: "PUT", body: JSON.stringify({ bots: { [scout.id]: { monthlyTokens } } }) });+ expect(response.status).toBe(200);+ };+ await setCap(24);+ await runControlOmb(["send", "--bot", scout.id, "--task", scout.threadId, "--text", "Check usage before handing off work", "--url", url]);+ let token = "";+ await expect.poll(() => {+ try { token = JSON.parse(readFileSync(fixtureDumpPath, "utf8")).mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN; } catch { return false; }+ return Boolean(token);+ }, { timeout: hostTimeout(15_000) }).toBe(true);+ const client = createHarnessClient(url, token);+ const botUsagePath = "/api/internal/engine-limits?scope=bot";+ expect((await createHarnessClient(url, "wrong").apiResponse(botUsagePath)).status).toBe(401);+ expect((await client.apiResponse(`${botUsagePath}&botId=${peer.id}`)).status).toBe(403);+ const subscription = await callUsageLimitsTool({ client });+ expect(subscription.isError).toBeUndefined();+ expect(JSON.parse(subscription.text)).toEqual({ accounts: expect.any(Array) });+ const before = await callUsageLimitsTool({ client }, { scope: "bot", period: "month", thread: "this" });+ expect(before.isError).toBeUndefined();+ expect(JSON.parse(before.text)).toMatchObject({+ totals: { turns: 1, input: 10, output: 2 },+ caps: [{ used: 12, remaining: 12, reached: false }],+ });++ await setCap(12);+ const reached = await callUsageLimitsTool({ client }, { scope: "bot", period: "month" });+ expect(JSON.parse(reached.text)).toMatchObject({ caps: [{ used: 12, remaining: 0, reached: true, resetsAt: expect.any(Number) }] });+ writeFileSync(gate, "finish");+ await runControlOmb(["wait", "--bot", scout.id, "--task", scout.threadId, "--timeout", "30", "--url", url]);+ expect((await client.apiResponse(botUsagePath)).status).toBe(401);+ } finally {+ try { await fixture?.close(); } finally { await removeTempDir(folder); }+ }+}, hostTimeout(60_000));diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex 3d21fce1b5..0b393081f9 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -256,7 +256,7 @@ export async function callTool(called: string, input: Json, context: ToolCallConif (DEVS_TOOL_NAMES.has(name)) return callDevsTool(name, args, context);if (TRIGGER_TOOL_NAMES.has(name)) return callTriggerTool(name, args, context);if (WAIT_TOOL_NAMES.has(name)) return callWaitTool(name, args, context); if (CHECK_BACK_TOOL_NAMES.has(name)) return callCheckBackTool(args, context);- if (name === USAGE_LIMITS_TOOL) return callUsageLimitsTool(context);+ if (name === USAGE_LIMITS_TOOL) return callUsageLimitsTool(context, args);if (COMPUTER_ASK_TOOL_NAMES.has(name)) return callComputerAskTool(args, context);// Second lock: with sharing off the catalog already omits these tools.if (SHARED_COMPUTER_TOOL_NAMES.has(name) && !context.sharedComputers) {diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.jsonindex 873f13c9f4..863a5ba94a 100644--- a/server/drivers/agents-catalog-goldens/full.tools-list.json+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json@@ -238,11 +238,35 @@},{"name": "usage_limits",- "description": "Each AI account's usage limits: percent used, reset time, when checked. status: ok, unknown (no data now; see why) or unsupported.",+ "description": "AI subscription limits and reset times by default. With scope bot, read this bot's visible tokens, estimated cost and usage cap headroom. Bot periods use UTC.","inputSchema": {"type": "object","additionalProperties": false,- "properties": {}+ "properties": {+ "scope": {+ "type": "string",+ "enum": [+ "subscription",+ "bot"+ ],+ "default": "subscription"+ },+ "period": {+ "type": "string",+ "enum": [+ "today",+ "month"+ ],+ "description": "Bot scope only. Defaults to today."+ },+ "thread": {+ "type": "string",+ "enum": [+ "this"+ ],+ "description": "Bot scope only. Omit for all visible conversations."+ }+ }},"annotations": {"readOnlyHint": true,diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.jsonindex 0b44988f08..49212134df 100644--- a/server/drivers/agents-catalog-goldens/profiles.json+++ b/server/drivers/agents-catalog-goldens/profiles.json@@ -1,7 +1,7 @@{"default": {- "bytes": 58828,- "sha256": "0bc510317f6c20f8a6f99d3c523657344603486fa41285717358c37316e186af",+ "bytes": 59150,+ "sha256": "71136187e2b8942e9858c492918893e609e4330dc8bb8fe5d14e340e8d929489","tools": ["tool_result_read","list_room_targets",@@ -58,8 +58,8 @@]},"voice": {- "bytes": 59609,- "sha256": "84c74fc165fa7788490f88532d8fac7766879c6f215328a26fdfad5aaddb1cec",+ "bytes": 59931,+ "sha256": "3e97a365c8e0d45fc166273c1e222a3daf7339d3f8eba092d202930e12e40505","tools": ["tool_result_read","list_room_targets",@@ -117,8 +117,8 @@]},"shared": {- "bytes": 61093,- "sha256": "8efe0d27e4adf6249d19c047a929bcf1c389d10403fd6399da9e1e9f1428edde",+ "bytes": 61415,+ "sha256": "a624450f68cc5a55fbe1e1b9b1413cadd97defa34d2272b06eb91455c64279a2","tools": ["tool_result_read","list_shared_computers",@@ -177,8 +177,8 @@]},"shared+voice": {- "bytes": 61874,- "sha256": "ef67c1e35a2219d9e1b132a12d425e390327b3d12b3deee713565d5107a40dfe",+ "bytes": 62196,+ "sha256": "0b6b7e1f47512ba0668db5efadcfb341840e3313e4bc38cfccc18c4d42bcd6e8","tools": ["tool_result_read","list_shared_computers",@@ -238,8 +238,8 @@]},"skills": {- "bytes": 61149,- "sha256": "2b9c046537f8c3bf02d291061963d3e093a8f76906980f472f548694695e1b43",+ "bytes": 61471,+ "sha256": "5658f58277de8373cd31d166e5380e9b1be64e62c5302797477661a52e19e540","tools": ["tool_result_read","list_room_targets",@@ -298,8 +298,8 @@]},"skills+voice": {- "bytes": 61930,- "sha256": "6790c26bf2db33fe4a05a28e3c8be24361fc0177da1860fdc6f085a015185dd5",+ "bytes": 62252,+ "sha256": "853d22c20778a951d154a7c6e1757ad7120104339bd65030f6c193078e2617b4","tools": ["tool_result_read","list_room_targets",@@ -359,8 +359,8 @@]},"skills+shared": {- "bytes": 63414,- "sha256": "7e4b83b4bd72690866e9ac5fdb04a797618e0c2084d3037d303c2a858651d8d4",+ "bytes": 63736,+ "sha256": "79e7eb7659a97be6289e3963abc391e8b0b5b089f0954f241aec694037da5d57","tools": ["tool_result_read","list_shared_computers",@@ -421,8 +421,8 @@]},"skills+shared+voice": {- "bytes": 64195,- "sha256": "3baddbc0c2fb5eae43372a7ec7975dde4bad9777672e170645df5fa174d6bbcb",+ "bytes": 64517,+ "sha256": "4e29bc6937df0257d38296132c74c12820c2d37feabe46b6b4ed73352d13f28a","tools": ["tool_result_read","list_shared_computers",@@ -484,8 +484,8 @@]},"non-chief": {- "bytes": 50280,- "sha256": "2f36a30278c390b6e75b5ef9b13d8969b41d37dbcd03046857c515d8a8949885",+ "bytes": 50602,+ "sha256": "a94a417a620bffa6ea6902126e73b64fab8e4ec8e0d59038d4cacf48e0100be4","tools": ["tool_result_read","list_room_targets",@@ -535,8 +535,8 @@]},"voice+non-chief": {- "bytes": 51061,- "sha256": "9c2327276275e3c59daeb928ba6ef8cc7d0113050bfb6db068383f9b51345778",+ "bytes": 51383,+ "sha256": "ea6d951ab8e36616741d94de3841eb144d5bdd57d3409bcb59ebaf2836ec0e2b","tools": ["tool_result_read","list_room_targets",@@ -587,8 +587,8 @@]},"shared+non-chief": {- "bytes": 52545,- "sha256": "7b88c750cfc76292aefafbaad6c338aa57581a7634b4594c20174df59eacdb27",+ "bytes": 52867,+ "sha256": "7b5800019438f3d233db77755eab201d54844026ab44161cadea0fca19baa97e","tools": ["tool_result_read","list_shared_computers",@@ -640,8 +640,8 @@]},"shared+voice+non-chief": {- "bytes": 53326,- "sha256": "344fae24fb4ca181f9535d8491d63f4b3730733852e556f29a5e0e5afdf33070",+ "bytes": 53648,+ "sha256": "b1153f9b82da726f1aab39bcffeb14d07671b9910c90afcb79150242bebfcccb","tools": ["tool_result_read","list_shared_computers",@@ -694,8 +694,8 @@]},"skills+non-chief": {- "bytes": 52601,- "sha256": "f58b8554a43b1221632d881269372885edf7fc9d560d6ddabf7e51d9d42b945c",+ "bytes": 52923,+ "sha256": "ea9d277a3cbe59727e4cd73ec207417b1e04d9680c326b0e59361449fd04af29","tools": ["tool_result_read","list_room_targets",@@ -747,8 +747,8 @@]},"skills+voice+non-chief": {- "bytes": 53382,- "sha256": "45cc5db670f9c0ad6c487df9a881db5d58802813b0d7237f853b2599cd79dcc0",+ "bytes": 53704,+ "sha256": "01677a7053ff53e02b996b5e78f8b2fe2f6b7c4cdecd459816c1715a8c3b1702","tools": ["tool_result_read","list_room_targets",@@ -801,8 +801,8 @@]},"skills+shared+non-chief": {- "bytes": 54866,- "sha256": "3d70000599f350cbbbd41fbe67d26c5e3fa0ecff3ba5ed707ab389c621e79f28",+ "bytes": 55188,+ "sha256": "2400c79c30b54a547737341c6680937f9ea99285e7c06185d85c9534fde63b28","tools": ["tool_result_read","list_shared_computers",@@ -856,8 +856,8 @@]},"skills+shared+voice+non-chief": {- "bytes": 55647,- "sha256": "618f91f99861d9b84922da174fa7cb4fac6b8b6269c48e2bed7802d4d259c1d1",+ "bytes": 55969,+ "sha256": "545da102b5abdac14a3334ee98cbe35bd927050fa8bfdf013b6264c2d57a29f4","tools": ["tool_result_read","list_shared_computers",@@ -912,8 +912,8 @@]},"skills+shared+voice+cloud-home": {- "bytes": 63961,- "sha256": "12b61b8135e45ed1d8d5cc1b3d486ed8b1dc2754f7207d13ef797ada1b94adaa",+ "bytes": 64283,+ "sha256": "960297811f692f658fbbedf158b9697606a53cc607265c623ec65dbc6b2eb0c7","tools": ["tool_result_read","list_shared_computers",@@ -975,8 +975,8 @@]},"skills+shared+voice+non-chief+cloud-home": {- "bytes": 55413,- "sha256": "2b1058789d6de069e611534026b85b4fe6e01cf6d4c3d927e584010b9c7422ad",+ "bytes": 55735,+ "sha256": "8a258ac601d54b555ac49d181fca46ad0408d26d7a452faf8a982484c4b7651e","tools": ["tool_result_read","list_shared_computers",@@ -1031,8 +1031,8 @@]},"skills+shared+voice+x": {- "bytes": 68034,- "sha256": "07704e3ea47b374017b1673993709c4c3295af93c1093fb978f79ee9c93cc119",+ "bytes": 68356,+ "sha256": "7d282d4771f36e808686a54e8881d1745ba32c8e0974d66db397583e6c5a7d9e","tools": ["tool_result_read","list_shared_computers",@@ -1098,8 +1098,8 @@]},"skills+shared+voice+x+team": {- "bytes": 68034,- "sha256": "07704e3ea47b374017b1673993709c4c3295af93c1093fb978f79ee9c93cc119",+ "bytes": 68356,+ "sha256": "7d282d4771f36e808686a54e8881d1745ba32c8e0974d66db397583e6c5a7d9e","tools": ["tool_result_read","list_shared_computers",@@ -1165,8 +1165,8 @@]},"skills+shared+voice+x+team+images": {- "bytes": 69981,- "sha256": "cdce42a3892f3425c82f94695e9f06760c57071751fbc5ba77dcc09bf6deac20",+ "bytes": 70303,+ "sha256": "20b0b5158ee7d3810d7a35d460c6620977995321d15e8b3f670349879c5497b1","tools": ["tool_result_read","list_shared_computers",@@ -1234,8 +1234,8 @@]},"default+legacy-switches": {- "bytes": 58828,- "sha256": "0bc510317f6c20f8a6f99d3c523657344603486fa41285717358c37316e186af",+ "bytes": 59150,+ "sha256": "71136187e2b8942e9858c492918893e609e4330dc8bb8fe5d14e340e8d929489","tools": ["tool_result_read","list_room_targets",@@ -1292,8 +1292,8 @@]},"default+mausbot": {- "bytes": 59479,- "sha256": "648fe0697b962ab200977b51d8438abaeede5ed122a3330ae88cff2ededb054f",+ "bytes": 59801,+ "sha256": "42b18b1dda88431e51a7abf98a3c97fecf0ff6451ef6803400e4383ba56186da","tools": ["tool_result_read","list_room_targets",@@ -1352,8 +1352,8 @@]},"skills+shared+voice+mausbot": {- "bytes": 64846,- "sha256": "3e38f4adecea9c5fe026ab7dbd15da8c4f1d8ed45c68a97c4fe923de7c389e75",+ "bytes": 65168,+ "sha256": "f1553294dd1933e553f481e812547f32b0d9895c7cd975b6f2a8a5ec41c88d23","tools": ["tool_result_read","list_shared_computers",@@ -1417,8 +1417,8 @@]},"default+no-computer-pick": {- "bytes": 57616,- "sha256": "0d4c7eb2d214eb47ca111a1d2f0cc8cf990a730f65e4be9829821be5b97b06dd",+ "bytes": 57938,+ "sha256": "166f63a6db8d03946685d5ac3f4a19543bf432e73247e581ced295db516301b3","tools": ["tool_result_read","list_room_targets",@@ -1474,8 +1474,8 @@]},"default+room": {- "bytes": 54176,- "sha256": "5712832949edbc37c2d3f0141d292b6ae2910e0e91f73a900a32e5da17dab9b2",+ "bytes": 54498,+ "sha256": "524bc95d73a6615118ac1e2046b1127b2a03cd70c39af6a13f8355bca99915c6","tools": ["tool_result_read","list_room_targets",@@ -1525,8 +1525,8 @@]},"non-chief+room": {- "bytes": 45628,- "sha256": "05c64d2fe12e3fa0cd6cc913cda686ee507123b956313f5c5893337e301f16c2",+ "bytes": 45950,+ "sha256": "6c9adbd8d773f221721c9de7480bff98dd9a8a7dbeb13ad85ee8174260303a62","tools": ["tool_result_read","list_room_targets",@@ -1569,8 +1569,8 @@]},"default+images": {- "bytes": 60775,- "sha256": "0843c41a1e3a7d891dbb8d0c767c614581f9123570d1bfd19286813d4c94c604",+ "bytes": 61097,+ "sha256": "be3b50b9d9af59b49c4351fb4325a5e6f4464f9dbcd290478592f60fceae7930","tools": ["tool_result_read","list_room_targets",@@ -1629,8 +1629,8 @@]},"skills+shared+voice+x+team+images+hosting": {- "bytes": 71844,- "sha256": "cdab3567ed19c7d4bd0a97614ddfe0421521913d19e63f9065ced6e4f73328cf",+ "bytes": 72166,+ "sha256": "cf23e493648e6b5d84eb24e46af77cd195a392c8874fd8cabbcef8037eb19f0c","tools": ["tool_result_read","list_shared_computers",@@ -1700,8 +1700,8 @@]},"default+hosting": {- "bytes": 60691,- "sha256": "ddfd0a210f66b3872a37eceff61fa185deeb866a5cca123bd54a50e9dfa4e3cb",+ "bytes": 61013,+ "sha256": "2a8c6ea3ec2012679a3e83477e57251e6f3d713a11dd06982151e6453e6e6844","tools": ["tool_result_read","list_room_targets",@@ -1760,8 +1760,8 @@]},"default+tools-off": {- "bytes": 54510,- "sha256": "4bc1783522425f2423926b2f68a7bdcd2959a2a592af06c454e7cf19db7aaf7d",+ "bytes": 54832,+ "sha256": "a88239561832405da5239a29d73e2743fa7c4968065ec40ffa0ce9c16beb9f35","tools": ["tool_result_read","list_room_targets",diff --git a/server/drivers/agents-catalog-wire.test.ts b/server/drivers/agents-catalog-wire.test.tsindex c737fbea73..2d44fc68d8 100644--- a/server/drivers/agents-catalog-wire.test.ts+++ b/server/drivers/agents-catalog-wire.test.ts@@ -87,37 +87,37 @@ const FULL = "skills+shared+voice+x+team+images+hosting";/** Bytes when the budget was last set; a profile may move at most 2% either way (lower it to lock in a win). */const BUDGET_BASELINE: Record<string, number> = {- "default": 57945,- "voice": 58726,- "shared": 60210,- "shared+voice": 60991,- "skills": 60031,- "skills+voice": 60812,- "skills+shared": 62296,- "skills+shared+voice": 63077,- "non-chief": 49528,- "voice+non-chief": 50309,- "shared+non-chief": 51793,- "shared+voice+non-chief": 52574,- "skills+non-chief": 51614,- "skills+voice+non-chief": 52395,- "skills+shared+non-chief": 53879,- "skills+shared+voice+non-chief": 54660,- "skills+shared+voice+cloud-home": 62843,- "skills+shared+voice+non-chief+cloud-home": 54426,- "default+legacy-switches": 57945,- "default+mausbot": 58596,- "skills+shared+voice+mausbot": 63728,- "skills+shared+voice+x": 67179,- "skills+shared+voice+x+team": 67179,- "default+no-computer-pick": 56733,- "default+room": 53729,- "non-chief+room": 45312,- "skills+shared+voice+x+team+images": 69244,- "default+images": 60010,- "skills+shared+voice+x+team+images+hosting": 71107,- "default+hosting": 59808,- "default+tools-off": 54421,+ "default": 58267,+ "voice": 59048,+ "shared": 60532,+ "shared+voice": 61313,+ "skills": 60353,+ "skills+voice": 61134,+ "skills+shared": 62618,+ "skills+shared+voice": 63399,+ "non-chief": 49850,+ "voice+non-chief": 50631,+ "shared+non-chief": 52115,+ "shared+voice+non-chief": 52896,+ "skills+non-chief": 51936,+ "skills+voice+non-chief": 52717,+ "skills+shared+non-chief": 54201,+ "skills+shared+voice+non-chief": 54982,+ "skills+shared+voice+cloud-home": 63165,+ "skills+shared+voice+non-chief+cloud-home": 54748,+ "default+legacy-switches": 58267,+ "default+mausbot": 58918,+ "skills+shared+voice+mausbot": 64050,+ "skills+shared+voice+x": 67501,+ "skills+shared+voice+x+team": 67501,+ "default+no-computer-pick": 57055,+ "default+room": 54051,+ "non-chief+room": 45634,+ "skills+shared+voice+x+team+images": 69566,+ "default+images": 60332,+ "skills+shared+voice+x+team+images+hosting": 71429,+ "default+hosting": 60130,+ "default+tools-off": 54743,};const RPC_PREFIX = '{"jsonrpc":"2.0","id":1,"result":';diff --git a/server/drivers/agents-usage-tool.test.ts b/server/drivers/agents-usage-tool.test.tsindex 4dac3033d6..37e3655a5e 100644--- a/server/drivers/agents-usage-tool.test.ts+++ b/server/drivers/agents-usage-tool.test.ts@@ -22,6 +22,18 @@ describe("the usage_limits tool", () => {await expect(callTool(USAGE_LIMITS_TOOL, {}, asked)).resolves.toEqual({ text: '{"accounts":[]}' });});+ it("reads bot usage only when the caller selects it", async () => {+ const asked = context({ ok: true, body: { text: '{"totals":{"input":12}}' } });+ await expect(callTool(USAGE_LIMITS_TOOL, { scope: "bot", period: "month", thread: "this" }, asked))+ .resolves.toEqual({ text: '{"totals":{"input":12}}' });+ expect(asked.client.apiResponse).toHaveBeenCalledWith("/api/internal/engine-limits?scope=bot&period=month&thread=this");++ vi.mocked(asked.client.apiResponse).mockClear();+ await expect(callTool(USAGE_LIMITS_TOOL, { scope: "subscription", thread: "this" }, asked))+ .resolves.toMatchObject({ isError: true });+ expect(asked.client.apiResponse).not.toHaveBeenCalled();+ });+it("hands the bot the route's answer, and its refusal as an error", async () => {const asked = context({ ok: true, body: { text: '{"accounts":[]}' } });await expect(callUsageLimitsTool(asked)).resolves.toEqual({ text: '{"accounts":[]}' });diff --git a/server/drivers/agents-usage-tool.ts b/server/drivers/agents-usage-tool.tsindex 6d1a717a4c..fd07d245b8 100644--- a/server/drivers/agents-usage-tool.ts+++ b/server/drivers/agents-usage-tool.ts@@ -1,16 +1,26 @@-// The agents catalog's usage_limits tool: one read of the plan-usage data the app's own Usage page shows. The internal-// route (server/routes/engine-limits.ts) decides which accounts this conversation may see.import type { ToolCallContext, ToolCallResult } from "./agents-call.ts";export const USAGE_LIMITS_TOOL = "usage_limits";-export async function callUsageLimitsTool(context: ToolCallContext): Promise<ToolCallResult> {- const { ok, body } = await context.client.apiResponse("/api/internal/engine-limits");+export async function callUsageLimitsTool(context: Pick<ToolCallContext, "client">, args: Record<string, unknown> = {}): Promise<ToolCallResult> {+ const { scope, period, thread } = args;+ if (scope !== undefined && scope !== "subscription" && scope !== "bot") return { text: "scope must be subscription or bot.", isError: true };+ if (scope !== "bot" && (period !== undefined || thread !== undefined)) return { text: "period and thread require scope: bot.", isError: true };+ if (period !== undefined && period !== "today" && period !== "month") return { text: "period must be today or month.", isError: true };+ if (thread !== undefined && thread !== "this") return { text: "thread must be this or omitted.", isError: true };++ const path = "/api/internal/engine-limits";+ const query = new URLSearchParams({ scope: "bot", ...(period ? { period } : {}), ...(thread ? { thread } : {}) });+ const { ok, body } = await context.client.apiResponse(scope === "bot" ? `${path}?${query}` : path);return ok ? { text: String(body.text ?? "") } : { text: String(body.error ?? "Usage limits could not be read. Try again shortly."), isError: true };}export const USAGE_LIMITS_TOOL_DEFINITION = {name: USAGE_LIMITS_TOOL,- description: "Each AI account's usage limits: percent used, reset time, when checked. status: ok, unknown (no data now; see why) or unsupported.",- inputSchema: { type: "object", additionalProperties: false, properties: {} },+ description: "AI subscription limits and reset times by default. With scope bot, read this bot's visible tokens, estimated cost and usage cap headroom. Bot periods use UTC.",+ inputSchema: { type: "object", additionalProperties: false, properties: {+ scope: { type: "string", enum: ["subscription", "bot"], default: "subscription" },+ period: { type: "string", enum: ["today", "month"], description: "Bot scope only. Defaults to today." },+ thread: { type: "string", enum: ["this"], description: "Bot scope only. Omit for all visible conversations." },+ } },};diff --git a/server/index.ts b/server/index.tsindex 2785c558d7..3b17319a22 100644--- a/server/index.ts+++ b/server/index.ts@@ -12329,7 +12329,7 @@ ROUTES.push(createBrowserViewerRoutes({restartRefusal: (session) => browserRestartRefusal(browserRuntime.interrupted(session), store.bots.filter((candidate) => candidate.busy&& browserSessionsOf(candidate.id, candidate.browserProfile).includes(session)).map((candidate) => ({ waitingOnBrowser: computerControl.snapshot(candidate.id).help?.place === "browser" }))),}));-const internalToolRoutes = createInternalToolRoutes({ engineLimits: { instances: () => registry.instances(), configs: () => instanceConfigs(cfg), status: (instanceId) => registry.knownSnapshot(instanceId), load: (accounts) => loadPlanUsage({ accounts }), audienceOf: (threadId) => teamHost.audienceOf(threadId), guestDriven: cloudGuestDriven, dataDir: DATA_DIR }, helpers: { decider, extractor }, notifications: { bot: (id) => store.bot(id), team: sharedMembership, broadcast }, xResearch: { credential: () => researchCredential(cfg.treg?.key), botEnabled: (botId) => store.bot(botId)?.xResearch !== false, cloudHome: CLOUD_HOME !== null, researchOff: () => researchAvailability.refused() }, appPublisher }); const waitRoutes = createWaitRoutes({ waits: botWaits, cloudHome: Boolean(CLOUD_HOME), sleeps: Boolean(CLOUD_HOME) && CLOUD_TEAM === null }); ROUTES.push(createXConnectorRoutes({ credential: () => researchCredential(cfg.treg?.key), included: () => xCredential(), unavailable: () => xResearchStatus().unavailable === true }));+const internalToolRoutes = createInternalToolRoutes({ botUsage: { dataDir: DATA_DIR, guestDriven: cloudGuestDriven, caps: () => cfg.usageCaps, onPlan: (id) => registry.lastSnapshot(id)?.billing === "subscription", bot: (id) => store.bot(id), readableFrom: threadReadableFrom, crossThreadReads: () => Boolean(CLOUD_HOME || ownHome.ownServer()), knownThread: (botId, threadId) => Boolean(connectorThread(botId, threadId)) }, engineLimits: { instances: () => registry.instances(), configs: () => instanceConfigs(cfg), status: (instanceId) => registry.knownSnapshot(instanceId), load: (accounts) => loadPlanUsage({ accounts }), audienceOf: (threadId) => teamHost.audienceOf(threadId), guestDriven: cloudGuestDriven, dataDir: DATA_DIR }, helpers: { decider, extractor }, notifications: { bot: (id) => store.bot(id), team: sharedMembership, broadcast }, xResearch: { credential: () => researchCredential(cfg.treg?.key), botEnabled: (botId) => store.bot(botId)?.xResearch !== false, cloudHome: CLOUD_HOME !== null, researchOff: () => researchAvailability.refused() }, appPublisher }); const waitRoutes = createWaitRoutes({ waits: botWaits, cloudHome: Boolean(CLOUD_HOME), sleeps: Boolean(CLOUD_HOME) && CLOUD_TEAM === null }); ROUTES.push(createXConnectorRoutes({ credential: () => researchCredential(cfg.treg?.key), included: () => xCredential(), unavailable: () => xResearchStatus().unavailable === true }));// Live calls: the client holds the WebRTC audio; the key never leaves the harness, which creates the session.function liveBotFor(botId: string): LiveBot {@@ -12832,7 +12832,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {throw Object.assign(new Error(TURN_ENDED_REFUSAL), { status: 401 });}};- const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await lentMcp.route({ method, path, req, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS || await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await cloudComputerResets.internal({ method, path, res, json, sender: internalSender, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await meetingsHost.internal({ method, path, res, json, readBody: readInternalBody, bot: internalSender, threadId: internalCapability.threadId, active: () => internalCapabilityIsActive(internalCapability) }) !== PASS || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, folders: botFolders, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS || await share.tool({ method, path, res, json, readBody: readInternalBody, bot: internalSender, threadId: internalCapability.threadId, roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), actsForAdmin: teamConnections.actsForAdmin(internalCapability.threadId, internalCapability.generation), githubPerson: teamConnections.turnPerson(internalCapability.threadId, internalCapability.generation), actingName: CLOUD_TEAM ? teamHost.personName(actingPeople.requester(internalCapability.threadId, internalCapability.generation)) : undefined, personMessage: turnOrigin(internalCapability).kind === "user" ? store.messagesFor(internalCapability.threadId).find((line) => line.role === "user" && line.id === (directRequestOwners.get(internalCapability.threadId)?.messageId ?? roomRun(internalCapability.generation)?.requestMessageId))?.text ?? null : null, post: (text, template) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return source ? store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, template, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id : null; } }) !== PASS) return; const callSignal = turnCallSignals.signal(internalCapability, res); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: callSignal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle, bot: internalSender })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;+ const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await lentMcp.route({ method, path, req, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS || await internalToolRoutes({ method, path, url, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders, requireActive: requireActiveInternalCapability }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await cloudComputerResets.internal({ method, path, res, json, sender: internalSender, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await meetingsHost.internal({ method, path, res, json, readBody: readInternalBody, bot: internalSender, threadId: internalCapability.threadId, active: () => internalCapabilityIsActive(internalCapability) }) !== PASS || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, folders: botFolders, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS || await share.tool({ method, path, res, json, readBody: readInternalBody, bot: internalSender, threadId: internalCapability.threadId, roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), actsForAdmin: teamConnections.actsForAdmin(internalCapability.threadId, internalCapability.generation), githubPerson: teamConnections.turnPerson(internalCapability.threadId, internalCapability.generation), actingName: CLOUD_TEAM ? teamHost.personName(actingPeople.requester(internalCapability.threadId, internalCapability.generation)) : undefined, personMessage: turnOrigin(internalCapability).kind === "user" ? store.messagesFor(internalCapability.threadId).find((line) => line.role === "user" && line.id === (directRequestOwners.get(internalCapability.threadId)?.messageId ?? roomRun(internalCapability.generation)?.requestMessageId))?.text ?? null : null, post: (text, template) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return source ? store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, template, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id : null; } }) !== PASS) return; const callSignal = turnCallSignals.signal(internalCapability, res); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: callSignal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle, bot: internalSender })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;const delegatedThisTurn = (taskId: string) => {(internalCapability.delegatedThisTurn ??= new Set()).add(taskId);};diff --git a/server/routes/bot-usage.test.ts b/server/routes/bot-usage.test.tsnew file mode 100644index 0000000000..e4f6f797cb--- /dev/null+++ b/server/routes/bot-usage.test.ts@@ -0,0 +1,97 @@+import { mkdirSync, mkdtempSync } from "node:fs";+import type { ServerResponse } from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import { mayRead, type Audience } from "../audience.ts";+import { removeTempDir } from "../testing/cleanup.ts";+import { appendUsage, type UsageRow } from "../usage-ledger.ts";+import { createBotUsageRoute } from "./bot-usage.ts";++const now = new Date("2026-11-18T14:00:00Z");+let dataDir: string;+beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), "omb-bot-usage-")); });+afterEach(() => removeTempDir(dataDir));++const row = (fields: Partial<UsageRow> = {}): UsageRow => ({+ at: "2026-11-18T12:00:00Z", botId: "scout", botName: "Scout", threadId: "here", instanceId: "private-account",+ driverKind: "claude", model: "test-model", input: 10, cachedInput: 3, output: 2, costUsd: null,+ trigger: { kind: "user", email: "[email protected]" }, ...fields,+});++const audiences = new Map<string, Audience>([["here", "team"], ["older", "team"], ["private", "member:other"], ["peer", "team"]]);+const readableFrom = (threadId: string) => (otherThreadId: string) => {+ const audience = audiences.get(otherThreadId);+ return audience !== undefined && mayRead(audience, audiences.get(threadId)!);+};++async function query(args: string, deps: Partial<Parameters<typeof createBotUsageRoute>[0]> = {}, botId = "scout") {+ const path = "/api/internal/engine-limits";+ const json = vi.fn();+ const route = createBotUsageRoute({ dataDir, env: {}, now: () => now, guestDriven: () => false, caps: () => undefined,+ readableFrom, crossThreadReads: () => true, knownThread: (_botId, threadId) => audiences.has(threadId),+ bot: (id) => ({ id, name: id }), onPlan: () => false, ...deps });+ const url = new URL(`http://localhost${path}${args}`);+ url.searchParams.set("scope", "bot");+ await route({ method: "GET", path, url, res: {} as ServerResponse, json, botId, threadId: "here", requireActive() {} });+ const [, status, body] = json.mock.calls[0]!;+ return { status, body, result: body.text ? JSON.parse(body.text) : null };+}++it("reports only the caller's visible usage and never returns the ledger row", async () => {+ const seeded = [+ row({ contextTokens: 30, contextWindow: 120, outcome: { status: "error", reason: "private-text" } }),+ row({ at: "2026-11-17T12:00:00Z", threadId: "older", costUsd: 0.01 }),+ row({ at: "2026-10-31T23:59:59Z", input: 700 }),+ row({ threadId: "private", input: 800, costUsd: 9 }),+ row({ threadId: "deleted", input: 900 }),+ row({ botId: "other", threadId: "peer", input: 222 }),+ ];+ for (const entry of seeded) expect(await appendUsage(dataDir, entry)).toBe(true);++ const { result, body } = await query("");+ expect(result).toMatchObject({+ period: "today", timeZone: "UTC", totals: { turns: 1, input: 10, output: 2, cachedInput: 3, barTokens: 9, costUsd: null, unpricedTurns: 1 },+ context: { contextTokens: 30, contextWindow: 120 }, caps: [], capsComplete: true,+ });+ expect(body.text).not.toMatch(/private-account|private@example|private-text|deleted/);+ expect((await query("?period=month", { onPlan: () => true })).result.totals).toMatchObject({+ turns: 2, input: 20, costUsd: 0.01, unpricedTurns: 1, notBilled: { usd: 0.01, turns: 1 },+ });+ expect((await query("?period=month&thread=this")).result.totals.turns).toBe(1);+ expect((await query("", {}, "other")).result.totals).toMatchObject({ turns: 1, input: 222 });+});++it("shows exact cap headroom only when all contributing rows are readable", async () => {+ await appendUsage(dataDir, row({ costUsd: 0.01 }));+ await appendUsage(dataDir, row({ threadId: "private", costUsd: 0.10 }));+ const caps = () => ({ server: { dailyUsd: 0.20 }, bots: { scout: { dailyTokens: 18, monthlyUsd: 0.11 }, other: { dailyTokens: 45 } } });+ const own = await query("", { caps, readableFrom: () => () => true });+ expect(own.result.capsComplete).toBe(true);+ expect(own.result.caps).toEqual([+ expect.objectContaining({ scope: "server", used: 0.11, reached: false }),+ expect.objectContaining({ scope: "bot", unit: "usd", remaining: 0, reached: true, resetsAt: Date.parse("2026-12-01T00:00:00Z") }),+ expect.objectContaining({ scope: "bot", unit: "tokens", used: 18, remaining: 0, reached: true, resetsAt: Date.parse("2026-11-19T00:00:00Z") }),+ ]);+ const shared = await query("", { caps });+ expect(shared.result).toMatchObject({ caps: [], capsComplete: false, stops: null, totals: { turns: 1, costUsd: 0.01 } });+ expect(shared.body.text).not.toContain("0.11");+});++it("refuses guest turns and unbounded filters", async () => {+ expect((await query("", { guestDriven: () => true })).status).toBe(403);+ let guestChecks = 0;+ expect((await query("", { guestDriven: () => ++guestChecks === 2 })).status).toBe(403);+ expect((await query("?period=year")).status).toBe(400);+ expect((await query("?thread=private")).status).toBe(400);+});++it("reports a failed month read without claiming zero usage or full headroom", async () => {+ const caps = () => ({ server: { dailyTokens: 20 } });+ expect((await query("", { caps })).result.caps[0]).toMatchObject({ used: 0, remaining: 20 });+ mkdirSync(join(dataDir, "usage", "2026-11.jsonl"), { recursive: true });+ const failed = await query("", { caps });+ expect(failed.status).toBe(503);+ expect(failed.result).toBeNull();+});diff --git a/server/routes/bot-usage.ts b/server/routes/bot-usage.tsnew file mode 100644index 0000000000..71c76b3573--- /dev/null+++ b/server/routes/bot-usage.ts@@ -0,0 +1,103 @@+import type { ServerResponse } from "node:http";++import type { json as sendJson } from "../harness/http.ts";+import { canReach, type RosterMember } from "../peer-roster.ts";+import { capStates, capTokens, dayKey, effectiveCaps, type CapState, type UsageCapsConfig } from "../usage-caps.ts";+import { flushUsageLedger, parseUsageRange, readUsage, summarizeUsage, type UsageRow } from "../usage-ledger.ts";+import { PASS } from "./table.ts";+import { notBilledShare } from "./usage.ts";++interface BotUsageDeps {+ dataDir: string;+ guestDriven(threadId: string): boolean;+ readableFrom(threadId: string): (otherThreadId: string) => boolean;+ crossThreadReads(): boolean;+ knownThread(botId: string, threadId: string): boolean;+ bot(botId: string): RosterMember | null;+ caps(): UsageCapsConfig | undefined;+ onPlan(instanceId: string): boolean;+ env?: NodeJS.ProcessEnv;+ now?(): Date;+}++const GUEST_REFUSAL = "Bot usage belongs to this workspace, and this conversation was started by someone else.";++function visibleUsageRows(rows: UsageRow[], deps: BotUsageDeps, botId: string, threadId: string): Set<UsageRow> {+ const caller = deps.bot(botId);+ const canReadThread = deps.readableFrom(threadId);+ const crossThread = deps.crossThreadReads();+ const checked = new Map<string, Map<string, boolean>>();+ return new Set(rows.filter((row) => {+ if (typeof row.threadId !== "string" || !row.threadId || (!crossThread && row.threadId !== threadId)) return false;+ let threads = checked.get(row.botId);+ if (!threads) checked.set(row.botId, threads = new Map());+ const cached = threads.get(row.threadId);+ if (cached !== undefined) return cached;+ const source = deps.bot(row.botId);+ const visible = Boolean(caller && source && (source.id === caller.id || canReach(caller, source))+ && deps.knownThread(row.botId, row.threadId) && canReadThread(row.threadId) && !deps.guestDriven(row.threadId));+ threads.set(row.threadId, visible);+ return visible;+ }));+}++function capUsedBy(row: UsageRow, cap: CapState): number {+ if (cap.unit === "tokens") return capTokens(row);+ return typeof row.costUsd === "number" && Number.isFinite(row.costUsd) && row.costUsd > 0 ? row.costUsd : 0;+}++function visibleCap(cap: CapState, rows: UsageRow[], visible: ReadonlySet<UsageRow>) {+ const { scope, period, unit, limit, used, percent, warn, reached, resetsAt } = cap;+ let visibleUsed = 0;+ for (const row of rows) {+ if (!row.at.startsWith(cap.periodKey) || (scope === "bot" && row.botId !== cap.botId)) continue;+ const amount = capUsedBy(row, cap);+ if (amount > 0 && !visible.has(row)) return null;+ visibleUsed += amount;+ }+ // Never disclose a cap total that includes a contribution outside the visible ledger snapshot.+ if (visibleUsed !== used) return null;+ return { scope, period, unit, limit, used, remaining: Math.max(0, limit - used), percent, warn, reached, resetsAt };+}++export function createBotUsageRoute(deps: BotUsageDeps) {+ return async (ctx: { method: string; path: string; url: URL; res: ServerResponse; json: typeof sendJson; botId: string; threadId: string; requireActive(): void }): Promise<typeof PASS | void> => {+ if (ctx.method !== "GET" || ctx.path !== "/api/internal/engine-limits" || ctx.url.searchParams.get("scope") !== "bot") return PASS;+ if (deps.guestDriven(ctx.threadId)) return void ctx.json(ctx.res, 403, { error: GUEST_REFUSAL });+ const period = ctx.url.searchParams.get("period") ?? "today";+ const thread = ctx.url.searchParams.get("thread");+ if ((period !== "today" && period !== "month") || (thread !== null && thread !== "this")) {+ return void ctx.json(ctx.res, 400, { error: "period must be today or month, and thread must be this or omitted." });+ }++ await flushUsageLedger(deps.dataDir);+ ctx.requireActive();+ if (deps.guestDriven(ctx.threadId)) return void ctx.json(ctx.res, 403, { error: GUEST_REFUSAL });+ const now = deps.now?.() ?? new Date();+ const month = parseUsageRange(null, null, now)!;+ let ledger: UsageRow[];+ try {+ ledger = readUsage(deps.dataDir, month, { requireReadable: true });+ } catch {+ return void ctx.json(ctx.res, 503, { error: "The usage ledger could not be read. Try again shortly." });+ }+ const visible = visibleUsageRows(ledger, deps, ctx.botId, ctx.threadId);+ const today = dayKey(now);+ const rows = [...visible].filter((row) => row.botId === ctx.botId+ && (period === "month" || row.at.startsWith(today)) && (thread === null || row.threadId === ctx.threadId));+ const { turns, input, output, cachedInput, barTokens, costUsd, unpriced } = summarizeUsage(rows, "bot").total;+ const latest = rows.filter((row) => row.threadId === ctx.threadId && Number.isFinite(row.contextTokens) && Number.isFinite(row.contextWindow))+ .reduce<UsageRow | undefined>((previous, row) => !previous || row.at >= previous.at ? row : previous, undefined);++ const config = deps.caps();+ const states = capStates(config, deps.dataDir, now, deps.env, ctx.botId);+ const caps = states.map((cap) => visibleCap(cap, ledger, visible)).filter((cap) => cap !== null);+ return void ctx.json(ctx.res, 200, { text: JSON.stringify({+ period, thread: thread ?? "visible", timeZone: "UTC",+ totals: { turns, input, output, cachedInput, barTokens, costUsd, unpricedTurns: unpriced, notBilled: notBilledShare(rows, deps.onPlan) },+ context: latest ? { contextTokens: latest.contextTokens, contextWindow: latest.contextWindow } : null,+ caps, capsComplete: states.length === caps.length, stops: caps.length ? effectiveCaps(config, deps.env).stops : null,+ note: "Usage covers settled turns visible to this conversation. Dollar amounts are estimates; unpriced turns have no cost estimate. An incomplete cap list means some cap totals are unavailable here.",+ }) });+ };+}diff --git a/server/routes/internal-tools.ts b/server/routes/internal-tools.tsindex 38172bfc9d..1098ea801f 100644--- a/server/routes/internal-tools.ts+++ b/server/routes/internal-tools.ts@@ -3,15 +3,16 @@// capability bearer is checked; each route answers its own paths and passes the rest on.import type { AppPublisher } from "../host/app-publisher.ts";import { createAppHostingInternalRoutes } from "./app-hosting.ts";+import { createBotUsageRoute } from "./bot-usage.ts";import { createEngineLimitsRoutes, type EngineLimitsDeps } from "./engine-limits.ts";import { createHelperToolRoutes, type HelperToolContext, type HelperToolDeps } from "./helper-tools.ts";import { createMausBotNotificationRoutes, type LiveNotificationsDeps } from "./mausbot-notifications.ts";import { PASS } from "./table.ts";import { createXResearchInternalRoutes, type XResearchDeps } from "./x-research.ts";-export function createInternalToolRoutes(deps: { helpers: HelperToolDeps; xResearch: XResearchDeps; notifications: LiveNotificationsDeps; engineLimits: EngineLimitsDeps; appPublisher: AppPublisher }) {- const routes = [createXResearchInternalRoutes(deps.xResearch), createHelperToolRoutes(deps.helpers), createMausBotNotificationRoutes(deps.notifications), createEngineLimitsRoutes(deps.engineLimits), createAppHostingInternalRoutes(deps.appPublisher)];- return async (ctx: HelperToolContext & { threadId: string }): Promise<typeof PASS | void> => {+export function createInternalToolRoutes(deps: { helpers: HelperToolDeps; xResearch: XResearchDeps; notifications: LiveNotificationsDeps; engineLimits: EngineLimitsDeps; botUsage: Parameters<typeof createBotUsageRoute>[0]; appPublisher: AppPublisher }) {+ const routes = [createXResearchInternalRoutes(deps.xResearch), createHelperToolRoutes(deps.helpers), createMausBotNotificationRoutes(deps.notifications), createBotUsageRoute(deps.botUsage), createEngineLimitsRoutes(deps.engineLimits), createAppHostingInternalRoutes(deps.appPublisher)];+ return async (ctx: HelperToolContext & { threadId: string; url: URL; requireActive(): void }): Promise<typeof PASS | void> => {for (const route of routes) if (await route(ctx) !== PASS) return;return PASS;};diff --git a/server/usage-ledger.ts b/server/usage-ledger.tsindex 51a87a1122..34a523a5d9 100644--- a/server/usage-ledger.ts+++ b/server/usage-ledger.ts@@ -200,12 +200,13 @@ function parseMonth(text: string): ParsedFile["rows"] {/** The file's valid rows in file order, parsed again only when its size, times or identity changed. Callers share the* row objects and must not change them. */-function monthRows(file: string): ParsedFile["rows"] {+function monthRows(file: string, requireReadable: boolean): ParsedFile["rows"] {let fd: number;try {fd = openSync(file, "r");- } catch {+ } catch (error) {parsedFiles.delete(file);+ if (requireReadable && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;return [];}try {@@ -219,20 +220,21 @@ function monthRows(file: string): ParsedFile["rows"] {parsedFiles.set(file, { stamp, rows });if (parsedFiles.size > PARSED_FILES_KEPT) parsedFiles.delete(parsedFiles.keys().next().value!);return rows;- } catch {+ } catch (error) {parsedFiles.delete(file);+ if (requireReadable) throw error;return [];} finally {closeSync(fd);}}-export function readUsage(dataDir: string, range: { from: Date; to: Date }): UsageRow[] {+export function readUsage(dataDir: string, range: { from: Date; to: Date }, { requireReadable = false } = {}): UsageRow[] {const rows: UsageRow[] = [];const from = range.from.getTime();const to = range.to.getTime();for (const key of monthsBetween(range.from, range.to)) {- for (const { at, row } of monthRows(join(dataDir, DIR, `${key}.jsonl`))) {+ for (const { at, row } of monthRows(join(dataDir, DIR, `${key}.jsonl`), requireReadable)) {if (at >= from && at <= to) rows.push(row);}}