Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Usage caps: optional day and month caps for the server and each bot, in every edition (#6170)
Milind Soni344b33cd4a88
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 572f51c972..44faa084e7 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -1201,6 +1201,19 @@ curl -H "Authorization: Bearer $TOKEN" -o usage.csv \Dates are inclusive, UTC, at most a year apart; without them you get thecurrent month to date.+### Usage caps++By default nothing limits what the bots use. The owner can cap a day's and a+month's usage, for the whole server and for each bot, in estimated dollars+and in tokens, under **Settings → Usage → Usage caps**, in `config.json`, or+for the server's own caps in the environment+(`OMB_USAGE_CAP_DAILY_USD`, `OMB_USAGE_CAP_MONTHLY_USD`,+`OMB_USAGE_CAP_DAILY_TOKENS`, `OMB_USAGE_CAP_MONTHLY_TOKENS`,+`OMB_USAGE_CAP_STOPS`). A reached cap stops new unattended work (routines,+webhooks, app events, Bot API calls, hand-offs nobody is waiting on) until+the day or month rolls over, and cuts nothing off mid-turn.+[Usage caps](usage-caps.md) has every setting and what a person sees.+### When an engine runs outWhen a turn ends on a usage limit (a subscription's 5-hour or weekly limit,diff --git a/docs/usage-caps.md b/docs/usage-caps.mdnew file mode 100644index 0000000000..d5fca45ea7--- /dev/null+++ b/docs/usage-caps.md@@ -0,0 +1,158 @@+# Usage caps++A server that runs many bots unattended can use a lot before anyone looks.+Usage caps let its owner set a limit on a day's and a month's usage, for the+whole server and for each bot. They are part of every edition, and none is+set by default: a server whose owner sets nothing behaves as it always has.++## What can be capped++| Setting | Counts | Period |+| --- | --- | --- |+| `dailyUsd` | estimated dollars | the UTC day |+| `monthlyUsd` | estimated dollars | the UTC month |+| `dailyTokens` | tokens | the UTC day |+| `monthlyTokens` | tokens | the UTC month |++Each of the four can be set for the server (everything its bots use+together) and for any one bot. Empty or `0` means no cap. A bot's work counts+against its own caps and the server's; whichever is reached first stops it.++**Dollars** are the usage ledger's figure: what the engine reported, or+tokens times a list price for engines that report none. That figure is+notional when the AI is signed in with a subscription (nobody is billed it),+and `$0` for a model that has no price. **Tokens** always count: a token cap+counts fresh input plus output, the same sum the Usage page's bars show. On a+subscription sign-in, or with unpriced models, cap tokens.++Days and months are UTC, as the usage ledger's are. The reset time is shown+in the server's own time zone.++## What a reached cap stops++`stops` chooses, for all caps together:++- `unattended` (the default once any cap is set): routines, webhooks, app+ events, Bot API calls, and hand-offs in work no person started. A person's+ own message always runs, and so does a routine run they start by hand, a+ webhook's Run now test, and the hand-offs their message leads to.+- `everything`: a person's own messages too, and the helper model's side+ jobs (titles, memory upkeep), which only the server's caps stop.++Nothing is cut off mid-turn. A turn that is running when the cap is reached+finishes; a cap is checked only before new work starts, so the last turn can+take the total past the limit. Work that already started carries on under a+reached cap: a run whose hand-off comes back with its result, one whose owner+answers a card it asked, or one a restart picks up again.++## What a person sees++**At 80% of a cap:** one line in the server log+(`usage cap at 81%: server:day:usd $8.10 of $10.00`), and the cap's bar on+Settings → Usage turns amber with "At 81% of the cap". Nothing else: no+notification, no card.++**When a cap is reached:** one notice in the owner's notifications for that+cap and that period ("Usage cap reached: Unattended work is skipped until+Nov 17, 5:30 AM (Asia/Kolkata): the daily usage cap for all bots ($10.00) is+reached. Your own messages still run."), one line in the server log, and the bar turns red+with when work starts again. The notice is not repeated, however much work is+skipped after it, and not after a restart. No popup, card or approval asks+anything.++Each piece of work the cap keeps from starting leaves one line:++- **A routine's scheduled run** is skipped and counted on one row in the+ routine's run log per cap and period: "Skipped 14 runs: the daily usage+ cap for all bots ($10.00) is reached. Runs start again after Nov 17,+ 5:30 AM (Asia/Kolkata)". Each routine keeps its own row. The routine stays+ on and nothing lands under To review. A one-time routine is not used up:+ it stays on, its time moves to when the cap resets, and it runs then.+ A run already queued when the cap was reached (a webhook's, an app+ event's) is let go quietly with the same reason, as a paused bot's is.+- **A hand-off** nobody is waiting on is refused to the bot that asked, which+ says so in one line in its own thread and does not route around the cap.+- **A Bot API call** answers `429` with a `Retry-After` header and+ "This bot has reached a usage cap its owner set, so it takes no new calls+ for now. Try again after …". The call is listed on the bot's Bot API card.+- **A webhook delivery** answers `429` with the reason, and is listed among+ the webhook's deliveries.+- **A person's message**, only under `everything`, is refused with the+ reason in place (`409`, code `spend_cap`).++**At reset:** nothing is announced. When the UTC day or month rolls over,+or the owner raises or removes the cap, covered work starts again by itself:+the next scheduled run runs, the next call is answered. Repeating runs+skipped meanwhile are not made up; a one-time run that waited runs now.++## Where it is set++**Settings → Usage → Usage caps**, shown to the owner only (the `admin`+scope; on a Team Cloud, its admins). The card shows each cap's use now, and+saves `stops`, the server's caps and each bot's.++`config.json`, for a server with no screen:++```json+{+ "usageCaps": {+ "stops": "unattended",+ "server": { "dailyUsd": 20, "monthlyTokens": 500000000 },+ "bots": { "<bot id>": { "dailyUsd": 2, "dailyTokens": 5000000 } }+ }+}+```++The environment sets the server's caps and wins over `config.json`, field by+field; a value that is not a number is ignored:++| Variable | Sets |+| --- | --- |+| `OMB_USAGE_CAP_DAILY_USD` | `server.dailyUsd` |+| `OMB_USAGE_CAP_MONTHLY_USD` | `server.monthlyUsd` |+| `OMB_USAGE_CAP_DAILY_TOKENS` | `server.dailyTokens` (a whole number) |+| `OMB_USAGE_CAP_MONTHLY_TOKENS` | `server.monthlyTokens` (a whole number) |+| `OMB_USAGE_CAP_STOPS` | `unattended` or `everything` |++Per-bot caps are set in Settings or `config.json` only.++The API, for the owner:++- `GET /api/usage/caps`: `{ stops, savedStops, server, bots, env, caps }`,+ where `stops` is the choice in force and `savedStops` the one `config.json`+ holds, `caps` lists every cap in force with `limit`, `used`, `percent`,+ `warn`, `reached` and `resetsAt`, and `env` names what the environment+ holds (`env.values` its values). Settings shows the environment's values in+ the greyed fields, and a save there keeps `config.json`'s own values for+ them, never the environment's.+- `PUT /api/usage/caps` with `{ stops, server, bots }` replaces the saved+ caps. On a server other people sign in to, the change is recorded in+ Settings → Activity like any other settings change.++## With the licensed monthly spend limit++The licensed edition's **Monthly spend limit** (`budgets.monthlyUsd`, the+`budgets` entitlement) is unchanged: it stops every kind of turn, has its own+warning level, and notifies admins at the warning and at the limit. Both read+the same totals from the same engine (`server/usage-caps.ts`). When both are+set, each applies on its own, and whichever is reached first stops the work+it covers. A Bot API call it refuses answers `429` with a `Retry-After`+header up to the start of the next UTC month.++The totals are kept as running sums: a check reads the month's ledger file+once, and after that only the lines appended since, and only when the file's+size or time changed (looked at most every 15 seconds).++## Checks++```sh+pnpm exec vitest run server/usage-caps.test.ts+pnpm exec vitest run server/host/usage-cap-gate.test.ts+pnpm exec vitest run server/usage-caps.e2e.test.ts+```++The last launches the isolated fixture with the scripted engine: a cap set+through the API, a Bot API call refused with `429`, a routine's counted+skipped row, the owner's own message still answered, and the work starting+again once the cap is raised; and a webhook run whose hand-off comes back+after the cap is reached finishing its work.diff --git a/docs/verification/usage-ledger.md b/docs/verification/usage-ledger.mdindex 2bd0ad3634..b99a922715 100644--- a/docs/verification/usage-ledger.md+++ b/docs/verification/usage-ledger.md@@ -123,8 +123,10 @@ scope on both routes.## Gotchas-- Rows are appended when `turn.completed` folds. A turn that fails before it- settles leaves no row, so a failed turn is not billed.+- Rows are appended when `turn.completed` folds, whether the turn succeeded+ or failed: a failed turn is booked with the tokens and cost it reported, and+ its row carries the failed outcome. Only a turn that never settles (refused+ before it started, or the server stopped first) leaves no row.- The cost column is what the engine reported (real on a metered key, anequivalent on a subscription) or, for engines that report none, an estimatefrom `server/model-prices.ts`, marked `~` in History and People and labelleddiff --git a/scripts/control-omb.ts b/scripts/control-omb.tsindex f7962e33c2..a164e20e26 100644--- a/scripts/control-omb.ts+++ b/scripts/control-omb.ts@@ -182,6 +182,8 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, datafor (const key of ["OMB_UNATTENDED_TURN_MAX_MS", "OMB_UNATTENDED_TURN_MAX_REQUESTS", "OMB_UNATTENDED_TURN_MAX_DENIALS", "OMB_LOOP_GUARD_UNATTENDED_STOP_AT"]) if (parentEnv[key]) childEnv[key] = parentEnv[key];// Warm summaries' minutes as seconds (server/warm-summary.ts), and the switch that turns them off.for (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];// 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/admin-activity.ts b/server/admin-activity.tsindex a223a961e4..73f23b707b 100644--- a/server/admin-activity.ts+++ b/server/admin-activity.ts@@ -195,6 +195,7 @@ const pick = (source: unknown, paths: readonly string[]) =>const CONFIG_CATEGORY: Record<string, AdminActivityCategory> = {signIn: "people",budgets: "budget",+ usageCaps: "budget",billing: "budget",mcpServers: "mcp",instances: "engine",diff --git a/server/bot-api-host.test.ts b/server/bot-api-host.test.tsindex 5253ea7a43..ca1458cffa 100644--- a/server/bot-api-host.test.ts+++ b/server/bot-api-host.test.ts@@ -8,6 +8,8 @@ import { BotApiManager } from "./bot-api.ts";import { BOT_API_DEFAULT_WAIT_MS, createBotApiHost, type BotApiHostDeps, type BotApiTurnOptions } from "./bot-api-host.ts";import type { RequestAuth } from "./request-auth.ts";import type { Message } from "./store.ts";+import { assertWithinBudget, resetSpendCacheForTests } from "./spend.ts";+import { appendUsage } from "./usage-ledger.ts";import { createWebhookIngressHandler } from "./webhook-ingress.ts";import type { WebhookManager } from "./webhooks.ts";@@ -312,6 +314,30 @@ describe("the Bot API door on the webhook receiver", () => {expect(await refused.json()).toEqual({ error: "This Cloud moved" });});+ it("answers the licensed monthly spend limit with 429 and a Retry-After up to the next UTC month", async () => {+ const fake = fakeStore();+ const dir = mkdtempSync(join(tmpdir(), "omb-bot-api-budget-"));+ dirs.push(dir);+ resetSpendCacheForTests();+ await appendUsage(dir, { botId: "b1", botName: "b1", threadId: "t", instanceId: "claude", driverKind: "claudeAgent", model: "m", input: 1, output: 1, costUsd: 2, trigger: { kind: "owner" } });+ const host = createBotApiHost({+ store: fake.store, manager: new BotApiManager({ file: join(dir, "bot-api.json") }), waitMs: 5_000,+ startTurn: async () => assertWithinBudget({ budgets: { monthlyUsd: 1 } }, dir, new Date(), () => true),+ threadBusy: () => false, canStart: () => true, canConfine: () => true, hooksBaseUrl: () => "https://x", manageRefusal: () => null,+ });+ const key = host.manager.enable("b1").key;+ const server = createServer((req, res) => { void createWebhookIngressHandler({} as WebhookManager, undefined, host.door)(req, res); });+ servers.push(server);+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const answer = await fetch(`http://127.0.0.1:${(server.address() as { port: number }).port}/hooks/api/bots/b1/messages`, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json" }, body: JSON.stringify({ message: "Hi" }) });+ expect(answer.status).toBe(429);+ const now = new Date(), next = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);+ const retryAfter = Number(answer.headers.get("retry-after"));+ expect(retryAfter).toBeGreaterThan(0);+ expect(Math.abs(retryAfter - (next - Date.now()) / 1000)).toBeLessThan(60);+ resetSpendCacheForTests();+ });+it("shows what callers sent only to those who manage the key", async () => {const h = await harness(replies("ok"));const key = (await h.app("POST", "/api/bots/b1/bot-api", { enabled: true })).body.key as string;diff --git a/server/bot-api-host.ts b/server/bot-api-host.tsindex 8c4036c401..6a8416f184 100644--- a/server/bot-api-host.ts+++ b/server/bot-api-host.ts@@ -93,6 +93,7 @@ function callerWords(error: unknown): string {const COULD_NOT_ANSWER = "The bot could not answer. Open this thread in the app to see why.";const BUSY = "The bot is busy. Try again soon.";+const CAPPED = "This bot has reached a usage cap its owner set, so it takes no new calls for now.";const CANNOT_CONFINE = "This bot's AI can't take Bot API calls. Choose another AI for this bot.";const NO_LONGER_OWNER = "This thread was opened with a key that acted as the bot's owner, and the key no longer does. Start a new thread.";const ACTS_AS_OWNER_NEVER = "A key can't act as the owner here.";@@ -193,6 +194,8 @@ export function createBotApiHost(deps: BotApiHostDeps) {} catch (error) {markRunning(botId, threadId, false);if (opened) deps.discard?.(botId, threadId);+ const capped = z.object({ code: z.literal("spend_cap"), message: z.string(), resetsAt: z.number().optional() }).safeParse(error);+ if (capped.success) throw Object.assign(new Error(capped.data.resetsAt === undefined ? CAPPED : `${CAPPED} Try again after ${new Date(capped.data.resetsAt).toISOString()}.`), { status: 429, forCaller: true, detail: capped.data.message, retryAt: capped.data.resetsAt });const busy = z.object({ code: z.enum(["thread_busy", "thread_limit"]) }).safeParse(error).success;fail(busy ? 409 : 502, busy ? BUSY : COULD_NOT_ANSWER, error instanceof Error ? error.message : String(error));}@@ -289,6 +292,8 @@ export function createBotApiHost(deps: BotApiHostDeps) {json(res, answer.status, answer.body);} catch (error) {manager.record(botId, { outcome: "rejected", statusCode: statusOf(error), reason: detailOf(error), preview: call.message });+ const retryAt = z.object({ retryAt: z.number() }).safeParse(error).data?.retryAt;+ if (retryAt !== undefined) res.setHeader("retry-after", String(Math.max(1, Math.ceil((retryAt - Date.now()) / 1000))));json(res, statusOf(error), { error: callerWords(error) });}return true;diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex 52fdc96f39..e842f82d74 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -54,7 +54,8 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_TEAM_PRESENCE_GRACE_MS", "OMB_TEST_INTERNAL_CAPABILITY_KEY", "OMB_TEST_ORG_LIBRARY_KEY","OMB_TEST_PLAN_USAGE_FILE", "OMB_TEST_TAILNET_STAND_IN", "OMB_THREAD_CACHE_MB", "OMB_TOOL_STALL_MS", "OMB_TREG_KEY", "OMB_TREG_URL", "OMB_TTS_DEFAULT_VOICE","OMB_TTS_KEY", "OMB_TUNNEL_ORIGIN_PORT", "OMB_TUNNEL_SOCKET", "OMB_TURN_STALL_MS", "OMB_UNATTENDED_TURN_MAX_DENIALS", "OMB_UNATTENDED_TURN_MAX_MS", "OMB_UNATTENDED_TURN_MAX_REQUESTS", "OMB_UNDER_IMAGE_INIT", "OMB_UPDATE_CHANNEL", "OMB_UPDATE_INSTALL",- "OMB_USER_DATA", "OMB_WARM_SUMMARY", "OMB_WARM_SUMMARY_TIME_SCALE", "OMB_WEBHOOK_PORT", "OMB_WEBHOOK_PUBLIC_URL", "OMB_WEBHOOK_SOCKET",+ "OMB_USAGE_CAP_DAILY_TOKENS", "OMB_USAGE_CAP_DAILY_USD", "OMB_USAGE_CAP_MONTHLY_TOKENS", "OMB_USAGE_CAP_MONTHLY_USD",+ "OMB_USAGE_CAP_STOPS", "OMB_USER_DATA", "OMB_WARM_SUMMARY", "OMB_WARM_SUMMARY_TIME_SCALE", "OMB_WEBHOOK_PORT", "OMB_WEBHOOK_PUBLIC_URL", "OMB_WEBHOOK_SOCKET","OMB_WORKERS_AI_TOKEN", "OMB_XAI_TTS_API","OMB_BURST_PART_MAX_RESTARTS", "OMB_CHIEF_INCIDENT_TURNS_PER_HOUR", "OMB_ROUTINE_FAILURES_BEFORE_SPACING", "OMB_ROUTINE_FAILURE_SPACING_MAX_MS","OMB_ROUTINE_FAILURE_SPACING_MS", "OMB_ROUTINE_RESTART_STAGGER_MS", "OMB_STARTUP_ROUTINE_GAP_MS",diff --git a/server/config.ts b/server/config.tsindex d736d7aec6..3a67828464 100644--- a/server/config.ts+++ b/server/config.ts@@ -31,7 +31,7 @@ import { parseJson, schemaIssue, type JsonObject, type JsonValue } from "./schemimport { deciderConfigSchema, type DeciderConfig } from "./decider/config.ts";import { fishKeyFromLiveKey, liveConfigSchema, liveConfigWithEnv, liveSettingEnv, type LiveConfig } from "./live-config.ts";import { browserEngineConfigSchema, isValidCdpTarget, type BrowserEngineConfig } from "./browser/config.ts";-import { roomContextSettings } from "./room-context-settings.ts";+import { roomContextSettings } from "./room-context-settings.ts"; import { usageCapsSchema, type UsageCapsConfig } from "./usage-caps-config.ts";import { localVmConfigSchema } from "./local-vm-settings.ts";export * from "./local-vm-settings.ts";@@ -339,7 +339,7 @@ const appConfigSchema = z.object({monthlyUsd: z.number().min(0).max(1_000_000).optional(),warnAtPercent: z.number().int().min(1).max(100).optional(),})- .optional(),+ .optional(), /** Caps on a day's and a month's usage, for the server and for each bot; none by default (usage-caps.ts). */ usageCaps: usageCapsSchema.optional(),/** Operator sell prices per million tokens by model id, `driver/model` or `default`; read only with the `billing` entitlement. */billing: z.object({@@ -461,7 +461,7 @@ export interface AppConfig extends HelperConfig {anthropic?: { key?: string; url?: string; everyClaudeBot?: boolean };openai?: { key?: string };openrouter?: { key?: string };- budgets?: { monthlyUsd?: number; warnAtPercent?: number };+ budgets?: { monthlyUsd?: number; warnAtPercent?: number }; usageCaps?: UsageCapsConfig;decisions?: { retentionDays?: number };loopGuard?: LoopGuardConfig;safetyFloor?: { enabled?: boolean };@@ -925,7 +925,7 @@ export function saveConfig(if (checkedPatch.signIn !== undefined) disk.signIn = checkedPatch.signIn;// Replace the section so clearing a backup cannot revive the old selection.if (checkedPatch.automaticRecovery !== undefined) disk.automaticRecovery = checkedPatch.automaticRecovery;- if (checkedPatch.cacheKeepWarm !== undefined) disk.cacheKeepWarm = checkedPatch.cacheKeepWarm;+ if (checkedPatch.cacheKeepWarm !== undefined) disk.cacheKeepWarm = checkedPatch.cacheKeepWarm; if (checkedPatch.usageCaps !== undefined) disk.usageCaps = checkedPatch.usageCaps;if (checkedPatch.defaultModelSelection !== undefined) {disk.defaultModelSelection = checkedPatch.defaultModelSelection;if (disk.newBotDefaults) {diff --git a/server/coordinator.ts b/server/coordinator.tsindex 17c604ae3a..c0d4fc0175 100644--- a/server/coordinator.ts+++ b/server/coordinator.ts@@ -246,8 +246,8 @@ export interface Coordinator {/** A plan's limit on handing out work. */export interface HandoffLimit {/** Why handing work to this bot is refused now, in words for the model that asked; null when it may go. `open` counts the- * hand-offs not yet ended. */- refusal(botId: string, open: () => number): string | null;+ * hand-offs not yet ended; `origin` is whether the work traces to a person's own typed line. */+ refusal(botId: string, open: () => number, origin?: "user" | "outside"): string | null;}export interface CoordinatorOptions {diff --git a/server/host/usage-cap-gate.test.ts b/server/host/usage-cap-gate.test.tsnew file mode 100644index 0000000000..07991f2670--- /dev/null+++ b/server/host/usage-cap-gate.test.ts@@ -0,0 +1,146 @@+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { removeTempDir } from "../testing/cleanup.ts";+import { resetUsageTotalsForTests, type UsageCapsConfig } from "../usage-caps.ts";+import { appendUsage, flushUsageLedger } from "../usage-ledger.ts";+import { capResets, createUsageCapGate, marksOf } from "./usage-cap-gate.ts";++describe("the usage cap gate", () => {+ let dataDir: string;+ let now: Date;+ let caps: UsageCapsConfig | undefined;+ let notices: Array<{ about: string | undefined; title: string; body: string }>;+ let log: string[];+ const gate = (env: NodeJS.ProcessEnv = {}) => createUsageCapGate({+ dataDir, caps: () => caps, botName: (botId) => ({ a: "Ada", b: "Bo" } as Record<string, string>)[botId], now: () => now, env,+ notice: (about, title, body) => notices.push({ about, title, body }), log: (line) => log.push(line),+ });+ const spend = async (at: string, botId: string, costUsd: number, tokens = 1_000) => {+ appendUsage(dataDir, { at, botId, botName: botId, threadId: "t", instanceId: "claude", driverKind: "claudeAgent", model: "m", input: tokens, output: 0, costUsd, trigger: { kind: "owner" } });+ await flushUsageLedger(dataDir);+ resetUsageTotalsForTests();+ };+ beforeEach(() => {+ dataDir = mkdtempSync(join(tmpdir(), "omb-cap-gate-"));+ resetUsageTotalsForTests();+ now = new Date("2026-09-15T12:00:00Z");+ caps = undefined;+ notices = [];+ log = [];+ });+ afterEach(async () => { await removeTempDir(dataDir); });++ it("lets everything through and says nothing while no cap is set", async () => {+ await spend("2026-09-15T08:00:00.000Z", "a", 500);+ const open = gate();+ open.assertTurn("a", false);+ open.booked("a");+ expect([open.refusal("a", false), open.routineSkip("a", "r1"), open.runText("a", "webhook"), open.handoff("a", "outside")]).toEqual([null, null, null, null]);+ expect(open.view()).toEqual({ stops: "unattended", savedStops: "unattended", server: {}, bots: {}, env: { stops: false, server: [], values: { server: {} } }, caps: [] });+ expect([notices, log]).toEqual([[], []]);+ });++ it("says one line in the log at 80%, and one notice when the cap is reached, however often it is asked", async () => {+ caps = { server: { dailyUsd: 10 } };+ const open = gate();+ await spend("2026-09-15T08:00:00.000Z", "a", 7.9);+ open.booked("a");+ expect([notices, log]).toEqual([[], []]);+ await spend("2026-09-15T09:00:00.000Z", "a", 0.2);+ open.booked("a");+ open.booked("a");+ expect(log).toEqual(["usage cap at 81%: server:day:usd $8.10 of $10.00"]);+ expect(notices).toEqual([]);+ expect(open.refusal("a", false)).toBeNull();++ await spend("2026-09-15T10:00:00.000Z", "b", 2);+ open.booked("b");+ for (let i = 0; i < 5; i += 1) expect(open.refusal("a", false)).toContain("the daily usage cap for all bots ($10.00) is reached");+ open.booked("a");+ const resets = capResets(Date.parse("2026-09-16T00:00:00Z"));+ expect(notices).toEqual([{ about: "b", title: "Usage cap reached",+ body: `Unattended work is skipped until ${resets}: the daily usage cap for all bots ($10.00) is reached. Your own messages still run.` }]);+ expect(log).toHaveLength(2);+ expect(log[1]).toBe("usage cap reached: server:day:usd $10.10 of $10.00; unattended work waits until 2026-09-16T00:00:00.000Z");++ // A restart does not repeat the notice; the next day's cap is a new one.+ expect(JSON.parse(readFileSync(join(dataDir, "usage", "cap-notices.json"), "utf8"))).toEqual({ "server:day:usd": { period: "2026-09-15", limit: 10, warn: true, reached: true } });+ const restarted = gate();+ restarted.booked("a");+ expect(restarted.refusal("a", false)).not.toBeNull();+ expect(notices).toHaveLength(1);+ now = new Date("2026-09-16T00:00:01Z");+ resetUsageTotalsForTests();+ expect(restarted.refusal("a", false)).toBeNull();+ await spend("2026-09-16T00:00:02.000Z", "a", 11);+ now = new Date("2026-09-16T00:00:03Z");+ restarted.booked("a");+ expect(notices).toHaveLength(2);+ });++ it("refuses unattended work with a 409 that names the cap and its reset, and lets a person's own message run", async () => {+ caps = { bots: { a: { monthlyTokens: 5_000 } } };+ await spend("2026-09-10T08:00:00.000Z", "a", 0, 6_000);+ const open = gate();+ open.assertTurn("a", true);+ open.assertTurn("b", false);+ let refused: unknown;+ try { open.assertTurn("a", false); } catch (error) { refused = error; }+ expect(refused).toMatchObject({ status: 409, code: "spend_cap", resetsAt: Date.parse("2026-10-01T00:00:00Z"),+ message: `Not started: Ada’s monthly usage cap (5,000 tokens) is reached. New work starts again by itself after ${capResets(Date.parse("2026-10-01T00:00:00Z"))}, or sooner if the owner raises the cap in Settings → Usage.` });+ expect(notices).toHaveLength(1);+ expect(notices[0]).toMatchObject({ about: "a" });++ caps = { stops: "everything", bots: { a: { monthlyTokens: 5_000 } } };+ expect(() => open.assertTurn("a", true)).toThrow(/Ada’s monthly usage cap/);+ caps = { bots: { a: { monthlyTokens: 50_000 } } };+ open.assertTurn("a", false);+ });++ it("gives a routine one counted row a period, a queued run its line, and a bot handing work on what to say", async () => {+ caps = { server: { dailyTokens: 1_000 } };+ await spend("2026-09-15T08:00:00.000Z", "a", 0, 1_000);+ const open = gate();+ const skip = open.routineSkip("a", "r1")!;+ const resets = capResets(Date.parse("2026-09-16T00:00:00Z"));+ // Each routine under the cap keeps its own row: the routine's id is part of the row's cause.+ expect([skip.behind, skip.resetsAt]).toEqual(["cap:r1:server:day:tokens:2026-09-15", Date.parse("2026-09-16T00:00:00Z")]);+ expect(open.routineSkip("b", "r2")!.behind).toBe("cap:r2:server:day:tokens:2026-09-15");+ expect(skip.words(1)).toEqual({ text: `Skipped: the daily usage cap for all bots (1,000 tokens) is reached. Runs start again after ${resets}`,+ codes: { errorCode: "routines.server.capSkippedOne", errorParams: { why: "routines.server.part.capServerDay", amount: "1,000 tokens", resets } } });+ expect(skip.words(3).text).toBe(`Skipped 3 runs: the daily usage cap for all bots (1,000 tokens) is reached. Runs start again after ${resets}`);+ expect(open.runText("a", "webhook")).toContain("Not started: the daily usage cap for all bots (1,000 tokens) is reached.");+ expect(open.runText("a", "manual")).toBeNull();+ expect(open.handoff("b", "user")).toBeNull();+ expect(open.handoff("b", "outside")).toBe(`Nothing was handed to @Bo: the daily usage cap for all bots (1,000 tokens) is reached, and nobody is waiting on this work. Work like this starts again by itself after ${resets}. `+ + "Say that in one line and stop. Do not retry, and do not hand this to another bot to work around the cap.");+ expect(notices).toHaveLength(1);+ });++ it("shows the owner each cap with its use, and which values the environment holds", async () => {+ caps = { stops: "unattended", server: { dailyUsd: 4 }, bots: { a: { dailyUsd: 1 } } };+ await spend("2026-09-15T08:00:00.000Z", "a", 0.5);+ const view = gate({ OMB_USAGE_CAP_DAILY_USD: "2", OMB_USAGE_CAP_STOPS: "everything" }).view();+ expect(view).toMatchObject({ stops: "everything", savedStops: "unattended", server: { dailyUsd: 4 }, bots: { a: { dailyUsd: 1 } },+ env: { stops: true, server: ["dailyUsd"], values: { stops: "everything", server: { dailyUsd: 2 } } } });+ expect(view.caps.map((cap) => [cap.id, cap.limit, cap.used, cap.percent])).toEqual([["server:day:usd", 2, 0.5, 25], ["bot:a:day:usd", 1, 0.5, 50]]);+ });++ it("reads a notices file out of shape as far as it is good, and never throws at the start of a turn", async () => {+ expect(marksOf({ ok: { period: "2026-09-15", limit: 10, warn: true }, noPeriod: { limit: 1 }, badPeriod: { period: 7, limit: 1 }, oddPeriod: { period: "soon", limit: 1 },+ noLimit: { period: "2026-09" }, nothing: null, text: "x", list: [1] })).toEqual({ ok: { period: "2026-09-15", limit: 10, warn: true } });+ for (const value of [null, [], "x", 3]) expect(marksOf(value)).toEqual({});+ caps = { server: { dailyTokens: 1_000 } };+ await spend("2026-09-15T08:00:00.000Z", "a", 0, 1_000);+ mkdirSync(join(dataDir, "usage"), { recursive: true });+ writeFileSync(join(dataDir, "usage", "cap-notices.json"), JSON.stringify({ "server:day:tokens": { period: null }, other: 5 }));+ const open = gate();+ expect(() => open.assertTurn("a", false)).toThrow(/is reached/);+ open.booked("a");+ expect(notices).toHaveLength(1);+ expect(JSON.parse(readFileSync(join(dataDir, "usage", "cap-notices.json"), "utf8"))).toEqual({ "server:day:tokens": { period: "2026-09-15", limit: 1_000, warn: true, reached: true } });+ });+});diff --git a/server/host/usage-cap-gate.ts b/server/host/usage-cap-gate.tsnew file mode 100644index 0000000000..5128db2a7c--- /dev/null+++ b/server/host/usage-cap-gate.ts@@ -0,0 +1,189 @@+// Where the server asks the cap engine (usage-caps.ts) before work starts, and the one line each refusal leaves: a turn's+// refusal, a routine's counted skipped row, what a bot handing work on is told, and one notice per cap per period.+// <data>/usage/cap-notices.json remembers which caps were announced for which period, so a restart does not repeat one.+import { mkdirSync, readFileSync } from "node:fs";+import { join } from "node:path";++import { writeFileAtomic } from "../atomic.ts";+import { codedLine, type RoutineLine, type RoutineLineKey } from "../routine-lines.ts";+import { serverLine, type ServerLineKey } from "../server-lines.ts";+import { hostTimeZone } from "../turn-clock.ts";+import { CAP_FIELDS, capsFromEnv, capStates, effectiveCaps, reachedCap, type CapLimits, type CapState, type CapStops, type UsageCapsConfig } from "../usage-caps.ts";++export const USAGE_CAP_CODE = "spend_cap";++export interface UsageCapView {+ /** What a reached cap stops now: the environment's choice when it makes one, else the saved one. */+ stops: CapStops;+ /** What `config.json` holds, which a save keeps when the environment makes the choice. */+ savedStops: CapStops;+ /** The saved caps, as `config.json` holds them. */+ server: CapLimits;+ bots: Record<string, CapLimits>;+ /** Fields the environment sets: they win over the saved ones and cannot be changed here. `values` is what it sets. */+ env: { stops: boolean; server: Array<keyof CapLimits>; values: { stops?: CapStops; server: CapLimits } };+ /** Every cap in force with its use now. */+ caps: CapState[];+}++export interface UsageCapGate {+ /** Throws the refusal (409, `spend_cap`) of a turn a reached cap keeps from starting. */+ assertTurn(botId: string | undefined, personWaiting: boolean, language?: string): void;+ /** The same refusal as words, or null when the work may start. */+ refusal(botId: string | undefined, personWaiting: boolean, language?: string): string | null;+ /** A scheduled occurrence that will not run: the cause its counted `missed` row is kept under, and that row's line. */+ routineSkip(botId: string, routineId: string): { behind: string; resetsAt: number; words(count: number): RoutineLine } | null;+ /** A run already queued (a webhook's, an app event's) that will not start; a run started by hand counts as a person's. */+ runText(botId: string, trigger: string | undefined, language?: string): string | null;+ /** What a bot handing work to `botId` is told when nobody is waiting on it; null when the hand-off may go. */+ handoff(botId: string, origin: "user" | "outside" | undefined): string | null;+ /** After a turn's usage is booked: the 80% line and the reached notice, once each per cap per period. */+ booked(botId: string): void;+ view(): UsageCapView;+}++type Marks = Record<string, { period: string; limit: number; warn?: true; reached?: true }>;++/** The notice marks as the file holds them: an entry out of shape is dropped, so a bad file never stops a turn. */+export function marksOf(value: unknown): Marks {+ const marks: Marks = {};+ if (!value || typeof value !== "object" || Array.isArray(value)) return marks;+ for (const [id, raw] of Object.entries(value)) {+ const mark = raw as Partial<Marks[string]> | null;+ if (id === "__proto__" || !mark || typeof mark !== "object" || typeof mark.period !== "string" || !/^\d{4}-\d{2}(-\d{2})?$/.test(mark.period) ||+ typeof mark.limit !== "number" || !Number.isFinite(mark.limit)) continue;+ marks[id] = { period: mark.period, limit: mark.limit, ...(mark.warn === true ? { warn: true } : {}), ...(mark.reached === true ? { reached: true } : {}) };+ }+ return marks;+}++const NAME: Record<`${CapState["scope"]}:${CapState["period"]}`, { line: ServerLineKey; part: RoutineLineKey }> = {+ "server:day": { line: "server.usageCap.name.serverDay", part: "routines.server.part.capServerDay" },+ "server:month": { line: "server.usageCap.name.serverMonth", part: "routines.server.part.capServerMonth" },+ "bot:day": { line: "server.usageCap.name.botDay", part: "routines.server.part.capBotDay" },+ "bot:month": { line: "server.usageCap.name.botMonth", part: "routines.server.part.capBotMonth" },+};++export const capAmount = (unit: CapState["unit"], value: number): string =>+ unit === "usd" ? `$${value.toFixed(2)}` : `${Math.round(value).toLocaleString("en-US")} tokens`;++/** Host-local with its zone: the period itself rolls over at midnight UTC. */+export function capResets(at: number, timeZone = hostTimeZone()): string {+ return `${new Date(at).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit", timeZone })} (${timeZone})`;+}++export function createUsageCapGate(deps: {+ dataDir: string;+ caps(): UsageCapsConfig | undefined;+ botName(botId: string): string | undefined;+ /** One notice to the owner, in the notifications list: never a card. `aboutBotId` is the bot whose work met the cap. */+ notice(aboutBotId: string | undefined, title: string, body: string): void;+ log(line: string): void;+ /** The language the owner's notice is written in. */+ language?(): string | undefined;+ now?(): Date;+ env?: NodeJS.ProcessEnv;+}): UsageCapGate {+ const env = deps.env ?? process.env;+ const now = () => deps.now?.() ?? new Date();+ const file = join(deps.dataDir, "usage", "cap-notices.json");+ let marks: Marks | undefined;++ const load = (): Marks => {+ if (marks) return marks;+ try {+ marks = marksOf(JSON.parse(readFileSync(file, "utf8")));+ } catch {+ marks = {};+ }+ return marks;+ };+ const save = () => {+ try {+ mkdirSync(join(deps.dataDir, "usage"), { recursive: true, mode: 0o700 });+ writeFileAtomic(file, JSON.stringify(marks), { mode: 0o600 });+ } catch {+ // The marks stay in memory: a notice is repeated after a restart rather than lost.+ }+ };++ const nameOf = (state: CapState, language?: string) =>+ serverLine(language, NAME[`${state.scope}:${state.period}`].line, { bot: deps.botName(state.botId ?? "") ?? "" });+ const refusedWords = (state: CapState, language?: string) => serverLine(language, "server.usageCap.refused",+ { cap: nameOf(state, language), limit: capAmount(state.unit, state.limit), resets: capResets(state.resetsAt) });++ /** Marks the cap's 80% line or reached notice as said for this period; true the first time. */+ const first = (state: CapState, what: "warn" | "reached"): boolean => {+ const all = load();+ const saved = all[state.id];+ const mark = saved && saved.period === state.periodKey && saved.limit === state.limit ? saved : { period: state.periodKey, limit: state.limit };+ if (mark[what] || (what === "warn" && mark.reached)) return false;+ all[state.id] = { ...mark, warn: true, ...(what === "reached" ? { reached: true as const } : {}) };+ for (const [id, old] of Object.entries(all)) if (old.period.length === state.periodKey.length && old.period < state.periodKey) delete all[id];+ save();+ return true;+ };++ const announce = (state: CapState, aboutBotId: string | undefined) => {+ const stops = effectiveCaps(deps.caps(), env).stops;+ if (state.reached) {+ if (!first(state, "reached")) return;+ const language = deps.language?.();+ const params = { cap: nameOf(state, language), limit: capAmount(state.unit, state.limit), resets: capResets(state.resetsAt) };+ deps.log(`usage cap reached: ${state.id} ${capAmount(state.unit, state.used)} of ${capAmount(state.unit, state.limit)}; ${stops === "everything" ? "all new work" : "unattended work"} waits until ${new Date(state.resetsAt).toISOString()}`);+ deps.notice(state.botId ?? aboutBotId, serverLine(language, "server.usageCap.noticeTitle"),+ serverLine(language, stops === "everything" ? "server.usageCap.noticeEverything" : "server.usageCap.noticeUnattended", params));+ } else if (state.warn && first(state, "warn")) {+ deps.log(`usage cap at ${state.percent}%: ${state.id} ${capAmount(state.unit, state.used)} of ${capAmount(state.unit, state.limit)}`);+ }+ };++ const blocking = (botId: string | undefined, personWaiting: boolean): CapState | null => {+ const state = reachedCap(deps.caps(), deps.dataDir, { ...(botId ? { botId } : {}), personWaiting }, now(), env);+ if (state) announce(state, botId);+ return state;+ };++ return {+ refusal(botId, personWaiting, language) {+ const state = blocking(botId, personWaiting);+ return state ? refusedWords(state, language) : null;+ },+ assertTurn(botId, personWaiting, language) {+ const state = blocking(botId, personWaiting);+ if (state) throw Object.assign(new Error(refusedWords(state, language)), { status: 409, code: USAGE_CAP_CODE, resetsAt: state.resetsAt });+ },+ routineSkip(botId, routineId) {+ const state = blocking(botId, false);+ if (!state) return null;+ const params = { why: NAME[`${state.scope}:${state.period}`].part, amount: capAmount(state.unit, state.limit), resets: capResets(state.resetsAt) };+ // One row per routine, cap and period: two routines under one cap never share (or misfile) a row.+ return {+ behind: `cap:${routineId}:${state.id}:${state.periodKey}`.replace(/[^\w:-]/g, "-").slice(0, 160), resetsAt: state.resetsAt,+ words: (count) => count === 1 ? codedLine("error", "routines.server.capSkippedOne", params) : codedLine("error", "routines.server.capSkippedMany", { count, ...params }),+ };+ },+ runText(botId, trigger, language) {+ return this.refusal(botId, trigger === "manual", language);+ },+ handoff(botId, origin) {+ const state = blocking(botId, origin === "user");+ if (!state) return null;+ const name = deps.botName(botId) ?? "that bot";+ return `Nothing was handed to @${name}: ${nameOf(state)} (${capAmount(state.unit, state.limit)}) is reached, and nobody is waiting on this work. `+ + `Work like this starts again by itself after ${capResets(state.resetsAt)}. Say that in one line and stop. Do not retry, and do not hand this to another bot to work around the cap.`;+ },+ booked(botId) {+ for (const state of capStates(deps.caps(), deps.dataDir, now(), env, botId)) announce(state, botId);+ },+ view() {+ const saved = deps.caps();+ const fromEnv = capsFromEnv(env);+ return {+ stops: effectiveCaps(saved, env).stops, savedStops: saved?.stops ?? "unattended", server: saved?.server ?? {}, bots: saved?.bots ?? {},+ env: { stops: fromEnv.stops !== undefined, server: CAP_FIELDS.map(({ field }) => field).filter((field) => fromEnv.server[field] !== undefined), values: fromEnv },+ caps: capStates(saved, deps.dataDir, now(), env),+ };+ },+ };+}diff --git a/server/index.ts b/server/index.tsindex ceb303ea61..1d10d7eb2c 100644--- a/server/index.ts+++ b/server/index.ts@@ -195,7 +195,7 @@ import type { PriceList } from "./prices.ts";import type { RequestAuth } from "./request-auth.ts";import { adminAuditPlan, type AuditPlan } from "./admin-audit-plan.ts"; import { departmentGrants, type DepartmentGrant } from "./department-grants.ts";import { onKeyRejectionChange } from "./key-rejections.ts";-import { assertWithinBudget, noteSpend, spendAlertText, spendState, takeSpendAlert } from "./spend.ts";+import { assertWithinBudget, noteSpend, spendAlertText, spendState, takeSpendAlert } from "./spend.ts"; import { personWaiting, personWaitingInRoom, type ThreadStanding } from "./usage-caps.ts"; import { createUsageCapGate, USAGE_CAP_CODE } from "./host/usage-cap-gate.ts"; import { createUsageCapRoutes } from "./routes/usage-caps.ts";import { fleetAvailable, fleetSocketPath } from "./fleet-client.ts";import { HOSTED_CONTRACT_HEADER, HOSTED_CONTRACT_METADATA, HOSTED_CONTRACT_VERSION } from "./hosted-contract.ts";import { cliProbeEnvironment, testCliBinary } from "./cli-probe.ts";@@ -1356,7 +1356,7 @@ function operatorPrices(): PriceList | null {return entitled("billing") && cfg.billing?.prices && Object.keys(cfg.billing.prices).length ? cfg.billing.prices : null;}-const attributeUsage = createUsageAttribution({ section: (botId) => store.bot(botId)?.section, threadTrigger: (threadId) => turnTriggers.get(threadId), routineWriter: (id) => { const key = cloudRoutineAuthors?.writer(id); return key ? teamOwners.people?.list().find((one) => personKey({ id: "", email: one.email }) === key)?.email : undefined; } }); function bookTurnUsage(row: Omit<UsageRow, "at" | "costSource">, tokensReported = true, notificationThreadId = row.threadId): void {+const attributeUsage = createUsageAttribution({ section: (botId) => store.bot(botId)?.section, threadTrigger: (threadId) => turnTriggers.get(threadId), routineWriter: (id) => { const key = cloudRoutineAuthors?.writer(id); return key ? teamOwners.people?.list().find((one) => personKey({ id: "", email: one.email }) === key)?.email : undefined; } }); const usageCapGate = createUsageCapGate({ dataDir: DATA_DIR, caps: () => cfg.usageCaps, botName: (botId) => store.bot(botId)?.name, language: () => appLanguage(), log: (line) => console.log(line), notice: (aboutBotId, title, body) => { const bot = store.bot(aboutBotId ?? "") ?? store.bots[0]; if (bot) broadcast({ kind: "notify", notification: logNotification(buildSpendNotification({ id: bot.id, name: bot.name }, bot.threadId, { title, body })) }, { adminOnly: true }); } }); const threadStanding = (botId: string, threadId: string): ThreadStanding => { const owner = directRequestOwners.get(threadId); return { unattended: isUnattended(botId, threadId), automation: owner?.automation, origin: owner?.origin?.kind }; }; const routineTriggerOf = (threadId: string) => { const run = activeRoutineRunForThread(threadId); return run ? run.triggerSource ?? (run.manual ? "manual" : "schedule") : undefined; }; function bookTurnUsage(row: Omit<UsageRow, "at" | "costSource">, tokensReported = true, notificationThreadId = row.threadId): void {const cost = tokensReported || row.costUsd !== null ? ledgerCost(row, operatorPrices()) : { costUsd: null };const booked = attributeUsage({ ...row, ...cost, ...usageTrace.settle(row.threadId), at: new Date().toISOString() });// The append is async; noteSpend counts the row from memory until it lands, so the cap check sees it.@@ -1365,7 +1365,7 @@ const attributeUsage = createUsageAttribution({ section: (botId) => store.bot(boconst alert = takeSpendAlert(DATA_DIR, state);if (alert && state) {broadcast({ kind: "notify", notification: logNotification(buildSpendNotification({ id: row.botId, name: row.botName }, notificationThreadId, spendAlertText(alert, state))) }, { adminOnly: true });- }+ } usageCapGate.booked(row.botId);}const providerAuthSessions = new ProviderAuthSessions({ signedIn: (instanceId) => limitTakeover.signedIn(instanceId) }); const mcpServersHost = createMcpServersHost({ dataDir: DATA_DIR, cfg: () => cfg, moveGrants: (bot, move) => moveSavedGrants(store, bot, move), persist: persistMcpServers, bots: () => store.bots, policy: (servers) => managedPolicy.filterMcp(servers), tell: (text, about) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), startsServers: (botId) => { const bot = store.bot(botId); return Boolean(bot && registry.get(bot.modelSelection.instanceId)?.adapter.capabilities.customMcp === true); }, boxed: () => botBox.enabled(), keys: mcpKeys, forgetSignIn: (name) => mcpOAuth.forget(name) });@@ -2812,8 +2812,8 @@ const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusalForBot,ownerPerson: cloudProvenOwnerPerson, cardAnswerer: cloudCardAnswerer, activeRoutineRun: activeRoutineRunForThread, ownerStartedRun: (runId) => ownerStartedRoutineRuns.has(runId),routineRunIsOwners: cloudRoutineRunIsOwners, routines: () => routines, routineAuthors: cloudRoutineAuthors, lentPlatform: () => sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform,memoryChangedBySomeoneElse: (botId) => lendingMemory?.reconcile(botId, foreignTurnRunning(botId), { cached: true }).changedBySomeoneElse === true, lifts: () => lendingLifts, handedSince: (threadId, since) => handedInSince(coordinator.inThread(threadId, { since }), threadId, since) });-const teamAway = createTeamAwayHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, here: (person) => [...sseClients].some((client) => client.ask.person === person), people: () => teamOwners.people?.everyone() ?? [], language: personLanguages.forLine, audienceOf: teamHost.audienceOf, store, unseen: (person) => teamMessages.inbox.unseen(person), readUpTo: (key, person) => personRooms.reads?.readUpTo(key, person), session: (auth) => (auth.kind === "session" ? auth.session : null) }); const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) }); const lendingLifts = lendingMemory ? createLendingLifts({ store, stopped: (threadId) => directRequestOwners.get(threadId)?.stopped === true, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn, notify, language: (threadId) => threadLanguage(threadId), device: () => deviceWord(sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform), decide: (row) => appendDecision(DATA_DIR, row), words: changedWords, ownersAnswer: (card) => cloudProvenOwnerPerson(cloudCardAnswerer(card)), memory: { info: (botId) => lendingMemory.reviewInfo(botId), accept: (botId, token) => lendingMemory.review(botId, foreignTurnRunning(botId), token).ok } }) : null;-const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, lending: sharedComputers, principal: CLOUD_HOME_LENDER, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn,+const teamAway = createTeamAwayHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, here: (person) => [...sseClients].some((client) => client.ask.person === person), people: () => teamOwners.people?.everyone() ?? [], language: personLanguages.forLine, audienceOf: teamHost.audienceOf, store, unseen: (person) => teamMessages.inbox.unseen(person), readUpTo: (key, person) => personRooms.reads?.readUpTo(key, person), session: (auth) => (auth.kind === "session" ? auth.session : null) }); const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) }); const lendingLifts = lendingMemory ? createLendingLifts({ store, stopped: (threadId) => directRequestOwners.get(threadId)?.stopped === true, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: (botId, text, opts) => startTurn(botId, text, { ...opts, continuesRun: true }), notify, language: (threadId) => threadLanguage(threadId), device: () => deviceWord(sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform), decide: (row) => appendDecision(DATA_DIR, row), words: changedWords, ownersAnswer: (card) => cloudProvenOwnerPerson(cloudCardAnswerer(card)), memory: { info: (botId) => lendingMemory.reviewInfo(botId), accept: (botId, token) => lendingMemory.review(botId, foreignTurnRunning(botId), token).ok } }) : null;+const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, lending: sharedComputers, principal: CLOUD_HOME_LENDER, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: (botId, text, opts) => startTurn(botId, text, { ...opts, continuesRun: true }),refusal: (turn) => sharedComputerPrincipal(turn) ? null : cloudLendingRefusalForBot(turn) ?? "This conversation can't use your computer.", request: (threadId) => directRequestOwners.get(threadId), active: (turn) => internalCapabilityIsActive(turn as InternalCapability) }) : null;const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersonStop({store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, stopping: (botId, threadId) => idleThreads.stopping(botId, threadId), clearUnattended,@@ -3523,7 +3523,7 @@ type GroupTurnOperation = {queuedQueueIds?: string[];line?: RoomRoundLine;/** The person's room line this run answers (its member turns, mentions included, act for whoever wrote it), or the handed-on work it does. */- requestMessageId?: string; handedFor?: HandedRun;+ requestMessageId?: string; handedFor?: HandedRun; /** Whether a person's own line started this run, or the work handed on to it traces to one (usage-caps.ts). */ personStarted?: boolean; /** A coordinated run that already started carries on: no usage cap refuses it. */ continuesRun?: boolean;goalRun?: LiveGoalRun; /** What the person pointed at in a member's page; taken once by the page's bot (takeRoomPick). */ pick?: RoomPick;};@@ -3798,9 +3798,9 @@ function noteQueuedBehindPerson(node: HandoffView): void {}function runRoomNode(node: HandoffView, group: GroupRecord, bot: BotRecord, signal: AbortSignal, parent: HandoffView | undefined,- turn: (operation: GroupTurnOperation, result: GroupTurnOrchestration["result"], coordination: NonNullable<GroupTurnOrchestration["coordination"]>) => Promise<unknown>,+ turn: (operation: GroupTurnOperation, result: GroupTurnOrchestration["result"], coordination: NonNullable<GroupTurnOrchestration["coordination"]>) => Promise<unknown>, continuesRun = false,): Promise<HostTurnResult> {- const operation = Object.assign(beginGroupTurnOperation(group.id, node.threadId, [bot.id]), { handedFor: actingPeople.handedRun(node.id), speaking: false });+ const operation = Object.assign(beginGroupTurnOperation(group.id, node.threadId, [bot.id]), { handedFor: actingPeople.handedRun(node.id), speaking: false, personStarted: node.origin?.kind === "user", continuesRun });return new Promise<HostTurnResult>(resolve => {let done = false;const finish = (outcome: HostTurnResult) => {@@ -3842,7 +3842,7 @@ function runRoomRootTurn(node: HandoffView, group: GroupRecord, bot: BotRecord,return runRoomNode(node, group, bot, signal, undefined, (operation, result, coordination) =>runGroupMemberTurn(group.id, node.threadId, bot.id, 0, new Set(), composed.text, error => { result.stopReason = error; }, () => operation.cancelled,() => groupProviderHandshakeStarted(operation), () => groupProviderHandshakeSettled(operation), undefined,- { roomHandoffId: node.id, systemInstructions: "", followMentions: true, result, coordination, ...(node.goalRunId ? { goalRunId: node.goalRunId } : {}) }, operation));+ { roomHandoffId: node.id, systemInstructions: "", followMentions: true, result, coordination, ...(node.goalRunId ? { goalRunId: node.goalRunId } : {}) }, operation), composed.turn !== "first");}function runRootTurn(node: HandoffView, bot: BotRecord, signal: AbortSignal, composed: ComposedTurn): Promise<HostTurnResult> {@@ -3866,7 +3866,7 @@ function runRootTurn(node: HandoffView, bot: BotRecord, signal: AbortSignal, comsignal.addEventListener("abort", abort, { once: true });if (signal.aborted) { abort(); return; }void startTurn(bot.id, composed.text, {- threadId: node.threadId, cardContinuation: true,+ threadId: node.threadId, cardContinuation: true, continuesRun: composed.turn !== "first",...(ownRequest?.messageId ? { requestMessageId: ownRequest.messageId } : {}),...(ownRequest ? {} : { origin: actingPeople.handedOrigin(node.origin ?? OUTSIDE, node.id) }),unattended: isUnattended(bot.id, node.threadId),@@ -3902,7 +3902,7 @@ const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATTworksInOwnFolder: (botId, threadId) => turnsRunInOwnFolder(botId, threadId, store.taskByThread(botId, threadId)?.cwd, store.bot(botId)?.cwd, Boolean(store.groupByThread(threadId))), vmHome: (botId) => localVmMode(cfg) === "per-bot" ? perBotLocalVmTarget(botId).workspaceDir : null, withheld: (child, parent) => Boolean(roomHandoffProblem(child, parent)) || keptPrivate({ child: teamHost.privateTo(child.threadId), parent: teamHost.privateTo(parent.threadId) }) });const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: beginGroupTurnOperation, finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), refusal: botMoveRefusal, language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({dataDir: DATA_DIR,- now: Date.now, wrote: handoffTicks.kick, handoffLimit: { refusal: (botId, open) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) },+ now: Date.now, wrote: handoffTicks.kick, handoffLimit: { refusal: (botId, open, origin) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) ?? usageCapGate.handoff(botId, origin) },log: line => console.error("coordinator:", line),legacyThreads: {standingThreadOf: botId => botMainThread(botId) ?? store.bot(botId)?.threadId,@@ -4051,7 +4051,7 @@ const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLif (signal.aborted) { abort(); return; }const swapped = parent && ownThreads.own(parent, node) ? ownThreads.swapRefusal(bot, node.threadId) : null; if (swapped) { finish({ ok: false, text: swapped }); return; }void startTurn(bot.id, turnText, {- threadId: node.threadId, cardContinuation: true, commsDepth: MAX_COMMS_DEPTH,+ threadId: node.threadId, cardContinuation: true, commsDepth: MAX_COMMS_DEPTH, continuesRun: composed.turn !== "first",requestMessageId: directRequestOwners.get(node.threadId)?.generations.has(node.rootId)? directRequestOwners.get(node.threadId)?.messageId : undefined,origin: actingPeople.handedOrigin(coordinator.node(node.rootId)?.origin ?? OUTSIDE, node.id),@@ -4064,7 +4064,7 @@ const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLrunGroupMemberTurn(group.id, node.threadId, bot.id, MAX_COMMS_DEPTH, new Set(),undefined, error => { result.stopReason = error; }, () => operation.cancelled,() => groupProviderHandshakeStarted(operation), () => groupProviderHandshakeSettled(operation),- { claimed: true }, { roomHandoffId: node.id, resumed, systemInstructions, turnInstructions: brief, turnNote: composed.note, turnRestartNote: composed.restartNote, liveRoster, followMentions: false, result, coordination }, operation));+ { claimed: true }, { roomHandoffId: node.id, resumed, systemInstructions, turnInstructions: brief, turnNote: composed.note, turnRestartNote: composed.restartNote, liveRoster, followMentions: false, result, coordination }, operation), composed.turn !== "first");}),names: (node, parent) => {const scope = parent ?? node;@@ -5116,7 +5116,7 @@ const sideJobs = createSideJobs({refusal: (instance) => policyModelRefusal(instance), smallModels: quickFallback,helper: cacheUntilConfigChanges((config) => helperSelection(config)),...(hostedModels ? { modelAllowed: (selection: ModelSelection) => hostedModels.allows(selection) } : {}),- assertWithinBudget: () => assertWithinBudget(cfg, DATA_DIR),+ assertWithinBudget: () => { assertWithinBudget(cfg, DATA_DIR); usageCapGate.assertTurn(undefined, true); },book: bookTurnUsage,log: (line) => console.log(line),});@@ -5225,7 +5225,7 @@ const cacheKeepWarm = createCacheKeepWarm({return null;},busy: ({ threadId, botId }) => threadBusy(botId, threadId) || botHasActiveTurn(botId) || Boolean(store.groupByThread(threadId)?.busyBotId),- overBudget: () => spendState(cfg, DATA_DIR)?.exceeded === true,+ overBudget: () => spendState(cfg, DATA_DIR)?.exceeded === true || usageCapGate.refusal(undefined, false) !== null,ping: async ({ threadId, instanceId }, signal) => {const warm = registry.get(instanceId)?.adapter.cacheKeepWarm;return warm ? warm.ping(threadId, { signal }) : { ok: false, reason: "this engine cannot keep its cache warm" };@@ -7201,7 +7201,7 @@ class DirectSendRefused extends Error {function directSendRefusal(botId: string, threadId: string): DirectSendRefused | null { const standIn = store.standIns.get(botId); if (standIn) return new DirectSendRefused(409, { error: botMoveRefusal(standIn)!, code: "moved" });try {- assertWithinBudget(cfg, DATA_DIR);+ assertWithinBudget(cfg, DATA_DIR); usageCapGate.assertTurn(botId, true, threadLanguage(threadId));} catch (error) {return new DirectSendRefused(409, { error: error instanceof Error ? error.message : String(error), code: "spend_cap" });}@@ -7550,6 +7550,7 @@ async function beginTurn(/** A one-on-one goal step: a card continuation that is still its own turn, as a room goal step is. */goalRunId?: string;coordination?: { id: string; resumed: boolean; settle: (outcome: HostTurnResult) => void };+ /** Carries on a run already started (a hand-off's result, an answered card, a restart): usage caps never refuse it (usage-caps.ts). */ continuesRun?: boolean;/** A person's own send: it may run beside a room turn on another thread. */ allowRoomTurnElsewhere?: boolean;},) {@@ -7585,7 +7586,7 @@ async function beginTurn(if (providerInstancesChanging.has(bot.modelSelection.instanceId)) {throw Object.assign(new Error("this provider account is being updated — try again shortly"), { status: 409, code: "settling" });}- assertWithinBudget(cfg, DATA_DIR);+ assertWithinBudget(cfg, DATA_DIR); if (!opts?.continuesRun) usageCapGate.assertTurn(botId, personWaiting({ ...opts, peerAsk: opts?.peerAsk ?? opts?.userMessage?.peerAsk }, threadStanding(botId, threadId)) || activeRoutineRunForThread(threadId)?.byPerson === true, threadLanguage(threadId));if (boatLifecycleBusyBots.has(botId)) {const changing = "this bot's cloud computer is being changed — wait for it to finish";if (!answer.incident) throw Object.assign(new Error(changing), { status: 409, code: "settling" });@@ -8784,7 +8785,7 @@ routines = new RoutineManager({skipStartupRuns: (startedFromSleep = Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR)), prepareRun: (run, signal) => runComputers.prepare(run, signal), preparing: RUN_COMPUTER_LINES.waking, // a Cloud home waking from a sleep it was stopped forhasPendingDelegations: runtimeWorkPending, refusedHandoff: refusedHandoffs.take, handedOffWorkLive: (threadId) => coordinator.outstandingFor(threadId).length > 0,routineTurn: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined, personTurn: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "user", home: { machine: CLOUD_HOME?.machineId, cloud: CLOUD_HOME !== null }, turnLive: (run) => runTurnLive(run, (threadId) => ({ busy: threadBusy(run.botId, threadId), settling: settlingTurns.has(threadId), queued: queuedThreadPosition(run.botId, threadId) !== null, pending: runtimeWorkPending(threadId), parked: store.taskByThread(run.botId, threadId)?.activity === "parked.computer" })),- botState: unattendedDispatchState, pausedText: (botId) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? starterCaps.pausedText(botId, threadLanguage(store.bot(botId)?.threadId ?? "")), held: (botId) => botHolds.held(botId),+ botState: unattendedDispatchState, pausedText: (botId) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? starterCaps.pausedText(botId, threadLanguage(store.bot(botId)?.threadId ?? "")), held: (botId) => botHolds.held(botId), capSkip: (botId, routineId) => usageCapGate.routineSkip(botId, routineId), capText: (botId, trigger) => usageCapGate.runText(botId, trigger, threadLanguage(store.bot(botId)?.threadId ?? "")),goalState: (groupId, coordinatorBotId) => {if (!groupId) return unattendedDispatchState(coordinatorBotId);const group = store.group(groupId);@@ -9461,7 +9462,7 @@ async function undoAppliedChange(res: ServerResponse, threadId: string, requestIconst webhooks = new WebhookManager({emit: broadcast,botState: unattendedDispatchState,- enqueue: (input) => routines!.enqueueWebhook(input),+ enqueue: (input) => { const capped = usageCapGate.refusal(input.botId, input.byPerson === true, threadLanguage(store.bot(input.botId)?.threadId ?? "")); if (capped) throw Object.assign(new Error(capped), { status: 429, code: USAGE_CAP_CODE }); return routines!.enqueueWebhook(input); },findRun: (webhookId, deliveryId) => routines!.webhookRunReceipt(webhookId, deliveryId),cancelQueued: (webhookId, message) => routines!.cancelQueuedWebhook(webhookId, message),pendingRuns: (webhookId) => routines!.activeWebhookRunCount(webhookId),@@ -9720,7 +9721,7 @@ async function runClaimedGroupMemberTurn(let roomFailure: string | undefined;const reportDispatchError = (message: string) => { roomFailure = message; onDispatchError?.(message); };try {- assertWithinBudget(cfg, DATA_DIR);+ assertWithinBudget(cfg, DATA_DIR); if (!operation?.continuesRun) usageCapGate.assertTurn(bot.id, personWaitingInRoom(operation, routineTriggerOf(threadId)), threadLanguage(threadId));assertModelVariantSupported(preparedSelection, instance.adapter.capabilities);const integrations: NonNullable<Parameters<typeof instance.adapter.sendTurn>[0]["integrations"]> = {};const skillAuthoring =@@ -10862,9 +10863,8 @@ function startGroupTurn(goalCoordinator || autoRoute ? [] : responders.map((responder) => responder.id),);// Only a person's own chat line; cloudHomeLendingRefusal still proves it is the owner's.- if (!goalCoordinator && message.role === "user" && !message.via && (!options.trigger || options.trigger.kind === "user" || options.trigger.kind === "owner")) {- operation.requestMessageId = message.id;- }+ operation.personStarted = message.role === "user" && !message.via && (!options.trigger || options.trigger.kind === "user" || options.trigger.kind === "owner");+ if (!goalCoordinator && operation.personStarted) operation.requestMessageId = message.id;const routing = autoRoute? decideRoomResponder(decider, roomRoutingInput(group.name, text, routableMembers, historyBeforeSend, userNameFor(group.threadId), options.sender), {signal: operation.cancellation.signal,@@ -12065,7 +12065,7 @@ const cloudMoveRoutes = createCloudMoveRoutes();// `workspaceAccess` is assigned at boot, after this line: read it per request.ROUTES.push(createHostedSlackRoutes({ bot: (id) => store.bot(id), hostedReady: () => Boolean(workspaceAccess) && entitled("admin") })); ROUTES.push(createStopLineRoutes());const orgInstallStatuses = () => orgLibrary?.installStatuses() ?? new Map();-ROUTES.push(createBotPresetRoutes({ presets: presetStore, orgStatuses: orgInstallStatuses })); ROUTES.push(createBotHoldRoutes({ holds: botHolds, named: (kind, id) => (kind === "bot" ? store.bot(id)?.name ?? null : store.sections.includes(id.trim()) ? id.trim() : null), stop: async (botIds) => { let stopped = 0; for (const botId of botIds) { for (const { threadId } of store.tasks(botId)) if (threadBusy(botId, threadId) || coordinator.activeDirect(threadId)) { await stopThreadForPerson(botId, threadId); stopped++; } for (const group of store.groups) if (roomThreadIds(group).some((threadId) => groupSpeakers.get(threadId)?.botId === botId)) { await interruptHeldMember(group.id, botId); stopped++; } } return stopped; }, audit: (entry, auth, req) => { if (!DESKTOP_MANAGED && adminActivityRecording()) appendAdminAction(DATA_DIR, { category: "bot", action: `${entry.kind}.${entry.paused ? "pause" : "resume"}`, target: { kind: entry.kind, id: entry.id, name: entry.name }, actor: adminActorFor(auth, req) }); } })); ROUTES.push(createWorkspaceBannerRoutes({ changed: () => broadcast({ kind: "config", ...configStatus() }) })); const starterAwakeRoutes = createStarterAwakeRoutes({ awake: starterAwake }); ROUTES.push(starterAwakeRoutes);+ROUTES.push(createBotPresetRoutes({ presets: presetStore, orgStatuses: orgInstallStatuses })); ROUTES.push(createBotHoldRoutes({ holds: botHolds, named: (kind, id) => (kind === "bot" ? store.bot(id)?.name ?? null : store.sections.includes(id.trim()) ? id.trim() : null), stop: async (botIds) => { let stopped = 0; for (const botId of botIds) { for (const { threadId } of store.tasks(botId)) if (threadBusy(botId, threadId) || coordinator.activeDirect(threadId)) { await stopThreadForPerson(botId, threadId); stopped++; } for (const group of store.groups) if (roomThreadIds(group).some((threadId) => groupSpeakers.get(threadId)?.botId === botId)) { await interruptHeldMember(group.id, botId); stopped++; } } return stopped; }, audit: (entry, auth, req) => { if (!DESKTOP_MANAGED && adminActivityRecording()) appendAdminAction(DATA_DIR, { category: "bot", action: `${entry.kind}.${entry.paused ? "pause" : "resume"}`, target: { kind: entry.kind, id: entry.id, name: entry.name }, actor: adminActorFor(auth, req) }); } })); ROUTES.push(createWorkspaceBannerRoutes({ changed: () => broadcast({ kind: "config", ...configStatus() }) })); ROUTES.unshift(createUsageCapRoutes({ view: () => usageCapGate.view(), botExists: (botId) => Boolean(store.bot(botId)), save: (usageCaps) => { saveConfig({ usageCaps }); Object.assign(cfg, loadConfig()); } })); const starterAwakeRoutes = createStarterAwakeRoutes({ awake: starterAwake }); ROUTES.push(starterAwakeRoutes);ROUTES.push(createSharedComputerRoutes({ enabled: (auth) => lendingEnabled() || (ownerLends() && ownHome.owner(auth)), computers: sharedComputers, sessionLive: (id) => sessions.isLive(id), environmentId: ENVIRONMENT_ID,cloudHomeLender: CLOUD_HOME ? CLOUD_HOME_LENDER : null, principal: sessionLendingPrincipal, personKey: (session) => lendingPersonKey(session, ownHome.ownServer()), power: () => cloudPower, links: CLOUD_HOME ? deviceLinks : null, upgrades, asks: computerAsks?.asks ?? null, answerer: cardAnswererFor }));// `routines` is assigned at boot, so it is read per request.@@ -12301,7 +12301,7 @@ ROUTES.push(createBrowserEvidenceRoutes({ evidence: browserEvidence.attach({ onCconst loginRoutes = botLogins.routes((id) => Boolean(store.bot(id))); ROUTES.push(createLoginRoutes(loginRoutes), createVaultRoutes({ logins: loginRoutes, secrets: logins, linked: () => botLogins.linkedSecrets(), keys: mcpKeys, reader: vaultReaders.viewer }));const privateRecords = createPrivateRecords({ visibleFor: (auth) => visibleTo(viewerFor(auth)), botExists: (id) => Boolean(store.bot(id)), routine: (id) => routines?.listRoutines().find((routine) => routine.id === id) }); const includedHosting = createIncludedHosting({ credential: () => hostingCredential(), dataDir: DATA_DIR, warn: (line) => console.warn(line) }), appPublisher = createAppPublisher({ hosting: includedHosting, botName: (id) => store.bot(id)?.name ?? "", botFolder: workspaceDir, home: homedir(), env: process.env }); ROUTES.push(createPublishedAppsRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), apps: createPublishedApps({ included: { hosting: includedHosting, publisher: appPublisher }, bots: () => store.bots, rooms: () => store.groups, messages: (threadId) => store.messagesFor(threadId), folders: (bot) => [...new Set([bot.threadId, ...(bot.tasks ?? []).map((task) => task.threadId)].flatMap((threadId) => liveRoots(threadId, bot.id) ?? []))], ownFolder: (botId, threadId) => join(TASK_WORKSPACES_DIR, botId, threadId), pages: () => publishedPages.store.list(), unpublishPage: (pageId) => publishedPages.publisher.unpublish({ pageId }), netlifyToken: (botId, auth, threadId) => savedNetlifyToken(logins, botId, CLOUD_TEAM && !threadId ? null : vaultReaders.turn(threadId ?? ""), auth.kind === "session" ? actorKey(auth) : null), ownChat: (auth, threadId) => auth.kind === "session" && teamHost.privateTo(threadId) === personKey(auth.session), home: homedir(), env: process.env }) })); ROUTES.push(createUsageRoutes({dataDir: DATA_DIR, prices: operatorPrices,- budget: () => spendState(cfg, DATA_DIR),+ budget: () => spendState(cfg, DATA_DIR), caps: (auth) => (auth.scopes.includes("admin") ? usageCapGate.view() : null), onPlan: (instanceId) => registry.lastSnapshot(instanceId)?.billing === "subscription",currency: () => cfg.billing?.currency ?? "USD",recorder: usageTrace, messages: (threadId) => store.messagesFor(threadId), liveBot: (threadId) => {const bot = store.botByThread(threadId) ?? store.bot(groupSpeakers.get(threadId)?.botId ?? "");diff --git a/server/routes/usage-caps.ts b/server/routes/usage-caps.tsnew file mode 100644index 0000000000..b0c2db55ac--- /dev/null+++ b/server/routes/usage-caps.ts@@ -0,0 +1,40 @@+// The usage caps as the owner sets them: GET /api/usage/caps answers with the saved caps, what the environment sets+// and each cap's use now; PUT replaces the saved caps. Admin scope only: on a self-hosted server that is its owner.+import { CAP_FIELDS, usageCapsSchema, type CapLimits, type UsageCapsConfig } from "../usage-caps.ts";+import type { UsageCapView } from "../host/usage-cap-gate.ts";+import { schemaIssue } from "../schema.ts";+import { PASS, type RouteHandler } from "./table.ts";++export interface UsageCapRouteDeps {+ view(): UsageCapView;+ botExists(botId: string): boolean;+ save(caps: UsageCapsConfig): void;+}++const OWNER_ONLY = "Only the owner of this server can see or change its usage caps.";++/** Zero and empty mean no cap, so neither is kept. */+function setLimits(limits: CapLimits | undefined): CapLimits {+ const kept: CapLimits = {};+ for (const { field } of CAP_FIELDS) {+ const value = limits?.[field];+ if (typeof value === "number" && value > 0) kept[field] = value;+ }+ return kept;+}++export function createUsageCapRoutes(deps: UsageCapRouteDeps): RouteHandler {+ return async ({ req, res, path, method, auth, json, readBody }) => {+ if (path !== "/api/usage/caps" || (method !== "GET" && method !== "PUT")) return PASS;+ if (!auth.scopes.includes("admin")) return void json(res, 403, { error: OWNER_ONLY });+ res.setHeader("cache-control", "no-store");+ if (method === "GET") return void json(res, 200, deps.view());+ const parsed = usageCapsSchema.safeParse(await readBody(req, 65_536).catch(() => null));+ if (!parsed.success) return void json(res, 400, { error: schemaIssue(parsed.error, "Send stops (unattended or everything), server and bots, each cap a number of dollars or tokens.") });+ const unknown = Object.keys(parsed.data.bots ?? {}).find((botId) => !deps.botExists(botId));+ if (unknown) return void json(res, 404, { error: `No such bot: ${unknown}` });+ const bots = Object.fromEntries(Object.entries(parsed.data.bots ?? {}).map(([botId, limits]) => [botId, setLimits(limits)] as const).filter(([, limits]) => Object.keys(limits).length));+ deps.save({ stops: parsed.data.stops ?? "unattended", server: setLimits(parsed.data.server), bots });+ json(res, 200, deps.view());+ };+}diff --git a/server/routes/usage-not-billed.test.ts b/server/routes/usage-not-billed.test.tsnew file mode 100644index 0000000000..6811157a67--- /dev/null+++ b/server/routes/usage-not-billed.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";++import type { UsageRow } from "../usage-ledger.ts";+import { notBilledShare } from "./usage.ts";++const row = (instanceId: string, costUsd: number | null): UsageRow => ({+ at: "2026-09-15T08:00:00.000Z", botId: "b", botName: "B", threadId: "t", instanceId, driverKind: "claudeAgent", model: "m", input: 10, output: 5, costUsd, trigger: { kind: "owner" },+});++describe("the part of a period's dollars nobody is billed", () => {+ it("adds up only priced turns on engines signed in with a subscription, asking about each engine once", () => {+ const asked: string[] = [];+ const onPlan = (instanceId: string) => { asked.push(instanceId); return instanceId === "claude"; };+ const rows = [row("claude", 0.5), row("claude", 0.25), row("claude", null), row("claude", 0), row("openai", 2), row("openai", 1)];+ expect(notBilledShare(rows, onPlan)).toEqual({ usd: 0.75, turns: 2 });+ expect(asked).toEqual(["claude", "openai"]);+ expect(notBilledShare([], onPlan)).toEqual({ usd: 0, turns: 0 });+ });+});diff --git a/server/routes/usage.ts b/server/routes/usage.tsindex c2822b8a79..f78c1922b3 100644--- a/server/routes/usage.ts+++ b/server/routes/usage.ts@@ -2,6 +2,7 @@ import { redactSecretsInText } from "../../shared/redact.ts";import type { PriceList } from "../prices.ts";import type { RequestAuth } from "../request-auth.ts";import type { SpendState } from "../spend.ts";+import type { UsageCapView } from "../host/usage-cap-gate.ts";import {flushUsageLedger,parseUsageRange,@@ -23,6 +24,10 @@ export interface UsageRouteDeps {dataDir: string;prices(): PriceList | null;budget(): SpendState | null;+ /** The open usage caps with their use now, for the owner; null for anyone else. */+ caps(auth: RequestAuth): UsageCapView | null;+ /** Whether this engine is signed in with a subscription now: its dollars are an estimate nobody is billed. */+ onPlan(instanceId: string): boolean;currency(): string;recorder: TraceServiceDeps["recorder"];messages: TraceServiceDeps["messages"];@@ -40,6 +45,21 @@ const whole = (raw: string | null, fallback: number, max: number): number | nullreturn /^\d{1,7}$/.test(raw) && Number(raw) <= max ? Number(raw) : null;};+/** The period's dollars booked on engines signed in with a subscription now, and the turns they came from. A row keeps+ * no record of how its engine was signed in when it ran, so this reads the sign-in as it is today. */+export function notBilledShare(rows: readonly UsageRow[], onPlan: (instanceId: string) => boolean): { usd: number; turns: number } {+ const plan = new Map<string, boolean>();+ let usd = 0, turns = 0;+ for (const row of rows) {+ if (typeof row.costUsd !== "number" || !(row.costUsd > 0)) continue;+ if (!plan.has(row.instanceId)) plan.set(row.instanceId, onPlan(row.instanceId));+ if (!plan.get(row.instanceId)) continue;+ usd += row.costUsd;+ turns += 1;+ }+ return { usd, turns };+}+/** The usage endpoints: trace browsing plus the grouped token and cost summary with its CSV export. */export function createUsageRoutes(deps: UsageRouteDeps): RouteHandler {const traces = createTraceService({ dataDir: deps.dataDir, recorder: deps.recorder, messages: deps.messages, liveBot: deps.liveBot });@@ -99,6 +119,8 @@ export function createUsageRoutes(deps: UsageRouteDeps): RouteHandler {splitBy,...summarizeUsage(rows, groupBy, prices, splitBy),budget: deps.budget(),+ caps: deps.caps(auth),+ notBilled: notBilledShare(rows, deps.onPlan),billing: prices ? { currency: deps.currency() } : null,});};diff --git a/server/routine-lines.ts b/server/routine-lines.tsindex 0816ebd8ea..8e944ba9cd 100644--- a/server/routine-lines.ts+++ b/server/routine-lines.ts@@ -34,6 +34,12 @@ export const ROUTINE_LINE = {"routines.server.part.computerNoStart": "its cloud desktop has not started, so its next tries are spaced out","routines.server.part.runsFailed": "its last runs failed, so its next tries are spaced out","routines.server.part.restartedSoon": "OpenMausBot started again soon after the start that last ran it",+ "routines.server.capSkippedOne": "Skipped: {why} ({amount}) is reached. Runs start again after {resets}",+ "routines.server.capSkippedMany": "Skipped {count} runs: {why} ({amount}) is reached. Runs start again after {resets}",+ "routines.server.part.capServerDay": "the daily usage cap for all bots",+ "routines.server.part.capServerMonth": "the monthly usage cap for all bots",+ "routines.server.part.capBotDay": "this bot’s daily usage cap",+ "routines.server.part.capBotMonth": "this bot’s monthly usage cap","routines.server.missedOne": "Missed because {why}","routines.server.missedMany": "Missed {count} scheduled runs because {why}","routines.server.missedTooLate": "Missed because {why} until more than {hours} hours after its time",diff --git a/server/routine-skips.ts b/server/routine-skips.tsindex 8fb248c0fa..baa73c46c3 100644--- a/server/routine-skips.ts+++ b/server/routine-skips.ts@@ -2,7 +2,7 @@// (the same earlier run still going, the same spacing after a cloud computer that did not start or after failed runs) share one row, which// counts them and keeps the first and last time: a schedule every minute behind a run of hours adds one row, not hundreds.import { ROUTINE_DEFERRAL_NOTICE_MS } from "./routine-execution.ts";-import { codedLine, type RoutineLineKey } from "./routine-lines.ts";+import { codedLine, type RoutineLine, type RoutineLineKey } from "./routine-lines.ts";import type { RoutineRun } from "./routines.ts";/** What a `missed` row stands for when it counts skipped occurrences. */@@ -34,8 +34,9 @@ export function blockingRun(runs: readonly RoutineRun[], routineId: string): { r* `earlier` occurrences that came due before it while nothing could look (routine-catch-up.ts). `tell` is true once per* waiting run, for the first occurrence skipped after it had waited a notice window: the owner is told then, and the row* shows as not yet seen. Any other skip is on a row already seen: a run that is still working when the next one comes- * due, or a spacing the owner was told about when it began, asks nothing more of them. */-export function recordSkip(runs: readonly RoutineRun[], make: () => RoutineRun, cause: { behind: string; why: SkipWhy; waitingSince?: number }, scheduledFor: number, now: number,+ * due, or a spacing the owner was told about when it began, asks nothing more of them. A cause+ * that is not one of the `why` parts (a reached usage cap) gives its row's line itself, as `words`. */+export function recordSkip(runs: readonly RoutineRun[], make: () => RoutineRun, cause: { behind: string; waitingSince?: number } & ({ why: SkipWhy } | { words: (count: number) => RoutineLine }), scheduledFor: number, now: number,earlier?: { count: number; scheduledFor: number }): { row: RoutineRun; added: boolean; tell: boolean } {const found = runs.findLast((run) => run.status === "missed" && run.skipped?.behind === cause.behind);const row = found ?? make(), count = 1 + (earlier?.count ?? 0);@@ -44,8 +45,9 @@ export function recordSkip(runs: readonly RoutineRun[], make: () => RoutineRun,: { count, firstAt: earlier?.scheduledFor ?? scheduledFor, lastAt: scheduledFor, behind: cause.behind };const tell = !skipped.told && cause.waitingSince !== undefined && scheduledFor >= cause.waitingSince + ROUTINE_DEFERRAL_NOTICE_MS;if (tell) skipped.told = true;- const atStart = cause.why === "routines.server.part.restartedSoon";- const line = skipped.count === 1 ? codedLine("error", atStart ? "routines.server.startSkippedOne" : "routines.server.skippedOne", { why: cause.why })+ const atStart = "why" in cause && cause.why === "routines.server.part.restartedSoon";+ const line = "words" in cause ? cause.words(skipped.count)+ : skipped.count === 1 ? codedLine("error", atStart ? "routines.server.startSkippedOne" : "routines.server.skippedOne", { why: cause.why }): codedLine("error", atStart ? "routines.server.startSkippedMany" : "routines.server.skippedMany", { count: skipped.count, why: cause.why });Object.assign(row, line.codes, { status: "missed", error: line.text, finishedAt: now, skipped } satisfies Partial<RoutineRun>);if (tell) delete row.seenAt;diff --git a/server/routines.test.ts b/server/routines.test.tsindex 86154d2626..0f71fe910f 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -17,6 +17,9 @@ import {type RoutineRun,type RoutineSchedule,} from "./routines.ts";+import { createUsageCapGate } from "./host/usage-cap-gate.ts";+import { resetUsageTotalsForTests } from "./usage-caps.ts";+import { appendUsage, flushUsageLedger } from "./usage-ledger.ts";const dirs: string[] = [];/** Runs that were made to start: a `missed` row that only counts skipped occurrences is left out. */@@ -4122,6 +4125,121 @@ describe("turning a schedule back on, and a deleted bot's schedules", () => {});});+describe("a reached usage cap", () => {+ const start = Date.parse("2026-09-13T08:00:00Z"), HOUR = 3_600_000, DAY = 24 * HOUR;+ const line = (count: number) => ({ text: count === 1 ? "Skipped: the cap is reached" : `Skipped ${count} runs: the cap is reached`, codes: {} });++ it("counts the scheduled runs it skips on one row, leaves the routine on, lets a hand-started run go, and runs again once it lifts", async () => {+ const h = harness(start);+ let capped = true;+ h.options.capSkip = () => (capped ? { behind: "cap:server:day:usd:2026-09-13", resetsAt: start + DAY, words: line } : null);+ h.options.capText = (_botId, trigger) => (capped && trigger !== "manual" ? "Not started: the cap is reached" : null);+ const routine = h.manager.create({ name: "Hourly check", prompt: "Check", botId: "maus-1", schedule: { type: "interval", everyMinutes: 60, anchorAt: start + HOUR } });+ for (let hour = 1; hour <= 3; hour += 1) {+ h.setNow(start + hour * HOUR);+ await h.manager.tick();+ }+ const rows = h.manager.listRuns();+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ status: "missed", error: "Skipped 3 runs: the cap is reached", skipped: { count: 3, firstAt: start + HOUR, lastAt: start + 3 * HOUR, behind: "cap:server:day:usd:2026-09-13" } });+ expect(rows[0]!.seenAt).toBeDefined();+ expect(h.manager.listRoutines()[0]).toMatchObject({ id: routine.id, enabled: true, nextRunAt: start + 4 * HOUR });+ expect(h.manager.listRoutines()[0]!.skippedRuns ?? 0).toBe(0);+ expect([h.started, h.failed, h.taskTitles]).toEqual([[], [], []]);++ // A webhook's run that was already queued is let go with the line, quietly; one started by hand runs.+ h.manager.enqueueWebhook({ webhookId: "hook", webhookName: "New lead", prompt: "Handle it", botId: "maus-1", runOn: "maus", deliveryId: "d1", receivedAt: start + 3 * HOUR });+ await h.manager.tick();+ expect(h.manager.listRuns().find((run) => run.webhookId === "hook")).toMatchObject({ status: "cancelled", error: "Not started: the cap is reached" });+ expect([h.started, h.failed]).toEqual([[], []]);+ h.manager.runNow(routine.id);+ await h.manager.tick();+ expect(h.started).toHaveLength(1);+ h.manager.handleRuntimeEvent({ eventId: "done", provider: "fake", threadId: h.started[0]!.threadId, createdAt: new Date().toISOString(), type: "turn.completed", ok: true });++ // The next day is a new period: its row would be a new one, and with the cap lifted the schedule simply runs.+ capped = false;+ h.setNow(start + 4 * HOUR);+ await h.manager.tick();+ expect(h.started).toHaveLength(2);+ expect(h.manager.listRuns().filter((run) => run.skipped)).toHaveLength(1);+ });++ it("applies to a routine whose bot is not paused only: a paused bot keeps its own line", async () => {+ const h = harness(start);+ h.options.pausedText = () => "Ada is paused, so it takes no new work.";+ h.options.held = () => true;+ h.options.capSkip = () => ({ behind: "cap:server:day:usd:2026-09-13", resetsAt: start + DAY, words: line });+ h.manager.create({ name: "Hourly check", prompt: "Check", botId: "maus-1", schedule: { type: "interval", everyMinutes: 60, anchorAt: start + HOUR } });+ h.setNow(start + HOUR);+ await h.manager.tick();+ await h.manager.tick();+ expect(h.manager.listRuns().map((run) => [run.status, run.error])).toEqual([["cancelled", "Ada is paused, so it takes no new work."]]);+ });++ /** The harness wired to the real cap gate over a ledger whose day of 2026-09-13 already used the server's 1-token cap. */+ async function cappedHarness() {+ const h = harness(start);+ const dataDir = mkdtempSync(join(tmpdir(), "omb-routine-caps-"));+ dirs.push(dataDir);+ resetUsageTotalsForTests();+ appendUsage(dataDir, { at: "2026-09-13T07:00:00.000Z", botId: "maus-1", botName: "Ada", threadId: "t", instanceId: "claude", driverKind: "claudeAgent", model: "m", input: 5, output: 0, costUsd: 0, trigger: { kind: "owner" } });+ await flushUsageLedger(dataDir);+ let clock = start;+ const gate = createUsageCapGate({ dataDir, caps: () => ({ server: { dailyTokens: 1 } }), botName: () => "Ada", now: () => new Date(clock), env: {}, notice: () => {}, log: () => {} });+ h.options.capSkip = (botId, routineId) => gate.routineSkip(botId, routineId);+ h.options.capText = (botId, trigger) => gate.runText(botId, trigger);+ return { ...h, at: (value: number) => { clock = value; h.setNow(value); } };+ }++ it("keeps each routine's own skipped row when two come due under one cap", async () => {+ const h = await cappedHarness();+ const first = h.manager.create({ name: "Hourly check", prompt: "Check", botId: "maus-1", schedule: { type: "interval", everyMinutes: 60, anchorAt: start + HOUR } });+ const second = h.manager.create({ name: "Hourly sweep", prompt: "Sweep", botId: "maus-1", schedule: { type: "interval", everyMinutes: 60, anchorAt: start + HOUR } });+ for (let hour = 1; hour <= 2; hour += 1) {+ h.at(start + hour * HOUR);+ await h.manager.tick();+ }+ const rows = h.manager.listRuns();+ expect(rows.map((run) => [run.routineId, run.status, run.skipped?.count]).sort()).toEqual([[first.id, "missed", 2], [second.id, "missed", 2]].sort());+ expect(new Set(rows.map((run) => run.skipped?.behind)).size).toBe(2);+ for (const row of rows) expect(row.skipped!.behind).toBe(`cap:${row.routineId}:server:day:tokens:2026-09-13`);+ expect(h.started).toEqual([]);+ });++ it("keeps a once-only routine on while capped and runs it when the cap resets", async () => {+ const h = await cappedHarness();+ const routine = h.manager.create({ name: "Send the report", prompt: "Send it", botId: "maus-1", schedule: { type: "once", at: start + HOUR } });+ h.at(start + HOUR);+ await h.manager.tick();+ const reset = Date.parse("2026-09-14T00:00:00Z");+ expect(h.manager.listRoutines()[0]).toMatchObject({ id: routine.id, enabled: true, nextRunAt: reset, schedule: { type: "once", at: reset } });+ expect(h.manager.listRuns().map((run) => [run.status, run.skipped?.count])).toEqual([["missed", 1]]);+ expect(h.started).toEqual([]);++ // Later the same day it is still waiting; at the rollover the cap counts from zero and the run goes.+ h.at(start + 3 * HOUR);+ await h.manager.tick();+ expect(h.started).toEqual([]);+ h.at(reset);+ await h.manager.tick();+ expect(h.started).toHaveLength(1);+ expect(h.manager.listRoutines()[0]).toMatchObject({ enabled: false, nextRunAt: null });+ });++ it("lets a person's own Run now of a webhook start while capped, and lets an outside delivery go", async () => {+ const h = await cappedHarness();+ h.at(start + HOUR);+ h.manager.enqueueWebhook({ webhookId: "hook", webhookName: "New lead", prompt: "Handle it", botId: "maus-1", runOn: "maus", deliveryId: "test-1", receivedAt: start + HOUR, byPerson: true });+ h.manager.enqueueWebhook({ webhookId: "hook", webhookName: "New lead", prompt: "Handle it", botId: "maus-1", runOn: "maus", deliveryId: "outside-1", receivedAt: start + HOUR });+ await h.manager.tick();+ const runs = h.manager.listRuns();+ expect(runs.find((run) => run.deliveryId === "test-1")).toMatchObject({ status: "running", byPerson: true });+ expect(runs.find((run) => run.deliveryId === "outside-1")).toMatchObject({ status: "cancelled", error: expect.stringContaining("Not started: the daily usage cap for all bots (1 tokens) is reached") });+ expect(h.started).toHaveLength(1);+ });+});+describe("runs that report into a chat", () => {const input = () => ({ name: "Inbox brief", prompt: "Brief me", botId: "maus-1", enabled: false,schedule: { type: "interval" as const, everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } });diff --git a/server/routines.ts b/server/routines.tsindex e522e0bb8c..fa344a281c 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -38,7 +38,7 @@ import { loadInstalledPackage, matchingRequestReceipt, rememberRequest } from ".import { applyHolds, holdCauses, type AppliedHolds } from "./routine-holds.ts";import { cancelUnfinishedRuns, interruptRunTurns } from "./routine-stops.ts";import { sanitizeInput } from "./routine-input.ts";-import { applyCheckResult, clipRunOutput, codedLine, routineLine, runLineFields, type RoutineLineCodes, type RoutineTroubleCode } from "./routine-lines.ts";+import { applyCheckResult, clipRunOutput, codedLine, routineLine, runLineFields, type RoutineLine, type RoutineLineCodes, type RoutineTroubleCode } from "./routine-lines.ts";import { checkHold, CHECK_BOOT_HOLD_MS, type CheckHold } from "./routine-check-pacing.ts";import { resolveRoutineResultsThread, routineRunDefinition, type ResultsThreadAllocation } from "./routine-run-definition.ts";@@ -131,7 +131,7 @@ export interface RoutineRun extends RoutineLineCodes, RoutineOwnerMark {workedMs?: number;triggerSource?: RoutineRunTrigger;/** "app": a connected-app event started it; "wait": a wait's follow-up did (its triggerSource stays "webhook", an outside event). sameConversation: its trigger keeps one conversation (routine-same-conversation.ts). */- eventSource?: "app" | "wait"; sameConversation?: true;+ eventSource?: "app" | "wait"; sameConversation?: true; /** A person's own "Run now" test of its webhook started it: a usage cap treats it as a run started by hand. */ byPerson?: true;webhookId?: string;deliveryId?: string;sourceThreadId?: string;@@ -238,7 +238,7 @@ export interface RoutineManagerOptions {/** Every payload must be `{ kind, … }`: the server numbers and replays frames by it. */emit?: (payload: Record<string, unknown>) => void;botState: (botId: string) => "ready" | "busy" | "missing";- /** Why this bot takes no runs now, in the person's words (a Starter Cloud keeps only so many bots awake); null when it does. */ pausedText?: (botId: string) => string | null; /** The person paused this bot: its runs are let go quietly, not failed into To review. */ held?: (botId: string) => boolean;+ /** Why this bot takes no runs now, in the person's words (a Starter Cloud keeps only so many bots awake); null when it does. */ pausedText?: (botId: string) => string | null; /** The person paused this bot: its runs are let go quietly, not failed into To review. */ held?: (botId: string) => boolean; /** A reached usage cap (host/usage-cap-gate.ts): `capSkip` for a scheduled occurrence, which is counted on one `missed` row per cap and period and never switches the routine off; `capText` for a run already queued. */ capSkip?: (botId: string, routineId: string) => { behind: string; resetsAt: number; words(count: number): RoutineLine } | null; capText?: (botId: string, trigger: RoutineRunTrigger) => string | null;goalState?: (groupId: string | undefined, coordinatorBotId: string) => "ready" | "busy" | "missing";createTask: (botId: string, title: string, run?: RoutineRun) => { threadId: string } | null;joinConversation?: (run: RoutineRun) => string | null;@@ -770,7 +770,7 @@ export class RoutineManager {enqueueWebhook(input: {webhookId: string; webhookName: string; prompt: string; botId: string; runOn: RoutineRunOn; deliveryId: string; receivedAt: number;- eventSource?: "app" | "wait"; sameConversation?: boolean;+ eventSource?: "app" | "wait"; sameConversation?: boolean; byPerson?: boolean;/** Where the run reports, instead of the event's own results chat. */resultsThreadId?: string;}): { id: string } {@@ -784,7 +784,7 @@ export class RoutineManager {id: randomUUID(), routineId: input.webhookId, routineName: input.webhookName, prompt: input.prompt, target: "bot",botId: input.botId, runOn: input.runOn, scheduledFor: input.receivedAt, status: "queued", manual: false,triggerSource: "webhook", webhookId: input.webhookId, deliveryId: input.deliveryId, attachments: [], createdAt: this.now(),- resultsThreadId: input.resultsThreadId ?? this.options.eventResultsThread?.(input), ...(input.eventSource ? { eventSource: input.eventSource } : {}), ...(input.sameConversation ? { sameConversation: true } : {}),+ resultsThreadId: input.resultsThreadId ?? this.options.eventResultsThread?.(input), ...(input.eventSource ? { eventSource: input.eventSource } : {}), ...(input.sameConversation ? { sameConversation: true } : {}), ...(input.byPerson ? { byPerson: true } : {}),};this.commitEvent(run, input.deliveryId, () => { this.runs.push(run); });return cloneRun(run);@@ -1055,16 +1055,17 @@ export class RoutineManager {const once = runsOnce(routine.schedule), blocker = once ? undefined : blockingRun(this.runs, routine.id), spaced = once ? null : runSpacing(routine, this.runs);const scheduledQueued = this.runs.some(run => run.routineId === routine.id && run.status === "queued" &&(run.triggerSource ?? (run.manual ? "manual" : "schedule")) === "schedule");- const skipFor = blocker && !(routine.overlap === "queue" && !scheduledQueued) ? { behind: blocker.run.id, why: blocker.why, waitingSince: blocker.waitingSince }- : spaced && spaced.until > now ? { behind: spaced.behind, why: spaced.why } : undefined;+ const capped = routine.target !== "room-goal" && this.options.pausedText?.(routine.botId) ? null : this.options.capSkip?.(routine.botId, routine.id);+ const skipFor = capped ?? (blocker && !(routine.overlap === "queue" && !scheduledQueued) ? { behind: blocker.run.id, why: blocker.why, waitingSince: blocker.waitingSince }+ : spaced && spaced.until > now ? { behind: spaced.behind, why: spaced.why } : undefined);if (!skipFor) {if (plan.older) countedSkips.push(Object.assign(this.newRun(routine, plan.older.scheduledFor, false, allocations), plan.older.fields));scheduledRuns.push(Object.assign(this.newRun(routine, scheduledFor, false, allocations), plan.fields, plan.late ? staggered(now, lateStarts++) : {}));} else {const skip = recordSkip(this.runs, () => this.newRun(routine, plan.through, false, allocations), skipFor, plan.through, now, plan.count > 1 ? { count: plan.count - 1, scheduledFor: plan.first } : undefined);(skip.tell ? scheduledRuns : countedSkips).push(skip.row);- routine.skippedRuns = Math.min(Number.MAX_SAFE_INTEGER, (routine.skippedRuns ?? 0) + plan.count);- routine.lastSkippedAt = plan.through;+ if (!capped) { routine.skippedRuns = Math.min(Number.MAX_SAFE_INTEGER, (routine.skippedRuns ?? 0) + plan.count); routine.lastSkippedAt = plan.through; }+ else if (once) { if (routine.schedule.type === "once") routine.schedule = { type: "once", at: capped.resetsAt }; routine.nextRunAt = capped.resetsAt; continue; } // a capped once-only run is not used up: it runs when the cap resets}this.advancePastOccurrence(routine, now, plan.through);}@@ -1138,7 +1139,7 @@ export class RoutineManager {if (state === "missing") { this.failRun(run, this.missingTargetMessage(run.target)); continue; }const paused = run.target === "room-goal" ? null : this.options.pausedText?.(run.botId);if (!this.ledger.ready(run)) continue; if (this.ledger.startedElsewhere(run)) { const line = codedLine("error", "routines.server.duplicate"); Object.assign(run, line.codes); void this.cancelRun(run.id, line.text); continue; }- if (paused) { if (triggerSource !== "manual" && this.options.held?.(run.botId)) void this.cancelRun(run.id, paused); else this.failRun(run, paused); continue; } const gated = triggerSource === "manual" ? false : this.gate.hold(run); if (gated === true) { if (this.options.preparing && run.attention !== this.options.preparing) { run.attention = this.options.preparing; this.emitRun(run); } continue; } if (gated) { this.failRun(run, gated); continue; }+ if (paused) { if (triggerSource !== "manual" && this.options.held?.(run.botId)) void this.cancelRun(run.id, paused); else this.failRun(run, paused); continue; } const startedBy = run.byPerson ? "manual" : triggerSource, capped = this.options.capText?.(run.botId, startedBy); if (capped) { if (startedBy === "manual") this.failRun(run, capped); else void this.cancelRun(run.id, capped); continue; } const gated = triggerSource === "manual" ? false : this.gate.hold(run); if (gated === true) { if (this.options.preparing && run.attention !== this.options.preparing) { run.attention = this.options.preparing; this.emitRun(run); } continue; } if (gated) { this.failRun(run, gated); continue; }const startedAt = this.now();const suffix = ` · ${new Date(startedAt).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}`;const title = `${run.routineName.slice(0, 80 - suffix.length).trimEnd()}${suffix}`;diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.tsindex 87c4c58883..47f087225e 100644--- a/server/runtime-coordinator.ts+++ b/server/runtime-coordinator.ts@@ -273,7 +273,7 @@ export class RuntimeCoordinator implements Coordinator {const existing = siblings.findLast(c => c.assignee.botId === target.botId && c.assignee.destination.groupId === target.groupId && c.brief === brief && c.mode === mode&& (!own || c.assignee.destination.threadId === target.threadId));if (existing && !(rework && isTerminal(existing))) return { node: view(existing, parent), duplicate: true };- const limited = this.handoffLimit?.refusal(target.botId, () => this.live().filter(a => a.parentId !== undefined).length);+ const limited = this.handoffLimit?.refusal(target.botId, () => this.live().filter(a => a.parentId !== undefined).length, parent.origin.kind === "person" ? "user" : "outside");if (limited) throw new Error(limited);if (mode === "work" && !rework && !own && siblings.some(c => c.mode === "work" && kindOf(c.assignee.destination.groupId, parent) === kind &&c.assignee.destination.groupId === target.groupId && c.assignee.botId === target.botId && c.status === "completed")) throw new Error(ALREADY_COMPLETED);diff --git a/server/spend.test.ts b/server/spend.test.tsindex 05e4ac5553..462f0912a6 100644--- a/server/spend.test.ts+++ b/server/spend.test.ts@@ -113,7 +113,8 @@ describe("spend against a monthly cap", () => {expect(spendState({ budgets: { monthlyUsd: 10, warnAtPercent: 90 } }, dataDir, now, yes)?.warn).toBe(false);expect(() => assertWithinBudget({ budgets: { monthlyUsd: 10 } }, dataDir, now, yes)).not.toThrow();expect(() => assertWithinBudget({ budgets: { monthlyUsd: 8 } }, dataDir, now, yes)).toThrow(- expect.objectContaining({ status: 409, code: "spend_cap", message: expect.stringContaining("$8.00") }),+ // resetsAt: a Bot API caller is told when to try again (Retry-After), the start of the next UTC month.+ expect.objectContaining({ status: 409, code: "spend_cap", message: expect.stringContaining("$8.00"), resetsAt: Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1) }),);expect(() => assertWithinBudget({ budgets: { monthlyUsd: 8 } }, dataDir, now, no)).not.toThrow();});diff --git a/server/spend.ts b/server/spend.tsindex 521d0bb377..31c5904323 100644--- a/server/spend.ts+++ b/server/spend.ts@@ -1,9 +1,10 @@-// Monthly spend cap over the usage ledger; enforced only with the `budgets` entitlement.+// The licensed monthly spend cap: enforced only with the `budgets` entitlement. It reads its total from the cap engine+// (usage-caps.ts) and adds its own warning threshold, admin notifications and a stop on every kind of turn.import { mkdirSync, readFileSync, writeFileSync } from "node:fs";import { join } from "node:path";import type { AppConfig } from "./config.ts";import { entitled } from "./enterprise.ts";-import { readUsage, usageRowKey } from "./usage-ledger.ts";+import { CAP_WARN_PERCENT, measure, monthKeyOf, noteUsage, periodEnd, resetUsageTotalsForTests, usageTotals } from "./usage-caps.ts";export interface SpendState {month: string;@@ -15,61 +16,14 @@ export interface SpendState {exceeded: boolean;}-const DEFAULT_WARN_AT_PERCENT = 80;-const CACHE_MS = 15_000;-const cache = new Map<string, { at: number; month: string; fileUsd: number; keys: Set<string> }>();-// Rows whose async ledger append may not have landed yet: a long turn would otherwise re-read the month without its own row.-const unwritten = new Map<string, Map<string, { month: string; costUsd: number }>>();--function monthOf(now: Date): string {- return now.toISOString().slice(0, 7);-}--const costOf = (value: unknown): number => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0);+const DEFAULT_WARN_AT_PERCENT = CAP_WARN_PERCENT;export function monthToDateSpend(dataDir: string, now = new Date()): number {- const month = monthOf(now);- let read = cache.get(dataDir);- if (!read || read.month !== month || now.getTime() - read.at >= CACHE_MS) {- const from = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));- const rows = readUsage(dataDir, { from, to: now });- read = { at: now.getTime(), month, fileUsd: rows.reduce((sum, row) => sum + costOf(row.costUsd), 0), keys: new Set(rows.map(usageRowKey)) };- cache.set(dataDir, read);- }- let pending = 0;- for (const [key, entry] of unwritten.get(dataDir) ?? []) {- if (entry.month === month && !read.keys.has(key)) pending += entry.costUsd;- }- return read.fileUsd + pending;+ return usageTotals(dataDir, now).server.month.usd;}-export function noteSpend(- dataDir: string,- row: { at: string; threadId: string; botId: string; costUsd: number | null | undefined },- written: Promise<boolean>,-): void {- const costUsd = costOf(row.costUsd);- if (!costUsd) return;- const key = usageRowKey(row);- const month = row.at.slice(0, 7);- const entries = unwritten.get(dataDir) ?? new Map<string, { month: string; costUsd: number }>();- unwritten.set(dataDir, entries);- entries.set(key, { month, costUsd });- void written.then((landed) => {- entries.delete(key);- if (entries.size === 0 && unwritten.get(dataDir) === entries) unwritten.delete(dataDir);- const read = cache.get(dataDir);- if (landed && read && read.month === month && !read.keys.has(key)) {- read.fileUsd += costUsd;- read.keys.add(key);- }- });-}--export function resetSpendCacheForTests(): void {- cache.clear();- unwritten.clear();-}+export const noteSpend = noteUsage;+export const resetSpendCacheForTests = resetUsageTotalsForTests;export function spendState(cfg: Pick<AppConfig, "budgets">,@@ -81,16 +35,8 @@ export function spendState(if (!isEntitled("budgets") || typeof monthlyUsd !== "number" || !Number.isFinite(monthlyUsd) || monthlyUsd <= 0) return null;const spentUsd = monthToDateSpend(dataDir, now);const warnAtPercent = cfg.budgets?.warnAtPercent ?? DEFAULT_WARN_AT_PERCENT;- const percent = Math.min(999, Math.round((spentUsd / monthlyUsd) * 100));- return {- month: monthOf(now),- monthlyUsd,- spentUsd,- percent,- warnAtPercent,- warn: percent >= warnAtPercent,- exceeded: spentUsd >= monthlyUsd,- };+ const { percent, warn, reached } = measure(monthlyUsd, spentUsd, warnAtPercent);+ return { month: monthKeyOf(now), monthlyUsd, spentUsd, percent, warnAtPercent, warn, exceeded: reached };}function usd(value: number): string {@@ -107,7 +53,8 @@ export function assertWithinBudget(if (!state?.exceeded) return;throw Object.assign(new Error(`this workspace has reached its monthly spend limit of $${usd(state.monthlyUsd)} — an admin can raise it under Settings → Usage`),- { status: 409, code: "spend_cap" },+ // When the month rolls over and work may start again: a Bot API caller is told it as Retry-After.+ { status: 409, code: "spend_cap", resetsAt: periodEnd("month", now) },);}diff --git a/server/usage-caps-config.ts b/server/usage-caps-config.tsnew file mode 100644index 0000000000..ec0ec83874--- /dev/null+++ b/server/usage-caps-config.ts@@ -0,0 +1,27 @@+// The shape of `usageCaps` in config.json, apart from the engine that reads the ledger (usage-caps.ts).+import { z } from "zod";++const amount = z.number().finite().min(0).max(1_000_000);+const tokens = z.number().int().min(0).max(1_000_000_000_000);+const limitsSchema = z.object({+ dailyUsd: amount.optional(),+ monthlyUsd: amount.optional(),+ dailyTokens: tokens.optional(),+ monthlyTokens: tokens.optional(),+}).strict();++/** `config.json` → `usageCaps`. Every cap is optional and none is set by default; 0 or absent means no cap. Days and+ * months are UTC, as the usage ledger's are. Dollars are the ledger's estimate (notional on a subscription sign-in, 0+ * for a model with no price), so a token cap is the one that always counts. */+export const usageCapsSchema = z.object({+ /** What a reached cap stops: `unattended` (the default) stops routines, webhooks, app events, Bot API calls and+ * hand-offs nobody is waiting on, and a person's own message still runs; `everything` stops a person's messages too. */+ stops: z.enum(["unattended", "everything"]).optional(),+ /** Caps on everything this server's bots use together. */+ server: limitsSchema.optional(),+ /** Caps on one bot, by bot id. */+ bots: z.record(z.string().min(1).max(128), limitsSchema).optional(),+}).strict();++export type CapLimits = z.output<typeof limitsSchema>;+export type UsageCapsConfig = z.output<typeof usageCapsSchema>;diff --git a/server/usage-caps.e2e.test.ts b/server/usage-caps.e2e.test.tsnew file mode 100644index 0000000000..8098e3ecfc--- /dev/null+++ b/server/usage-caps.e2e.test.ts@@ -0,0 +1,187 @@+// Usage caps on a real server with the scripted engine, whose every turn books $0.01: a cap set through the owner's route+// lets the turn that reaches it finish, then refuses a Bot API call and a webhook, counts a routine's scheduled run on one+// skipped row, tells the owner once, still answers the owner's own message, and lets everything start again once raised.+import { randomUUID } from "node:crypto";+import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { afterEach, expect, it } from "vitest";++import { launchVerificationServer, runControlOmb, type VerificationServer } from "../scripts/control-omb.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++let fixture: VerificationServer | undefined;+afterEach(async () => {+ await fixture?.close();+ fixture = undefined;+});++const client = (url: string) => {+ const call = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(url + path, { method, headers: { "content-type": "application/json", origin: url }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ return { status: response.status, body: await response.json().catch(() => ({})) as any };+ };+ const ok = async (method: string, path: string, body?: unknown) => {+ const answer = await call(method, path, body);+ expect(answer.status, `${method} ${path}: ${JSON.stringify(answer.body)}`).toBeLessThan(300);+ return answer.body;+ };+ return { call, ok };+};+const outside = async (endpoint: string, key: string, message: string) => {+ const response = await fetch(endpoint, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json" }, body: JSON.stringify({ message }) });+ return { status: response.status, retryAfter: response.headers.get("retry-after"), body: await response.json() as any };+};+const newBot = async (url: string, name: string) => (await runControlOmb(["new-bot", "--name", name, "--url", url]) as { bot: { id: string; activeTaskId: string } }).bot;+const replies = async (ok: ReturnType<typeof client>["ok"], threadId: string) =>+ ((await ok("GET", `/api/threads/${threadId}/messages?limit=200`)).messages as any[]).filter((line) => line.role === "bot" && line.kind === "text").length;++it("stops unattended work at a reached cap with one line each and one notice, keeps the owner's own message running, and resumes when raised", async () => {+ fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_VERSION: "2.1.284" });+ const { url, logPath } = fixture.info;+ const { call, ok } = client(url);+ const scout = await newBot(url, "Scout");+ const other = await newBot(url, "Other");+ const api = await ok("POST", `/api/bots/${scout.id}/bot-api`, { enabled: true });+ const hook = await ok("POST", "/api/webhooks", { name: "New lead", prompt: "Handle the lead.", botId: scout.id });++ // Nothing is capped until the owner sets a cap.+ expect(await ok("GET", "/api/usage/caps")).toEqual({ stops: "unattended", savedStops: "unattended", server: {}, bots: {}, env: { stops: false, server: [], values: { server: {} } }, caps: [] });+ expect((await call("PUT", "/api/usage/caps", { server: { dailyUsd: -1 } })).status).toBe(400);+ expect((await call("PUT", "/api/usage/caps", { bots: { nobody: { dailyUsd: 1 } } })).status).toBe(404);+ const set = await ok("PUT", "/api/usage/caps", { bots: { [scout.id]: { dailyUsd: 0.01, monthlyTokens: 0 } } });+ expect(set).toMatchObject({ stops: "unattended", server: {}, bots: { [scout.id]: { dailyUsd: 0.01 } } });+ expect(set.caps).toEqual([expect.objectContaining({ id: `bot:${scout.id}:day:usd`, limit: 0.01, used: 0, reached: false })]);+ expect(JSON.parse(readFileSync(`${fixture.info.dataDir}/config.json`, "utf8")).usageCaps).toEqual({ stops: "unattended", server: {}, bots: { [scout.id]: { dailyUsd: 0.01 } } });++ // The call that reaches the cap is answered in full: nothing is cut off mid-turn.+ const first = await outside(api.url, api.key, "Hello");+ expect([first.status, first.body.reply]).toEqual([200, "hello from fake claude"]);+ await expect.poll(async () => (await ok("GET", "/api/usage/caps")).caps[0], { timeout: hostTimeout(20_000) }).toMatchObject({ used: 0.01, percent: 100, warn: true, reached: true });++ // A Bot API call and a webhook delivery each get a clear refusal, and each is listed where its owner looks.+ const refused = await outside(api.url, api.key, "Hello again");+ expect(refused.status).toBe(429);+ expect(refused.body.error).toMatch(/^This bot has reached a usage cap its owner set, so it takes no new calls for now\. Try again after \d{4}-/);+ expect(Number(refused.retryAfter)).toBeGreaterThan(0);+ expect((await ok("GET", `/api/bots/${scout.id}/bot-api`)).calls[0]).toMatchObject({ outcome: "rejected", statusCode: 429, reason: expect.stringContaining("Scout’s daily usage cap ($0.01) is reached") });+ const delivery = await fetch(hook.credential.url, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": "lead-1" }, body: JSON.stringify({ lead: "Ada" }) });+ expect(delivery.status).toBe(429);+ expect((await delivery.json() as any).error).toContain("Scout’s daily usage cap ($0.01) is reached");++ // A scheduled run is skipped and counted on one row; its routine stays on and nothing asks for attention.+ const { routine } = await ok("POST", "/api/routines", { name: "Hourly check", prompt: "Check.", botId: scout.id, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_000 } });+ await expect.poll(async () => (await ok("GET", "/api/routines")).runs.filter((run: any) => run.routineId === routine.id).map((run: any) => run.status), { timeout: hostTimeout(90_000), interval: 1_000 }).toEqual(["missed"]);+ const state = await ok("GET", "/api/routines");+ const skipped = state.runs.find((run: any) => run.routineId === routine.id);+ expect(skipped).toMatchObject({ skipped: { count: 1, behind: expect.stringMatching(new RegExp(`^cap:${routine.id}:bot:.+:day:usd:\\d{4}-\\d\\d-\\d\\d$`)) }, errorCode: "routines.server.capSkippedOne" });+ expect(skipped.error).toMatch(/^Skipped: this bot’s daily usage cap \(\$0\.01\) is reached\. Runs start again after /);+ expect(skipped.threadId).toBeUndefined();+ expect(state.routines.find((each: any) => each.id === routine.id)).toMatchObject({ enabled: true });+ expect(state.routines.find((each: any) => each.id === routine.id).nextRunAt).toBeGreaterThan(Date.now());++ // The owner's own message still runs, and so does a run they start by hand; another bot is not touched by this bot's cap.+ const before = await replies(ok, scout.activeTaskId);+ expect((await call("POST", `/api/bots/${scout.id}/messages`, { text: "Are you there?", threadId: scout.activeTaskId, sendId: randomUUID() })).status).toBeLessThan(300);+ await expect.poll(() => replies(ok, scout.activeTaskId), { timeout: hostTimeout(30_000) }).toBe(before + 1);+ const otherApi = await ok("POST", `/api/bots/${other.id}/bot-api`, { enabled: true });+ expect((await outside(otherApi.url, otherApi.key, "Hello")).status).toBe(200);++ // In a room too: the owner's line gets its answer from the capped bot.+ const room = (await ok("POST", "/api/groups", { name: "Desk", memberIds: [scout.id, other.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: scout.id } } })).group;+ expect((await call("POST", `/api/groups/${room.id}/messages`, { text: "Scout, are you there?" })).status).toBe(202);+ await runControlOmb(["wait", "--channel", room.id, "--timeout", "60", "--url", url]);+ const roomLines = (await ok("GET", `/api/threads/${room.threadId}/messages?limit=50`)).messages as any[];+ expect(roomLines.filter((line) => line.role === "bot" && line.kind === "text" && line.from?.botId === scout.id)).toHaveLength(1);+ expect(roomLines.filter((line) => /usage cap/.test(line.tool?.name ?? ""))).toEqual([]);++ // One notice for the cap, however many runs it skipped, and one line in the server log; no card anywhere.+ expect((await outside(api.url, api.key, "And again")).status).toBe(429);+ const notices = ((await ok("GET", "/api/notifications")).notifications as any[]).filter((notice) => notice.title === "Usage cap reached");+ expect(notices).toHaveLength(1);+ expect(notices[0].body).toContain("Scout’s daily usage cap ($0.01) is reached");+ expect(notices[0].body).toContain("Your own messages still run.");+ expect(readFileSync(logPath, "utf8").split("\n").filter((line) => line.startsWith("usage cap reached: "))).toHaveLength(1);+ const cards = ((await ok("GET", `/api/threads/${scout.activeTaskId}/messages?limit=200`)).messages as any[]).filter((line) => line.card);+ expect(cards).toEqual([]);++ // Under "everything" the owner's own message is refused too, in place.+ await ok("PUT", "/api/usage/caps", { stops: "everything", bots: { [scout.id]: { dailyUsd: 0.01 } } });+ const stopped = await call("POST", `/api/bots/${scout.id}/messages`, { text: "And now?", threadId: scout.activeTaskId, sendId: randomUUID() });+ expect([stopped.status, stopped.body.code]).toEqual([409, "spend_cap"]);+ expect(stopped.body.error).toContain("Scout’s daily usage cap ($0.01) is reached");++ expect((await call("POST", `/api/groups/${room.id}/messages`, { text: "And in here?" })).status).toBe(202);+ await runControlOmb(["wait", "--channel", room.id, "--timeout", "60", "--url", url]);+ const refusedInRoom = ((await ok("GET", `/api/threads/${room.threadId}/messages?limit=50`)).messages as any[]).filter((line) => /usage cap/.test(line.tool?.name ?? ""));+ expect(refusedInRoom).toHaveLength(1);+ expect(refusedInRoom[0].tool.name).toContain("Scout’s daily usage cap ($0.01) is reached");++ // Raising the cap is all it takes: the next call is answered.+ await ok("PUT", "/api/usage/caps", { bots: { [scout.id]: { dailyUsd: 5 } } });+ const resumed = await outside(api.url, api.key, "Back?");+ expect([resumed.status, resumed.body.reply]).toEqual([200, "hello from fake claude"]);++ // The Usage page's own data carries the caps for the owner, and how much of the period is unpriced or not billed.+ const today = new Date().toISOString().slice(0, 10);+ const usage = await ok("GET", `/api/usage?from=${today}&to=${today}&groupBy=bot`);+ expect(usage.caps.caps).toEqual([expect.objectContaining({ id: `bot:${scout.id}:day:usd`, limit: 5, reached: false })]);+ expect(usage.total).toMatchObject({ unpriced: 0 });+ expect(usage.notBilled).toEqual({ usd: expect.any(Number), turns: expect.any(Number) });+}, hostTimeout(300_000));++it("takes a headless server's caps from the environment, and they win over the saved ones", async () => {+ fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_VERSION: "2.1.284", OMB_USAGE_CAP_DAILY_TOKENS: "1", OMB_USAGE_CAP_STOPS: "unattended" });+ const { url } = fixture.info;+ const { ok } = client(url);+ const scout = await newBot(url, "Scout");+ const api = await ok("POST", `/api/bots/${scout.id}/bot-api`, { enabled: true });+ expect(await ok("PUT", "/api/usage/caps", { stops: "everything", server: { dailyTokens: 1_000_000_000 } }))+ .toMatchObject({ stops: "unattended", server: { dailyTokens: 1_000_000_000 }, env: { stops: true, server: ["dailyTokens"] }, caps: [expect.objectContaining({ id: "server:day:tokens", limit: 1 })] });+ expect((await outside(api.url, api.key, "Hello")).status).toBe(200);+ await expect.poll(async () => (await ok("GET", "/api/usage/caps")).caps[0].reached, { timeout: hostTimeout(20_000) }).toBe(true);+ const refused = await outside(api.url, api.key, "Hello again");+ expect(refused.status).toBe(429);+ expect((await ok("GET", `/api/bots/${scout.id}/bot-api`)).calls[0].reason).toContain("the daily usage cap for all bots (1 tokens) is reached");+}, hostTimeout(180_000));++it("lets a run that already started carry on when its hand-off comes back after the cap is reached, and the owner's webhook test run", async () => {+ fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_VERSION: "2.1.284" }, undefined, undefined, undefined, undefined, { scripted: true });+ const { url, dataDir } = fixture.info;+ const { ok } = client(url);+ const pepper = await newBot(url, "Pepper");+ const sam = await newBot(url, "Sam");+ const samGate = join(dataDir, "sam-counts");+ writeFileSync(join(dataDir, "room-plan.json"), JSON.stringify({+ [pepper.id]: { script: [+ { key: "run", match: ["Do the stock check."], steps: [{ tool: "coordinate_bots", arguments: { bot_ids: [sam.id], message: "Count the boxes in stock." } }], reply: "Asked Sam to count the stock." },+ { key: "resume", match: ["42 boxes"], reply: "We have 42 boxes in stock." },+ { key: "test", match: ["Do the stock check."], reply: "Test run done." },+ ] },+ [sam.id]: { script: [{ key: "count", match: ["Count the boxes in stock."], reply: "Counted 42 boxes.", gateFile: samGate }] },+ }));+ // Pepper's cap is reached by the first turn of the webhook's run: the run's hand-off is under way by then.+ await ok("PUT", "/api/usage/caps", { bots: { [pepper.id]: { dailyTokens: 1 } } });+ const hook = await ok("POST", "/api/webhooks", { name: "Stock", prompt: "Do the stock check.", botId: pepper.id });+ const delivery = await fetch(hook.credential.url, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": "stock-1" }, body: JSON.stringify({ shelf: "A" }) });+ expect(delivery.status).toBeLessThan(300);+ const run = async () => ((await ok("GET", "/api/routines")).runs as any[]).find((each) => each.webhookId === hook.webhook.id);+ await expect.poll(async () => (await run())?.status, { timeout: hostTimeout(60_000), interval: 500 }).toBe("waiting");+ await expect.poll(async () => (await ok("GET", "/api/usage/caps")).caps[0]?.reached, { timeout: hostTimeout(20_000) }).toBe(true);++ // Sam answers; Pepper's run picks the result up and finishes, though new work for Pepper is refused now.+ writeFileSync(samGate, "done");+ await expect.poll(async () => (await run())?.status, { timeout: hostTimeout(60_000), interval: 500 }).toBe("completed");+ const { threadId } = await run();+ const lines = ((await ok("GET", `/api/threads/${threadId}/messages?limit=200`)).messages as any[]);+ expect(lines.filter((line) => line.role === "bot" && line.kind === "text").map((line) => line.text)).toContain("We have 42 boxes in stock.");+ expect(lines.filter((line) => /usage cap/.test(`${line.tool?.name ?? ""} ${line.text ?? ""}`))).toEqual([]);+ const again = await fetch(hook.credential.url, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": "stock-2" }, body: JSON.stringify({ shelf: "B" }) });+ expect(again.status).toBe(429);++ // The owner's own Run now of the webhook is theirs, as a routine started by hand is: it runs under the cap.+ const test = await ok("POST", `/api/webhooks/${hook.webhook.id}/test`, { shelf: "C" });+ const tested = async () => ((await ok("GET", "/api/routines")).runs as any[]).find((each) => each.id === test.runId);+ await expect.poll(async () => (await tested())?.status, { timeout: hostTimeout(60_000), interval: 500 }).toBe("completed");+ const testLines = ((await ok("GET", `/api/threads/${(await tested()).threadId}/messages?limit=200`)).messages as any[]);+ expect(testLines.filter((line) => line.role === "bot" && line.kind === "text").map((line) => line.text)).toContain("Test run done.");+}, hostTimeout(240_000));diff --git a/server/usage-caps.test.ts b/server/usage-caps.test.tsnew file mode 100644index 0000000000..9d2ac36950--- /dev/null+++ b/server/usage-caps.test.ts@@ -0,0 +1,166 @@+import { appendFileSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { removeTempDir } from "./testing/cleanup.ts";+import { capsFromEnv, capStates, capTokens, effectiveCaps, noteUsage, periodEnd, personWaiting, personWaitingInRoom, reachedCap, resetUsageTotalsForTests, usageCapsSchema, usageTotals, type ThreadStanding } from "./usage-caps.ts";+import { appendUsage, flushUsageLedger, usageFileFor } from "./usage-ledger.ts";++const NO_ENV = {};+const row = (at: string, botId: string, costUsd: number | null, input = 1_000, output = 500, cachedInput?: number) => ({+ at, botId, botName: botId, threadId: `t-${botId}`, instanceId: "claude", driverKind: "claudeAgent", model: "m",+ input, output, ...(cachedInput === undefined ? {} : { cachedInput }), costUsd, trigger: { kind: "owner" as const },+});++describe("what has been used", () => {+ let dataDir: string;+ const now = new Date("2026-09-15T12:00:00Z");+ beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), "omb-caps-")); resetUsageTotalsForTests(); });+ afterEach(async () => { await removeTempDir(dataDir); });++ it("adds up the UTC day and month for the server and for each bot, in dollars and in fresh tokens", async () => {+ appendUsage(dataDir, row("2026-08-31T23:59:59.000Z", "a", 9));+ appendUsage(dataDir, row("2026-09-01T00:00:00.000Z", "a", 1));+ appendUsage(dataDir, row("2026-09-14T23:59:59.000Z", "b", 2, 4_000, 1_000, 3_000));+ appendUsage(dataDir, row("2026-09-15T00:00:00.000Z", "a", 0.5));+ // A model with no price books $0 and still counts its tokens.+ appendUsage(dataDir, row("2026-09-15T08:00:00.000Z", "b", null, 10_000, 2_000));+ await flushUsageLedger(dataDir);+ const totals = usageTotals(dataDir, now);+ expect(totals.server.month).toEqual({ usd: 3.5, tokens: 1_500 + 2_000 + 1_500 + 12_000 });+ expect(totals.server.day).toEqual({ usd: 0.5, tokens: 13_500 });+ expect(totals.bots.get("a")).toEqual({ month: { usd: 1.5, tokens: 3_000 }, day: { usd: 0.5, tokens: 1_500 } });+ expect(totals.bots.get("b")).toEqual({ month: { usd: 2, tokens: 14_000 }, day: { usd: 0, tokens: 12_000 } });+ expect(capTokens({ input: 100, output: 7, cachedInput: 400 })).toBe(7);+ });++ it("counts a turn that was just booked before its row reaches the file, and starts from zero when the period rolls over", async () => {+ expect(usageTotals(dataDir, now).server.day).toEqual({ usd: 0, tokens: 0 });+ const booked = row("2026-09-15T11:59:00.000Z", "a", 0.25);+ noteUsage(dataDir, booked, appendUsage(dataDir, booked));+ expect(usageTotals(dataDir, now).server.day).toEqual({ usd: 0.25, tokens: 1_500 });+ await flushUsageLedger(dataDir);+ await Promise.resolve();+ expect(usageTotals(dataDir, now).server.day).toEqual({ usd: 0.25, tokens: 1_500 });+ const tomorrow = usageTotals(dataDir, new Date("2026-09-16T00:00:01Z"));+ expect([tomorrow.server.day, tomorrow.server.month.usd]).toEqual([{ usd: 0, tokens: 0 }, 0.25]);+ expect(usageTotals(dataDir, new Date("2026-10-01T00:00:01Z")).server.month).toEqual({ usd: 0, tokens: 0 });+ expect([periodEnd("day", now), periodEnd("month", now)]).toEqual([Date.parse("2026-09-16T00:00:00Z"), Date.parse("2026-10-01T00:00:00Z")]);+ expect(periodEnd("month", new Date("2026-12-31T23:00:00Z"))).toBe(Date.parse("2027-01-01T00:00:00Z"));+ });++ it("reads only what was appended since the last look, counts a landed row once, and reads a rewritten file again", async () => {+ const at = (seconds: number) => new Date(now.getTime() + seconds * 1_000);+ appendUsage(dataDir, row("2026-09-15T08:00:00.000Z", "a", 1));+ await flushUsageLedger(dataDir);+ expect(usageTotals(dataDir, now).server.day.usd).toBe(1);+ // Booked here: counted from memory while it is written and once it has landed, and not again when the file is read past it.+ const booked = row("2026-09-15T11:59:00.000Z", "a", 0.5);+ noteUsage(dataDir, booked, appendUsage(dataDir, booked));+ await flushUsageLedger(dataDir);+ await Promise.resolve();+ expect(usageTotals(dataDir, at(1)).server.day.usd).toBe(1.5);+ // Written by something else: seen at the next look after the cache window, from the appended bytes alone.+ appendUsage(dataDir, row("2026-09-15T11:59:30.000Z", "b", 2));+ await flushUsageLedger(dataDir);+ expect(usageTotals(dataDir, at(16)).server.day.usd).toBe(3.5);+ expect(usageTotals(dataDir, at(32)).bots.get("b")!.day.usd).toBe(2);+ // A line still being written is left for the next look.+ appendFileSync(usageFileFor(dataDir, now), JSON.stringify(row("2026-09-15T11:59:40.000Z", "b", 4)).slice(0, 20));+ expect(usageTotals(dataDir, at(48)).server.day.usd).toBe(3.5);+ // The file was rewritten shorter (a restore): it is read from the start.+ writeFileSync(usageFileFor(dataDir, now), JSON.stringify(row("2026-09-15T09:00:00.000Z", "a", 0.25)) + "\n");+ expect(usageTotals(dataDir, at(64)).server).toEqual({ day: { usd: 0.25, tokens: 1_500 }, month: { usd: 0.25, tokens: 1_500 } });+ });++ it("sets no cap at all until one is asked for, and reads 0 as no cap", () => {+ expect(capStates(undefined, dataDir, now, NO_ENV)).toEqual([]);+ expect(capStates({ server: { dailyUsd: 0 }, bots: { a: {} } }, dataDir, now, NO_ENV)).toEqual([]);+ expect(reachedCap(undefined, dataDir, { botId: "a", personWaiting: false }, now, NO_ENV)).toBeNull();+ });++ it("measures each cap, warns from 80%, and names the reached cap that resets last", async () => {+ appendUsage(dataDir, row("2026-09-15T08:00:00.000Z", "a", 4, 8_000, 0));+ appendUsage(dataDir, row("2026-09-15T09:00:00.000Z", "b", 1, 1_000, 0));+ await flushUsageLedger(dataDir);+ const caps = { server: { dailyUsd: 5, monthlyUsd: 5, dailyTokens: 100_000 }, bots: { a: { dailyTokens: 10_000 }, b: { monthlyUsd: 2 } } };+ const states = capStates(caps, dataDir, now, NO_ENV);+ expect(states.map((state) => [state.id, state.used, state.percent, state.warn, state.reached])).toEqual([+ ["server:day:usd", 5, 100, true, true],+ ["server:month:usd", 5, 100, true, true],+ ["server:day:tokens", 9_000, 9, false, false],+ ["bot:a:day:tokens", 8_000, 80, true, false],+ ["bot:b:month:usd", 1, 50, false, false],+ ]);+ expect(reachedCap(caps, dataDir, { botId: "a", personWaiting: false }, now, NO_ENV)).toMatchObject({ id: "server:month:usd", periodKey: "2026-09", resetsAt: Date.parse("2026-10-01T00:00:00Z") });+ // Another bot's cap never stops this bot; a bot's own cap stops only that bot.+ expect(reachedCap({ bots: { a: { dailyTokens: 8_000 } } }, dataDir, { botId: "b", personWaiting: false }, now, NO_ENV)).toBeNull();+ expect(reachedCap({ bots: { a: { dailyTokens: 8_000 } } }, dataDir, { botId: "a", personWaiting: false }, now, NO_ENV)).toMatchObject({ id: "bot:a:day:tokens", periodKey: "2026-09-15" });+ });++ it("stops a person's own message only when the owner chose everything", async () => {+ appendUsage(dataDir, row("2026-09-15T08:00:00.000Z", "a", 4));+ await flushUsageLedger(dataDir);+ const caps = { server: { dailyUsd: 1 } };+ expect(reachedCap(caps, dataDir, { botId: "a", personWaiting: true }, now, NO_ENV)).toBeNull();+ expect(reachedCap({ ...caps, stops: "unattended" }, dataDir, { botId: "a", personWaiting: true }, now, NO_ENV)).toBeNull();+ expect(reachedCap(caps, dataDir, { botId: "a", personWaiting: false }, now, NO_ENV)).toMatchObject({ id: "server:day:usd" });+ expect(reachedCap({ ...caps, stops: "everything" }, dataDir, { botId: "a", personWaiting: true }, now, NO_ENV)).toMatchObject({ id: "server:day:usd" });+ // The cap is raised: the work starts again without anything else being done.+ expect(reachedCap({ server: { dailyUsd: 10 } }, dataDir, { botId: "a", personWaiting: false }, now, NO_ENV)).toBeNull();+ });+});++describe("caps from the environment", () => {+ it("reads the server's caps and what they stop, ignores what is not a number, and wins over config.json", () => {+ const env = { OMB_USAGE_CAP_DAILY_USD: "5", OMB_USAGE_CAP_MONTHLY_TOKENS: "2000000", OMB_USAGE_CAP_DAILY_TOKENS: "1.5", OMB_USAGE_CAP_MONTHLY_USD: "lots", OMB_USAGE_CAP_STOPS: "Everything" };+ expect(capsFromEnv(env)).toEqual({ stops: "everything", server: { dailyUsd: 5, monthlyTokens: 2_000_000 } });+ expect(capsFromEnv({})).toEqual({ server: {} });+ expect(effectiveCaps({ stops: "unattended", server: { dailyUsd: 1, monthlyUsd: 30 }, bots: { a: { dailyUsd: 2 } } }, env))+ .toEqual({ stops: "everything", server: { dailyUsd: 5, monthlyUsd: 30, monthlyTokens: 2_000_000 }, bots: { a: { dailyUsd: 2 } } });+ expect(effectiveCaps(undefined, {})).toEqual({ stops: "unattended", server: {}, bots: {} });+ });++ it("accepts only the documented shape in config.json", () => {+ expect(usageCapsSchema.safeParse({ stops: "everything", server: { dailyUsd: 2.5, monthlyTokens: 1_000 }, bots: { b1: { dailyTokens: 5 } } }).success).toBe(true);+ for (const bad of [{ stops: "nothing" }, { server: { dailyUsd: -1 } }, { server: { dailyTokens: 1.5 } }, { server: { weeklyUsd: 1 } }, { bots: { b1: { dailyUsd: "5" } } }]) {+ expect(usageCapsSchema.safeParse(bad).success, JSON.stringify(bad)).toBe(false);+ }+ });+});++describe("whether a person is waiting on a turn", () => {+ const quiet: ThreadStanding = { unattended: false, automation: undefined, origin: "user" };+ it("always counts a person's own message, even in a conversation an automation used last", () => {+ expect(personWaiting({}, quiet)).toBe(true);+ expect(personWaiting({}, { unattended: true, automation: "webhook", origin: "outside" })).toBe(true);+ });+ it("never counts a routine, webhook, app event or Bot API call, and counts a run started by hand", () => {+ for (const automationSource of ["schedule", "startup", "webhook", "api", "app"]) expect(personWaiting({ automationSource }, quiet), automationSource).toBe(false);+ expect(personWaiting({ automationSource: "manual" }, quiet)).toBe(true);+ });+ it("counts a hand-off by where its work started", () => {+ expect(personWaiting({ commsDepth: 1, origin: { kind: "user" } }, quiet)).toBe(true);+ expect(personWaiting({ commsDepth: 1, origin: { kind: "outside" } }, quiet)).toBe(false);+ expect(personWaiting({ coordination: { id: "n" } }, { ...quiet, origin: "outside" })).toBe(false);+ expect(personWaiting({ coordination: { id: "n" } }, quiet)).toBe(true);+ expect(personWaiting({ commsDepth: 1, origin: { kind: "user" }, unattended: true }, quiet)).toBe(false);+ expect(personWaiting({ peerAsk: { unattended: true }, origin: { kind: "user" } }, quiet)).toBe(false);+ });+ it("counts a continuation by the conversation it continues", () => {+ expect(personWaiting({ cardContinuation: true }, quiet)).toBe(true);+ expect(personWaiting({ cardContinuation: true }, { ...quiet, automation: "schedule" })).toBe(false);+ expect(personWaiting({ cardContinuation: true }, { ...quiet, automation: "manual" })).toBe(true);+ expect(personWaiting({ cardContinuation: true }, { ...quiet, unattended: true })).toBe(false);+ expect(personWaiting({ unattended: true }, quiet)).toBe(false);+ });+ it("counts a room turn unless something other than a person started its run, or it is a routine's own run", () => {+ expect(personWaitingInRoom({ personStarted: true }, undefined)).toBe(true);+ expect(personWaitingInRoom(undefined, undefined)).toBe(true);+ expect(personWaitingInRoom({ personStarted: false }, undefined)).toBe(false);+ expect(personWaitingInRoom({ personStarted: true }, "schedule")).toBe(false);+ expect(personWaitingInRoom({ personStarted: true }, "webhook")).toBe(false);+ expect(personWaitingInRoom({ personStarted: true }, "manual")).toBe(true);+ });+});diff --git a/server/usage-caps.ts b/server/usage-caps.tsnew file mode 100644index 0000000000..5edc6811da--- /dev/null+++ b/server/usage-caps.ts@@ -0,0 +1,287 @@+// The cap engine over the usage ledger: what has been used this UTC day and month, by the server and by each bot, in+// estimated dollars and in tokens, and which caps that use has reached. The open caps (`usageCaps`) and the licensed+// monthly budget (spend.ts) both read their totals here.+import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs";++import { directTurnKind } from "./agents-turn.ts";+import { isUsageRow, usageFileFor, usageRowKey, type UsageRow } from "./usage-ledger.ts";+import type { CapLimits, UsageCapsConfig } from "./usage-caps-config.ts";++export { usageCapsSchema, type CapLimits, type UsageCapsConfig } from "./usage-caps-config.ts";++export const CAP_WARN_PERCENT = 80;+const CACHE_MS = 15_000;+const DAY_MS = 24 * 60 * 60_000;++export type CapPeriod = "day" | "month";+export type CapUnit = "usd" | "tokens";+export type CapStops = "unattended" | "everything";++export const CAP_FIELDS = [+ { field: "dailyUsd", period: "day", unit: "usd", env: "OMB_USAGE_CAP_DAILY_USD" },+ { field: "monthlyUsd", period: "month", unit: "usd", env: "OMB_USAGE_CAP_MONTHLY_USD" },+ { field: "dailyTokens", period: "day", unit: "tokens", env: "OMB_USAGE_CAP_DAILY_TOKENS" },+ { field: "monthlyTokens", period: "month", unit: "tokens", env: "OMB_USAGE_CAP_MONTHLY_TOKENS" },+] as const satisfies ReadonlyArray<{ field: keyof CapLimits; period: CapPeriod; unit: CapUnit; env: string }>;+export const CAP_STOPS_ENV = "OMB_USAGE_CAP_STOPS";++export interface Used { usd: number; tokens: number }+export interface UsageTotals {+ month: string;+ day: string;+ server: Record<CapPeriod, Used>;+ bots: Map<string, Record<CapPeriod, Used>>;+}++type Entry = { at: string; botId: string; usd: number; tokens: number };+type Sums = { server: Record<CapPeriod, Used>; bots: Map<string, Record<CapPeriod, Used>> };+/** One month file as far as it was read: running sums for its month and for `day`, and how many bytes they cover. The+ * ledger only grows by whole lines, so a later look reads just what was appended, and only when the file changed. */+type Read = {+ at: number; day: string; month: string; size: number; mtimeMs: number; sums: Sums;+ /** Every row counted, by ledger key. */+ keys: Set<string>;+ /** Rows counted from memory when their append landed, which the file has not yet been read past. */+ fromMemory: Set<string>;+};+const cache = new Map<string, Read>();+// Rows whose async ledger append may not have landed yet: a long turn would otherwise re-read the month without its own row.+const unwritten = new Map<string, Map<string, Entry>>();++const positive = (value: unknown): number => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0);++/** The tokens a cap counts: fresh input plus output, the same sum the Usage page's bars show. */+export function capTokens(row: Pick<UsageRow, "input" | "output" | "cachedInput">): number {+ const input = positive(row.input);+ return Math.max(0, input - Math.min(positive(row.cachedInput), input)) + positive(row.output);+}++const entryOf = (row: Pick<UsageRow, "at" | "botId" | "costUsd" | "input" | "output" | "cachedInput">): Entry =>+ ({ at: row.at, botId: row.botId, usd: positive(row.costUsd), tokens: capTokens(row) });++export const dayKey = (now: Date): string => now.toISOString().slice(0, 10);+export const monthKeyOf = (now: Date): string => now.toISOString().slice(0, 7);++/** When the period that holds `now` rolls over, in UTC. */+export function periodEnd(period: CapPeriod, now: Date): number {+ return period === "day"+ ? Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) + DAY_MS+ : Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);+}++const zero = (): Record<CapPeriod, Used> => ({ day: { usd: 0, tokens: 0 }, month: { usd: 0, tokens: 0 } });++function addTo(sums: Sums, entry: Entry, month: string, day: string): void {+ if (!entry.at.startsWith(month)) return;+ const bot = sums.bots.get(entry.botId) ?? zero();+ sums.bots.set(entry.botId, bot);+ for (const used of entry.at.startsWith(day) ? [sums.server.month, bot.month, sums.server.day, bot.day] : [sums.server.month, bot.month]) {+ used.usd += entry.usd;+ used.tokens += entry.tokens;+ }+}++/** Counts the whole lines of `bytes`; returns how many bytes they span (a line still being written is left for later). */+function countLines(read: Read, bytes: Buffer): number {+ const end = bytes.lastIndexOf(10) + 1;+ for (const line of bytes.subarray(0, end).toString("utf8").split("\n")) {+ if (!line) continue;+ let value: unknown;+ try { value = JSON.parse(line); } catch { continue; }+ if (!isUsageRow(value)) continue;+ const key = usageRowKey(value);+ if (read.fromMemory.delete(key)) continue;+ read.keys.add(key);+ addTo(read.sums, entryOf(value), read.month, read.day);+ }+ return end;+}++function statOf(file: string): { size: number; mtimeMs: number } {+ try {+ const { size, mtimeMs } = statSync(file);+ return { size, mtimeMs };+ } catch {+ return { size: 0, mtimeMs: 0 };+ }+}++/** Reads the month file from the start. */+function readMonth(dataDir: string, now: Date): Read {+ const read: Read = { at: now.getTime(), day: dayKey(now), month: monthKeyOf(now), size: 0, mtimeMs: 0, sums: { server: zero(), bots: new Map() }, keys: new Set(), fromMemory: new Set() };+ const file = usageFileFor(dataDir, now);+ let bytes: Buffer;+ try { bytes = readFileSync(file); } catch { return read; }+ read.mtimeMs = statOf(file).mtimeMs;+ read.size = countLines(read, bytes);+ return read;+}++/** Brings a read up to date: nothing when the file is as it was, the appended bytes when it grew, all of it otherwise. */+function refresh(dataDir: string, read: Read, now: Date): Read {+ const file = usageFileFor(dataDir, now);+ const { size, mtimeMs } = statOf(file);+ read.at = now.getTime();+ if (size === read.size && mtimeMs === read.mtimeMs) return read;+ if (size < read.size) return readMonth(dataDir, now);+ let fd: number | undefined;+ try {+ fd = openSync(file, "r");+ const bytes = Buffer.alloc(size - read.size);+ const got = readSync(fd, bytes, 0, bytes.length, read.size);+ read.size += countLines(read, bytes.subarray(0, got));+ read.mtimeMs = mtimeMs;+ return read;+ } catch {+ return readMonth(dataDir, now);+ } finally {+ if (fd !== undefined) try { closeSync(fd); } catch { /* already closed */ }+ }+}++export function usageTotals(dataDir: string, now = new Date()): UsageTotals {+ const month = monthKeyOf(now), day = dayKey(now);+ let read = cache.get(dataDir);+ if (!read || read.day !== day) read = readMonth(dataDir, now);+ else if (now.getTime() - read.at >= CACHE_MS) read = refresh(dataDir, read, now);+ cache.set(dataDir, read);+ const totals: UsageTotals = {+ month, day, server: { day: { ...read.sums.server.day }, month: { ...read.sums.server.month } },+ bots: new Map([...read.sums.bots].map(([botId, used]) => [botId, { day: { ...used.day }, month: { ...used.month } }])),+ };+ for (const [key, entry] of unwritten.get(dataDir) ?? []) if (!read.keys.has(key)) addTo(totals, entry, month, day);+ return totals;+}++/** Counts a booked row from memory until its append lands, so the next cap check already sees it. */+export function noteUsage(dataDir: string, row: Pick<UsageRow, "at" | "threadId" | "botId" | "costUsd" | "input" | "output" | "cachedInput">, written: Promise<boolean>): void {+ const entry = entryOf(row);+ if (!entry.usd && !entry.tokens) return;+ const key = usageRowKey(row);+ const entries = unwritten.get(dataDir) ?? new Map<string, Entry>();+ unwritten.set(dataDir, entries);+ entries.set(key, entry);+ void written.then((landed) => {+ entries.delete(key);+ if (entries.size === 0 && unwritten.get(dataDir) === entries) unwritten.delete(dataDir);+ const read = cache.get(dataDir);+ if (landed && read && !read.keys.has(key) && entry.at.startsWith(read.month)) {+ read.keys.add(key);+ read.fromMemory.add(key);+ addTo(read.sums, entry, read.month, read.day);+ }+ });+}++export function resetUsageTotalsForTests(): void {+ cache.clear();+ unwritten.clear();+}++/** One limit measured against its use: the arithmetic every cap shares. */+export function measure(limit: number, used: number, warnAtPercent = CAP_WARN_PERCENT): { percent: number; warn: boolean; reached: boolean } {+ const percent = Math.min(999, Math.round((used / limit) * 100));+ return { percent, warn: percent >= warnAtPercent, reached: used >= limit };+}++export interface CapState {+ /** `server:day:usd`, or `bot:<id>:month:tokens`: stable for one cap, whatever its limit. */+ id: string;+ scope: "server" | "bot";+ botId?: string;+ period: CapPeriod;+ unit: CapUnit;+ limit: number;+ used: number;+ percent: number;+ warn: boolean;+ reached: boolean;+ /** The UTC day or month the use was counted in. */+ periodKey: string;+ /** When that period rolls over and the cap counts from zero again. */+ resetsAt: number;+}++function numberFrom(raw: string | undefined, whole: boolean): number | undefined {+ if (raw === undefined || raw.trim() === "") return undefined;+ const value = Number(raw);+ return Number.isFinite(value) && value >= 0 && (!whole || Number.isInteger(value)) ? value : undefined;+}++/** A headless server's caps: `OMB_USAGE_CAP_DAILY_USD`, `…_MONTHLY_USD`, `…_DAILY_TOKENS`, `…_MONTHLY_TOKENS` set the+ * server's caps and `OMB_USAGE_CAP_STOPS` what they stop. A value that is not a number is ignored. */+export function capsFromEnv(env: NodeJS.ProcessEnv = process.env): { stops?: CapStops; server: CapLimits } {+ const server: CapLimits = {};+ for (const { field, unit, env: name } of CAP_FIELDS) {+ const value = numberFrom(env[name], unit === "tokens");+ if (value !== undefined) server[field] = value;+ }+ const stops = env[CAP_STOPS_ENV]?.trim().toLowerCase();+ return { ...(stops === "unattended" || stops === "everything" ? { stops } : {}), server };+}++/** The caps in force: what the environment sets wins over `config.json`, field by field. */+export function effectiveCaps(saved: UsageCapsConfig | undefined, env: NodeJS.ProcessEnv = process.env): { stops: CapStops; server: CapLimits; bots: Record<string, CapLimits> } {+ const fromEnv = capsFromEnv(env);+ return { stops: fromEnv.stops ?? saved?.stops ?? "unattended", server: { ...saved?.server, ...fromEnv.server }, bots: saved?.bots ?? {} };+}++function statesOf(scope: "server" | "bot", botId: string | undefined, limits: CapLimits | undefined, used: Record<CapPeriod, Used> | undefined, now: Date): CapState[] {+ const states: CapState[] = [];+ for (const { field, period, unit } of CAP_FIELDS) {+ const limit = limits?.[field];+ if (typeof limit !== "number" || !Number.isFinite(limit) || limit <= 0) continue;+ const spent = used?.[period][unit] ?? 0;+ states.push({+ id: `${scope === "bot" ? `bot:${botId}` : "server"}:${period}:${unit}`, scope, ...(botId ? { botId } : {}), period, unit, limit, used: spent,+ ...measure(limit, spent), periodKey: period === "day" ? dayKey(now) : monthKeyOf(now), resetsAt: periodEnd(period, now),+ });+ }+ return states;+}++/** Every cap that is set, with its use now. `botId` narrows it to the caps that count that bot's work. */+export function capStates(saved: UsageCapsConfig | undefined, dataDir: string, now = new Date(), env: NodeJS.ProcessEnv = process.env, botId?: string): CapState[] {+ const caps = effectiveCaps(saved, env);+ const bots = Object.entries(caps.bots).filter(([id]) => botId === undefined || id === botId);+ if (!bots.length && !CAP_FIELDS.some(({ field }) => (caps.server[field] ?? 0) > 0)) return [];+ const totals = usageTotals(dataDir, now);+ return [...statesOf("server", undefined, caps.server, totals.server, now), ...bots.flatMap(([id, limits]) => statesOf("bot", id, limits, totals.bots.get(id), now))];+}++/** The reached cap that keeps this work from starting, or null. A person's own message is stopped only by `everything`.+ * Of several reached caps, the one that resets last: the work cannot start before it does. */+export function reachedCap(saved: UsageCapsConfig | undefined, dataDir: string, work: { botId?: string; personWaiting: boolean }, now = new Date(), env: NodeJS.ProcessEnv = process.env): CapState | null {+ if (work.personWaiting && effectiveCaps(saved, env).stops !== "everything") return null;+ const reached = capStates(saved, dataDir, now, env, work.botId ?? "").filter((state) => state.reached);+ return reached.sort((a, b) => b.resetsAt - a.resetsAt)[0] ?? null;+}++/** What the harness already knows of the conversation a turn runs in. */+export interface ThreadStanding {+ /** Marked unattended by the turn that last ran there. */+ unattended: boolean;+ /** The trigger of the request the conversation is working on, when a routine, webhook, app event or API call started it. */+ automation: string | undefined;+ /** Whether that request traces to a person's own typed line. */+ origin: "user" | "outside" | undefined;+}++/** Whether a person is waiting on this turn. Their own message always is. A run started by hand is; a routine, webhook,+ * app event or Bot API call is not. A hand-off counts as theirs when it traces to a person's own typed line, and a+ * continuation when the conversation it continues is not an automation's. */+export function personWaiting(turn: Parameters<typeof directTurnKind>[0] & { origin?: { kind: "user" | "outside" } }, thread: ThreadStanding): boolean {+ const kind = directTurnKind(turn);+ if (kind === "person") return true;+ if (kind === "routine") return turn.automationSource === "manual";+ if (kind === "webhook" || kind === "api") return false;+ if (turn.unattended || (turn.peerAsk as { unattended?: boolean } | undefined)?.unattended || thread.unattended) return false;+ if (kind === "handoff") return (turn.origin?.kind ?? thread.origin) === "user";+ return thread.automation === undefined || thread.automation === "manual";+}++/** A room turn: a person is waiting unless the run is known to have been started by something else (a webhook's or+ * the API's line, work handed on from outside), or it is a routine's own run that nobody started by hand. */+export function personWaitingInRoom(run: { personStarted?: boolean } | undefined, routineTrigger: string | undefined): boolean {+ return run?.personStarted !== false && (routineTrigger === undefined || routineTrigger === "manual");+}diff --git a/server/webhooks.test.ts b/server/webhooks.test.tsindex d5ffcc52fe..4291cf9c1a 100644--- a/server/webhooks.test.ts+++ b/server/webhooks.test.ts@@ -671,10 +671,15 @@ describe("WebhookManager", () => {describe("turning a webhook back on, Run now, and a deleted bot's webhooks", () => {it("turns a paused webhook back on, and Run now works while it is paused, like a schedule's", () => {const h = harness();- const { webhook } = create(h.manager);+ const { webhook, secret } = create(h.manager);expect(h.manager.update(webhook.id, { enabled: false, verificationPending: false })).toMatchObject({ enabled: false });expect(h.manager.test(webhook.id)).toMatchObject({ runId: "run-1", duplicate: false });+ // The person's own test: a usage cap lets it run as it lets a routine started by hand; an outside delivery is not.+ expect(h.queued.at(-1)).toMatchObject({ byPerson: true });expect(h.manager.update(webhook.id, { enabled: true, verificationPending: false })).toMatchObject({ enabled: true });+ h.manager.receive(webhook.endpointId, secret, { payload: { lead: "Ada" }, deliveryId: "outside-1" });+ expect(h.queued).toHaveLength(2);+ expect(h.queued.at(-1)?.byPerson).toBeUndefined();});it("removes a deleted bot's webhooks for good, with their calls, and cancels their queued work", () => {diff --git a/server/webhooks.ts b/server/webhooks.tsindex 3910d1e3b8..e59919735a 100644--- a/server/webhooks.ts+++ b/server/webhooks.ts@@ -70,6 +70,8 @@ export interface WebhookManagerOptions {deliveryId: string;receivedAt: number;sameConversation?: boolean;+ /** The person's own Run now test, not an outside delivery. */+ byPerson?: boolean;}) => { id: string };cancelQueued?: (webhookId: string, message: string) => void;pendingRuns?: (webhookId: string) => number;@@ -826,6 +828,7 @@ export class WebhookManager {deliveryId,receivedAt: now,sameConversation: trigger.sameConversation,+ ...(byPerson ? { byPerson: true } : {}),});this.deliveries.push({ key: `${trigger.endpointId}:${deliveryId}`, runId: run.id, at: now });if (this.deliveries.length > MAX_DELIVERIES) {diff --git a/src/components/UsageCaps.test.ts b/src/components/UsageCaps.test.tsnew file mode 100644index 0000000000..fb5908bdb8--- /dev/null+++ b/src/components/UsageCaps.test.ts@@ -0,0 +1,100 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vitest";+import { CostCaveats } from "./UsageSection";+import { capsToSave, capTone, limitsOf, UsageCapsCard, type CapState, type UsageCapView } from "./UsageCaps";++vi.mock("@/state/store", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/state/store")>(),+ useStore: () => ({ state: { bots: [{ id: "b1", name: "Ada" }, { id: "b2", name: "Bo" }, { id: "b3", name: "Hidden", hidden: true }] }, dispatch: () => {} }),+}));++const cap = (more: Partial<CapState>): CapState => ({ id: "server:day:usd", scope: "server", period: "day", unit: "usd", limit: 10, used: 2, percent: 20, warn: false, reached: false, resetsAt: Date.parse("2026-09-16T00:00:00Z"), ...more });+const view = (more: Partial<UsageCapView> = {}): UsageCapView => ({ stops: "unattended", server: {}, bots: {}, env: { stops: false, server: [] }, caps: [], ...more });+const render = (value: UsageCapView | null | undefined) => renderToStaticMarkup(createElement(UsageCapsCard, { view: value }));++describe("the usage caps card", () => {+ it("is shown to the owner only: without the owner's view there is nothing", () => {+ expect(render(null)).toBe("");+ expect(render(undefined)).toBe("");+ });++ it("says no cap is set, and offers the two choices with unattended work first", () => {+ const markup = render(view());+ expect(markup).toContain("Usage caps");+ expect(markup).toContain("No cap is set, so nothing is stopped.");+ expect(markup).toContain("Unattended work only: routines, webhooks, app events, Bot API calls and hand-offs nobody is waiting on");+ expect(markup).toContain("Everything, including your own messages");+ for (const label of ["Per day (USD)", "Per day (tokens)", "Per month (USD)", "Per month (tokens)"]) expect(markup).toContain(`All bots together: ${label}`);+ expect(markup).toContain("Add a cap for a bot");+ expect(markup).toContain(">Ada</option>");+ expect(markup).not.toContain("Hidden");+ expect(markup).not.toContain("set in this installation’s environment");+ });++ it("shows the use against each cap, quiet below 80%, a line from 80%, and when work starts again once reached", () => {+ const markup = render(view({+ server: { dailyUsd: 10 }, bots: { b1: { monthlyTokens: 2_000_000 } },+ caps: [+ cap({}),+ cap({ id: "server:month:usd", period: "month", limit: 100, used: 81, percent: 81, warn: true }),+ cap({ id: "bot:b1:month:tokens", scope: "bot", botId: "b1", period: "month", unit: "tokens", limit: 2_000_000, used: 2_500_000, percent: 125, warn: true, reached: true }),+ ],+ }));+ expect(markup).toContain("All bots together, today");+ expect(markup).toContain("$2.00 of $10.00 (20%)");+ expect(markup).toContain("All bots together, this month");+ expect(markup).toContain("At 81% of the cap");+ expect(markup).toContain("Ada, this month");+ expect(markup).toContain("2.5M tokens of 2M tokens (125%)");+ expect(markup).toContain("Reached: the work it covers is skipped and starts again");+ expect(markup).toContain('aria-valuenow="100"');+ expect(markup.match(/At \d+% of the cap/g)).toHaveLength(1);+ expect(markup).toContain('value="10"');+ expect(markup).toContain('value="2000000"');+ expect([capTone(cap({})), capTone(cap({ warn: true })), capTone(cap({ warn: true, reached: true }))]).toEqual(["quiet", "warning", "danger"]);+ });++ it("locks what the environment sets and says where it is changed", () => {+ const markup = render(view({ stops: "everything", env: { stops: true, server: ["dailyUsd"] } }));+ expect(markup).toContain("<option value=\"everything\" selected=\"\">");+ expect(markup).toContain("The greyed-out values are set in this installation’s environment and are changed there.");+ expect(markup).toMatch(/<input[^>]*aria-label="All bots together: Per day \(USD\)"[^>]*disabled=""/);+ expect(markup).not.toMatch(/<input[^>]*aria-label="All bots together: Per day \(tokens\)"[^>]*disabled=""/);+ });++ it("shows the value in force in a greyed input, and a save keeps config.json's own values, never the environment's", () => {+ const locked = view({ stops: "everything", savedStops: "unattended", server: { dailyUsd: 4, monthlyUsd: 30 },+ env: { stops: true, server: ["dailyUsd", "dailyTokens"], values: { server: { dailyUsd: 2, dailyTokens: 500 } } } });+ const markup = render(locked);+ expect(markup).toMatch(/<input[^>]*aria-label="All bots together: Per day \(USD\)" disabled=""[^>]*value="2"\/>/);+ expect(markup).toMatch(/<input[^>]*aria-label="All bots together: Per day \(tokens\)" disabled=""[^>]*value="500"\/>/);+ expect(markup).toMatch(/<input[^>]*aria-label="All bots together: Per month \(USD\)" class[^>]*value="30"\/>/);+ // The form holds 2 and 500 from the environment and the owner typed 40 per month: only 40 is theirs to save.+ expect(capsToSave(locked, "everything", { dailyUsd: 2, dailyTokens: 500, monthlyUsd: 40 }, { b1: { dailyUsd: 1 } }))+ .toEqual({ stops: "unattended", server: { dailyUsd: 4, monthlyUsd: 40 }, bots: { b1: { dailyUsd: 1 } } });+ expect(capsToSave(view(), "everything", { dailyUsd: 2 }, {})).toEqual({ stops: "everything", server: { dailyUsd: 2 }, bots: {} });+ });++ it("reads a row of inputs as caps: empty and 0 are no cap, dollars may be fractions, tokens are whole", () => {+ expect(limitsOf({ dailyUsd: "2.5", monthlyUsd: "", dailyTokens: "1,000,000", monthlyTokens: "0" })).toEqual({ dailyUsd: 2.5, dailyTokens: 1_000_000 });+ expect(limitsOf({ dailyUsd: "", monthlyUsd: "", dailyTokens: "", monthlyTokens: "" })).toEqual({});+ for (const bad of [{ dailyUsd: "-1" }, { dailyUsd: "lots" }, { dailyTokens: "1.5" }]) {+ expect(limitsOf({ dailyUsd: "", monthlyUsd: "", dailyTokens: "", monthlyTokens: "", ...bad })).toBeNull();+ }+ });+});++describe("what the period's dollars leave out", () => {+ const render = (summary: Parameters<typeof CostCaveats>[0]["summary"]) => renderToStaticMarkup(createElement(CostCaveats, { summary }));+ it("says nothing when every turn is priced and billed", () => {+ expect(render(null)).toBe("");+ expect(render({ total: { turns: 4, unpriced: 0 }, notBilled: { usd: 0, turns: 0 } })).toBe("");+ });+ it("labels subscription dollars as estimated, not billed, and counts the turns that have no price", () => {+ const markup = render({ total: { turns: 9, unpriced: 3 }, notBilled: { usd: 1.25, turns: 5 } });+ expect(markup).toContain("$1.25 of this is estimated, not billed: it ran on an AI signed in with a subscription.");+ expect(markup).toContain("Turns counted at $0 because their model has no price: 3. The total leaves them out.");+ expect(render({ total: { turns: 9, unpriced: 3 } })).not.toContain("not billed");+ });+});diff --git a/src/components/UsageCaps.tsx b/src/components/UsageCaps.tsxnew file mode 100644index 0000000000..d51b1587f0--- /dev/null+++ b/src/components/UsageCaps.tsx@@ -0,0 +1,214 @@+import { useEffect, useState } from "react";+import { Loader2, Plus, Trash2 } from "lucide-react";+import { api, useStore } from "@/state/store";+import { cn } from "@/lib/cn";+import { activeLocale, documentLanguage, t } from "@/lib/i18n";+import type { LocaleKey } from "@/locales";+import { formatTokens, formatUsd } from "@/lib/usage";+import { Select } from "./Select";+import { Card } from "./SettingsPrimitives";++export type CapField = "dailyUsd" | "monthlyUsd" | "dailyTokens" | "monthlyTokens";+export type CapLimits = Partial<Record<CapField, number>>;++export interface CapState {+ id: string;+ scope: "server" | "bot";+ botId?: string;+ period: "day" | "month";+ unit: "usd" | "tokens";+ limit: number;+ used: number;+ percent: number;+ warn: boolean;+ reached: boolean;+ resetsAt: number;+}++/** `caps` on GET /api/usage and the body of /api/usage/caps: only the owner gets one. */+export interface UsageCapView {+ /** What a reached cap stops now; `savedStops` is what config.json holds. */+ stops: "unattended" | "everything";+ savedStops?: "unattended" | "everything";+ /** The saved caps; `env.values` holds what the environment sets, which wins field by field. */+ server: CapLimits;+ bots: Record<string, CapLimits>;+ env: { stops: boolean; server: CapField[]; values?: { server: CapLimits } };+ caps: CapState[];+}++const FIELDS: ReadonlyArray<{ field: CapField; label: LocaleKey; whole: boolean }> = [+ { field: "dailyUsd", label: "usage.caps.dailyUsd", whole: false },+ { field: "dailyTokens", label: "usage.caps.dailyTokens", whole: true },+ { field: "monthlyUsd", label: "usage.caps.monthlyUsd", whole: false },+ { field: "monthlyTokens", label: "usage.caps.monthlyTokens", whole: true },+];++type Draft = Record<CapField, string>;+const draftOf = (limits: CapLimits | undefined): Draft =>+ Object.fromEntries(FIELDS.map(({ field }) => [field, limits?.[field] ? String(limits[field]) : ""])) as Draft;++/** The numbers a row of inputs holds, or null when one is not a cap: empty means none, dollars 0 or more, tokens whole. */+export function limitsOf(draft: Draft): CapLimits | null {+ const limits: CapLimits = {};+ for (const { field, whole } of FIELDS) {+ const raw = draft[field].trim().replace(/,/g, "");+ if (raw === "") continue;+ const value = Number(raw);+ if (!Number.isFinite(value) || value < 0 || (whole && !Number.isInteger(value))) return null;+ if (value > 0) limits[field] = value;+ }+ return limits;+}++export const capTone = (cap: Pick<CapState, "warn" | "reached">): "quiet" | "warning" | "danger" => (cap.reached ? "danger" : cap.warn ? "warning" : "quiet");++const amount = (cap: Pick<CapState, "unit">, value: number) => (cap.unit === "usd" ? formatUsd(value) : t("usage.caps.tokens", { count: formatTokens(Math.round(value)) }));+const resets = (at: number) => new Date(at).toLocaleString(documentLanguage(activeLocale()), { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });++function CapUse({ cap, name }: { cap: CapState; name: string }) {+ const tone = capTone(cap);+ return (+ <li data-testid="usage-cap" data-cap={cap.id}>+ <div className="mb-1 flex flex-wrap items-baseline justify-between gap-x-3 text-[13px]">+ <span className="text-ink">{t(cap.period === "day" ? "usage.caps.useDay" : "usage.caps.useMonth", { who: name })}</span>+ <span className="tabular-nums text-ink-secondary">{t("usage.caps.used", { used: amount(cap, cap.used), limit: amount(cap, cap.limit), percent: String(cap.percent) })}</span>+ </div>+ <div className="h-2 w-full overflow-hidden rounded-full bg-inset" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.min(100, cap.percent)}>+ <div className={cn("h-full rounded-full", tone === "danger" ? "bg-danger" : tone === "warning" ? "bg-warning" : "bg-accent")} style={{ width: `${Math.min(100, cap.percent)}%` }} />+ </div>+ {tone !== "quiet" && (+ <p className={cn("mt-1 text-[12px]", tone === "danger" ? "text-danger" : "text-warning")}>+ {cap.reached ? t("usage.caps.reached", { resets: resets(cap.resetsAt) }) : t("usage.caps.nearing", { percent: String(cap.percent) })}+ </p>+ )}+ </li>+ );+}++const INPUT = "w-28 rounded-lg border border-hairline/40 bg-inset px-2 py-1.5 text-[13px] tabular-nums text-ink focus:outline-none disabled:opacity-50";++function LimitInputs({ who, draft, locked, disabled, onChange }: { who: string; draft: Draft; locked?: readonly CapField[]; disabled: boolean; onChange: (field: CapField, value: string) => void }) {+ return (+ <div className="flex flex-wrap items-end gap-2">+ {FIELDS.map(({ field, label, whole }) => (+ <label key={field} className="flex flex-col gap-1 text-[12px] text-ink-secondary">+ {t(label)}+ <input value={draft[field]} onChange={(event) => onChange(field, event.target.value)} inputMode={whole ? "numeric" : "decimal"} placeholder={t("usage.caps.noCap")}+ aria-label={`${who}: ${t(label)}`} disabled={disabled || locked?.includes(field)} className={INPUT} />+ </label>+ ))}+ </div>+ );+}++/** The owner's caps on a day's and a month's usage, for the server and for each bot, with the use against each. */+export function UsageCapsCard({ view, onSaved }: { view: UsageCapView | null | undefined; onSaved?: () => void }) {+ return view ? <CapsForm view={view} onSaved={onSaved} /> : null;+}++/** The server's caps in force: an environment value shows (greyed) in place of the saved one. */+const serverInForce = (view: UsageCapView): CapLimits => ({ ...view.server, ...view.env.values?.server });++/** What a save sends: the owner's own values, never one the environment holds. A greyed field keeps what config.json+ * has, and the choice of what a cap stops keeps the saved one while the environment makes it. */+export function capsToSave(view: UsageCapView, stops: UsageCapView["stops"], server: CapLimits, bots: Record<string, CapLimits>): { stops: UsageCapView["stops"]; server: CapLimits; bots: Record<string, CapLimits> } {+ const own: CapLimits = { ...server };+ for (const field of view.env.server) {+ const saved = view.server[field];+ if (saved === undefined) delete own[field];+ else own[field] = saved;+ }+ return { stops: view.env.stops ? view.savedStops ?? "unattended" : stops, server: own, bots };+}++const botRows = (view: UsageCapView) => Object.entries(view.bots).map(([botId, limits]) => ({ botId, draft: draftOf(limits) }));++function CapsForm({ view, onSaved }: { view: UsageCapView; onSaved?: () => void }) {+ const { state } = useStore();+ const [stops, setStops] = useState(view.stops);+ const [server, setServer] = useState(() => draftOf(serverInForce(view)));+ const [bots, setBots] = useState(() => botRows(view));+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const saved = JSON.stringify([view.stops, view.server, view.bots, view.env]);+ useEffect(() => {+ setStops(view.stops);+ setServer(draftOf(serverInForce(view)));+ setBots(botRows(view));+ }, [saved]);++ const botName = (botId: string | undefined) => state.bots?.find((bot) => bot.id === botId)?.name ?? t("usage.caps.goneBot");+ const free = (state.bots ?? []).filter((bot) => !bot.hidden && !bots.some((row) => row.botId === bot.id));++ const save = async () => {+ if (saving) return;+ const serverLimits = limitsOf(server);+ const botLimits = bots.map((row) => [row.botId, limitsOf(row.draft)] as const);+ if (!serverLimits || botLimits.some(([, limits]) => !limits)) {+ setError(t("usage.caps.invalid"));+ return;+ }+ setSaving(true);+ setError(null);+ try {+ await api("/api/usage/caps", { method: "PUT", body: JSON.stringify(capsToSave(view, stops, serverLimits, Object.fromEntries(botLimits) as Record<string, CapLimits>)) });+ onSaved?.();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setSaving(false);+ }+ };++ return (+ <Card title={t("usage.caps.title")} subtitle={t("usage.caps.subtitle")}>+ {view.caps.length ? (+ <ul className="mb-4 flex flex-col gap-3">+ {view.caps.map((cap) => <CapUse key={cap.id} cap={cap} name={cap.scope === "server" ? t("usage.caps.server") : botName(cap.botId)} />)}+ </ul>+ ) : <p className="mb-4 text-[13px] text-ink-secondary">{t("usage.caps.none")}</p>}+ <form className="flex flex-col gap-4" onSubmit={(event) => { event.preventDefault(); void save(); }}>+ <label className="flex flex-col gap-1 text-[12px] text-ink-secondary">+ {t("usage.caps.stops")}+ <Select size="sm" className="w-full max-w-md" value={stops} onChange={(event) => setStops(event.target.value as UsageCapView["stops"])} disabled={saving || view.env.stops}>+ <option value="unattended">{t("usage.caps.stopsUnattended")}</option>+ <option value="everything">{t("usage.caps.stopsEverything")}</option>+ </Select>+ </label>+ <div>+ <div className="mb-1.5 text-[13px] text-ink">{t("usage.caps.server")}</div>+ <LimitInputs who={t("usage.caps.server")} draft={server} locked={view.env.server} disabled={saving} onChange={(field, value) => setServer((current) => ({ ...current, [field]: value }))} />+ {(view.env.server.length > 0 || view.env.stops) && <p className="mt-1 text-[12px] text-ink-secondary">{t("usage.caps.fromEnv")}</p>}+ </div>+ {bots.map((row) => (+ <div key={row.botId}>+ <div className="mb-1.5 flex items-center gap-2 text-[13px] text-ink">+ {botName(row.botId)}+ <button type="button" onClick={() => setBots((current) => current.filter((other) => other.botId !== row.botId))} aria-label={t("usage.caps.removeBot", { bot: botName(row.botId) })} disabled={saving}+ className="rounded-md p-1 text-ink-secondary hover:bg-control hover:text-danger disabled:opacity-50"><Trash2 size={13} /></button>+ </div>+ <LimitInputs who={botName(row.botId)} draft={row.draft} disabled={saving}+ onChange={(field, value) => setBots((current) => current.map((other) => (other.botId === row.botId ? { ...other, draft: { ...other.draft, [field]: value } } : other)))} />+ </div>+ ))}+ <div className="flex flex-wrap items-center gap-2">+ {free.length > 0 && (+ <label className="flex items-center gap-1.5 text-[12px] text-ink-secondary">+ <Plus size={13} />+ <Select size="sm" value="" onChange={(event) => { const botId = event.target.value; if (botId) setBots((current) => [...current, { botId, draft: draftOf(undefined) }]); }} disabled={saving} aria-label={t("usage.caps.addBot")}>+ <option value="">{t("usage.caps.addBot")}</option>+ {free.map((bot) => <option key={bot.id} value={bot.id}>{bot.name}</option>)}+ </Select>+ </label>+ )}+ <button type="submit" disabled={saving} className="ml-auto flex items-center gap-1.5 rounded-lg bg-raised px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50">+ {saving && <Loader2 size={13} className="animate-spin" />}{t("common.save")}+ </button>+ </div>+ </form>+ <p className="mt-2 text-[12px] leading-relaxed text-ink-secondary">{t("usage.caps.hint")}</p>+ {error && <p role="alert" className="mt-2 text-[12px] text-danger">{error}</p>}+ </Card>+ );+}diff --git a/src/components/UsageSection.tsx b/src/components/UsageSection.tsxindex c5135ba291..897e0c5ea0 100644--- a/src/components/UsageSection.tsx+++ b/src/components/UsageSection.tsx@@ -14,6 +14,7 @@ import { BotAvatar } from "./Avatar";import { PlanUsage } from "./PlanUsage";import { Select } from "./Select";import { UsageBudgetCards, type BudgetState } from "./UsageBudget";+import { UsageCapsCard, type UsageCapView } from "./UsageCaps";import { TraceView } from "./usage/TraceView";import { LiveBadge, modelName, StatStrip, totalsStats } from "./usage/TraceWaterfall";@@ -37,7 +38,25 @@ export interface UsageGroup {interface UsageSummary {groupBy: UsageGroupBy;groups: UsageGroup[];+ /** The period as a whole; `unpriced` counts its turns whose model has no price, booked at $0. */+ total?: { turns: number; unpriced: number };budget?: BudgetState | null;+ caps?: UsageCapView | null;+ /** Dollars booked on engines signed in with a subscription: an estimate nobody is billed. */+ notBilled?: { usd: number; turns: number };+}++/** What the period's dollars leave out or overstate, one line each; nothing when the total is complete and billed. */+export function CostCaveats({ summary }: { summary: Pick<UsageSummary, "total" | "notBilled"> | null }) {+ const plan = summary?.notBilled?.usd ?? 0;+ const unpriced = summary?.total?.unpriced ?? 0;+ if (!(plan > 0) && !unpriced) return null;+ return (+ <div data-testid="usage-caveats" className="flex flex-col gap-0.5 px-1 text-[12px] leading-5 text-ink-secondary">+ {plan > 0 && <p>{t("usage.page.notBilled", { cost: formatCost(plan) })}</p>}+ {unpriced > 0 && <p>{t("usage.page.unpriced", { count: String(unpriced) })}</p>}+ </div>+ );}const GROUP_LABEL_KEYS: Record<UsageGroupBy, LocaleKey> = {@@ -183,12 +202,12 @@ function ModelLegend({ groups }: { groups: readonly UsageGroup[] }) {}/** The "Where it went" panel: bots on one side, the chosen grouping on the other, both split by model. */-function WhereItWent({ range, version, onBudget }: { range: { from: string; to: string }; version: number; onBudget: (budget: BudgetState | null) => void }) {+function WhereItWent({ range, version, onSummary }: { range: { from: string; to: string }; version: number; onSummary: (summary: UsageSummary | null) => void }) {const [other, setOther] = useState<UsageGroupBy>("model");const settings = useContext(SettingsLook);const byBot = useUsageGroups(range, "bot", version, "model");const byOther = useUsageGroups(range, other, version, other === "model" ? undefined : "model");- useEffect(() => { onBudget(byBot?.budget ?? null); }, [byBot, onBudget]);+ useEffect(() => { onSummary(byBot); }, [byBot, onSummary]);if (settings) return null;return (<section className="rounded-2xl border border-hairline/50 bg-card p-5" aria-label={t("usage.page.where")}>@@ -227,12 +246,12 @@ function WhereItWent({ range, version, onBudget }: { range: { from: string; to:const SETTINGS_GROUPINGS: readonly UsageGroupBy[] = ["bot", ...OTHER_GROUPINGS];/** Settings' Where it went: a select (by bot, model, person…) as the section's action, then one row per item. */-function SettingsWhereItWent({ range, version, onBudget }: { range: { from: string; to: string }; version: number; onBudget: (budget: BudgetState | null) => void }) {+function SettingsWhereItWent({ range, version, onSummary }: { range: { from: string; to: string }; version: number; onSummary: (summary: UsageSummary | null) => void }) {const { state } = useStore();const [by, setBy] = useState<UsageGroupBy>("bot");const byBot = useUsageGroups(range, "bot", version);const groups = useUsageGroups(range, by, version);- useEffect(() => { onBudget(byBot?.budget ?? null); }, [byBot, onBudget]);+ useEffect(() => { onSummary(byBot); }, [byBot, onSummary]);const top = groups?.groupBy === by ? [...groups.groups].sort((a, b) => headlineTokens(b) - headlineTokens(a)).filter((group) => headlineTokens(group) > 0).slice(0, 8) : null;return (<SettingsGroup label={t("usage.page.where")} block="where"@@ -299,7 +318,8 @@ export function UsageSection() {const [list, setList] = useState<TraceList | null>(null);const [error, setError] = useState<string | null>(null);const [version, setVersion] = useState(0);- const [budget, setBudget] = useState<BudgetState | null>(null);+ const [summary, setSummary] = useState<UsageSummary | null>(null);+ const budget = summary?.budget ?? null;const [open, setOpen] = useState<{ id: string; at: number } | null>(null);const pending = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -356,7 +376,8 @@ export function UsageSection() {</div></SettingsRows></SettingsGroup>- <SettingsWhereItWent range={range} version={version} onBudget={setBudget} />+ <CostCaveats summary={summary} />+ <SettingsWhereItWent range={range} version={version} onSummary={setSummary} /><SettingsGroup label={t("usage.page.runs")} block="runs" footnote={untimed ? t("usage.page.untimedNote") : undefined}actions={<a href={usageExportHref(range)} download className="ui-button ui-button-md rounded-full">{t("usage.history.export")}</a>}><SettingsRows>@@ -367,6 +388,7 @@ export function UsageSection() {</SettingsGroup></>}<PlanUsage />+ <UsageCapsCard view={summary?.caps} onSaved={() => setVersion((value) => value + 1)} /><UsageBudgetCards budget={budget} /></div>);@@ -398,7 +420,8 @@ export function UsageSection() {{list ? <StatStrip items={totalsStats(list.totals, t("trace.stat.time"))} />: <div className="flex items-center gap-2 p-5 text-[13px] text-ink-secondary"><Loader2 size={14} className="animate-spin" />{t("common.checking")}</div>}</section>- <WhereItWent range={range} version={version} onBudget={setBudget} />+ <CostCaveats summary={summary} />+ <WhereItWent range={range} version={version} onSummary={setSummary} /><section className="rounded-2xl border border-hairline/50 bg-card p-2" aria-label={t("usage.page.runs")}><div className="px-3 pb-1 pt-3"><h3 className="text-[15px] font-medium text-ink">{t("usage.page.runs")}</h3>@@ -416,6 +439,7 @@ export function UsageSection() {</>)}<PlanUsage />+ <UsageCapsCard view={summary?.caps} onSaved={() => setVersion((value) => value + 1)} /><UsageBudgetCards budget={budget} /></div>);diff --git a/src/locales/de.json b/src/locales/de.jsonindex 6d50a83386..c8c0a00ffe 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -221,6 +221,14 @@"server.botHeld": "{bot} ist pausiert und nimmt keine neue Arbeit an. Setze ihn über sein Menü in der Seitenleiste fort.","server.botHeldDepartment": "{bot} ist mit der Abteilung {department} pausiert und nimmt keine neue Arbeit an. Setze die Abteilung über ihr Menü in der Seitenleiste fort.","server.botHeldAll": "Alle Bots sind pausiert, daher nimmt {bot} keine neue Arbeit an. Setze alle Bots über das Menü eines beliebigen Bots in der Seitenleiste fort.",+ "server.usageCap.name.serverDay": "das tägliche Nutzungslimit für alle Bots",+ "server.usageCap.name.serverMonth": "das monatliche Nutzungslimit für alle Bots",+ "server.usageCap.name.botDay": "das tägliche Nutzungslimit von {bot}",+ "server.usageCap.name.botMonth": "das monatliche Nutzungslimit von {bot}",+ "server.usageCap.refused": "Nicht gestartet: {cap} ({limit}) ist erreicht. Neue Arbeit startet nach {resets} von selbst wieder, oder früher, wenn der Inhaber das Limit unter Einstellungen → Nutzung anhebt.",+ "server.usageCap.noticeTitle": "Nutzungslimit erreicht",+ "server.usageCap.noticeUnattended": "Unbeaufsichtigte Arbeit wird bis {resets} übersprungen: {cap} ({limit}) ist erreicht. Deine eigenen Nachrichten laufen weiter.",+ "server.usageCap.noticeEverything": "Bis {resets} startet keine neue Arbeit: {cap} ({limit}) ist erreicht.","server.teammates.queued.thread": "{bot} hat damit noch nicht begonnen: Ein früherer Durchlauf in diesem Thread läuft noch.","server.teammates.queued.slots": "{bot} hat damit noch nicht begonnen: Es laufen bereits {busy} von {limit} Threads gleichzeitig.","server.teammates.queued.room": "{bot} hat damit noch nicht begonnen: Es beendet gerade einen Durchlauf in einem Raum.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 001c343c13..5c5a22d2fb 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -357,6 +357,14 @@"server.botHeld": "{bot} is paused, so it takes no new work. Resume it from its menu in the sidebar.","server.botHeldDepartment": "{bot} is paused with the {department} department, so it takes no new work. Resume the department from its menu in the sidebar.","server.botHeldAll": "Every bot is paused, so {bot} takes no new work. Resume every bot from any bot’s menu in the sidebar.",+ "server.usageCap.name.serverDay": "the daily usage cap for all bots",+ "server.usageCap.name.serverMonth": "the monthly usage cap for all bots",+ "server.usageCap.name.botDay": "{bot}’s daily usage cap",+ "server.usageCap.name.botMonth": "{bot}’s monthly usage cap",+ "server.usageCap.refused": "Not started: {cap} ({limit}) is reached. New work starts again by itself after {resets}, or sooner if the owner raises the cap in Settings → Usage.",+ "server.usageCap.noticeTitle": "Usage cap reached",+ "server.usageCap.noticeUnattended": "Unattended work is skipped until {resets}: {cap} ({limit}) is reached. Your own messages still run.",+ "server.usageCap.noticeEverything": "No new work starts until {resets}: {cap} ({limit}) is reached.","pause.pauseBot": "Pause bot","pause.resumeBot": "Resume bot","pause.pauseDepartment": "Pause department",@@ -4322,6 +4330,30 @@"usage.budget.warnAt": "Warn at (%)","usage.budget.hint": "Counts what providers report (real on your keys, an equivalent on personal subscriptions) and, for providers that report no price, an estimate from list prices or your own prices. Models with no known price are not counted. Set 0 to remove the limit.","usage.budget.invalid": "Enter a limit of 0 or more and a warning percentage between 1 and 100.",+ "usage.caps.title": "Usage caps",+ "usage.caps.subtitle": "Stop new work once a day’s or a month’s usage reaches a limit you set. Nothing is cut off mid-turn, and work starts again by itself when the day or month rolls over (midnight UTC) or you raise the cap.",+ "usage.caps.none": "No cap is set, so nothing is stopped.",+ "usage.caps.server": "All bots together",+ "usage.caps.goneBot": "A deleted bot",+ "usage.caps.useDay": "{who}, today",+ "usage.caps.useMonth": "{who}, this month",+ "usage.caps.used": "{used} of {limit} ({percent}%)",+ "usage.caps.tokens": "{count} tokens",+ "usage.caps.reached": "Reached: the work it covers is skipped and starts again {resets}",+ "usage.caps.nearing": "At {percent}% of the cap",+ "usage.caps.stops": "What a reached cap stops",+ "usage.caps.stopsUnattended": "Unattended work only: routines, webhooks, app events, Bot API calls and hand-offs nobody is waiting on",+ "usage.caps.stopsEverything": "Everything, including your own messages",+ "usage.caps.dailyUsd": "Per day (USD)",+ "usage.caps.dailyTokens": "Per day (tokens)",+ "usage.caps.monthlyUsd": "Per month (USD)",+ "usage.caps.monthlyTokens": "Per month (tokens)",+ "usage.caps.noCap": "No cap",+ "usage.caps.addBot": "Add a cap for a bot",+ "usage.caps.removeBot": "Remove the caps for {bot}",+ "usage.caps.fromEnv": "The greyed-out values are set in this installation’s environment and are changed there.",+ "usage.caps.hint": "Dollars are the estimate this page shows: notional on a subscription sign-in and $0 for a model with no price, so a token cap is the one that always counts. Tokens are fresh input plus output. Only the owner sees this.",+ "usage.caps.invalid": "Enter dollars as 0 or more and tokens as a whole number, or leave a field empty for no cap.","usage.prices.title": "Sell prices","usage.prices.subtitle": "What you charge per million tokens, by model. History and the CSV export gain a billable column; the provider's own cost stays alongside.","usage.prices.currency": "Currency",@@ -10167,6 +10199,12 @@"routines.server.restored": "Not run again: this schedule was restored from a backup made before this run had its turn","routines.server.restoredMany": "Not run again: {count} scheduled runs from before this schedule was restored from a backup","routines.server.duplicate": "Not started: this scheduled run had already started once",+ "routines.server.capSkippedOne": "Skipped: {why} ({amount}) is reached. Runs start again after {resets}",+ "routines.server.capSkippedMany": "Skipped {count} runs: {why} ({amount}) is reached. Runs start again after {resets}",+ "routines.server.part.capServerDay": "the daily usage cap for all bots",+ "routines.server.part.capServerMonth": "the monthly usage cap for all bots",+ "routines.server.part.capBotDay": "this bot’s daily usage cap",+ "routines.server.part.capBotMonth": "this bot’s monthly usage cap","approval.applied.waitFollowUp": "Then {name} will: {followUp}","chat.notice.waitDone.urlContains": "{label}: done. {url} now says “{text}”.","chat.notice.waitDone.urlMissing": "{label}: done. {url} no longer says “{text}”.",@@ -10941,6 +10979,8 @@"settings.plan.cancelAction": "Cancel…","usage.page.summary": "Summary","usage.page.estimated": "Estimated {cost}",+ "usage.page.notBilled": "{cost} of this is estimated, not billed: it ran on an AI signed in with a subscription.",+ "usage.page.unpriced": "Turns counted at $0 because their model has no price: {count}. The total leaves them out.","settings.spending.aiLimits": "AI plan limits","settings.plan.spent": "{place} spent","settings.plan.spentWeek": "Estimated {cost} this week",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex a4254325ea..ba994bbaa4 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -340,6 +340,14 @@"server.botHeld": "{bot} está pausado e não recebe trabalho novo. Retome-o pelo menu dele na barra lateral.","server.botHeldDepartment": "{bot} está pausado junto com o departamento {department} e não recebe trabalho novo. Retome o departamento pelo menu dele na barra lateral.","server.botHeldAll": "Todos os bots estão pausados, então {bot} não recebe trabalho novo. Retome todos os bots pelo menu de qualquer bot na barra lateral.",+ "server.usageCap.name.serverDay": "o limite diário de uso de todos os bots",+ "server.usageCap.name.serverMonth": "o limite mensal de uso de todos os bots",+ "server.usageCap.name.botDay": "o limite diário de uso de {bot}",+ "server.usageCap.name.botMonth": "o limite mensal de uso de {bot}",+ "server.usageCap.refused": "Não iniciado: {cap} ({limit}) foi atingido. O trabalho novo volta a começar sozinho depois de {resets}, ou antes, se o dono aumentar o limite em Configurações → Uso.",+ "server.usageCap.noticeTitle": "Limite de uso atingido",+ "server.usageCap.noticeUnattended": "O trabalho automático é pulado até {resets}: {cap} ({limit}) foi atingido. Suas próprias mensagens continuam funcionando.",+ "server.usageCap.noticeEverything": "Nenhum trabalho novo começa até {resets}: {cap} ({limit}) foi atingido.","pause.pauseBot": "Pausar bot","pause.resumeBot": "Retomar bot","pause.pauseDepartment": "Pausar departamento",@@ -4120,6 +4128,30 @@"usage.budget.warnAt": "Avisar ao atingir (%)","usage.budget.hint": "Considera os valores que os provedores informam (o valor real ao usar suas chaves e um equivalente em assinaturas pessoais). Para provedores que não informam preço, usa uma estimativa com base na tabela de preços ou nos preços que você definiu. Modelos sem preço conhecido não entram na conta. Defina 0 para remover o limite.","usage.budget.invalid": "Informe um limite de 0 ou mais e uma porcentagem de aviso entre 1 e 100.",+ "usage.caps.title": "Limites de uso",+ "usage.caps.subtitle": "Interrompe o trabalho novo quando o uso do dia ou do mês chega a um limite que você define. Nada é cortado no meio de uma resposta, e o trabalho volta a começar sozinho quando o dia ou o mês vira (meia-noite UTC) ou quando você aumenta o limite.",+ "usage.caps.none": "Nenhum limite definido, então nada é interrompido.",+ "usage.caps.server": "Todos os bots juntos",+ "usage.caps.goneBot": "Um bot excluído",+ "usage.caps.useDay": "{who}, hoje",+ "usage.caps.useMonth": "{who}, este mês",+ "usage.caps.used": "{used} de {limit} ({percent}%)",+ "usage.caps.tokens": "{count} tokens",+ "usage.caps.reached": "Atingido: o trabalho coberto por ele é pulado e volta a começar {resets}",+ "usage.caps.nearing": "Em {percent}% do limite",+ "usage.caps.stops": "O que um limite atingido interrompe",+ "usage.caps.stopsUnattended": "Só o trabalho automático: rotinas, webhooks, eventos de apps, chamadas da Bot API e repasses que ninguém está esperando",+ "usage.caps.stopsEverything": "Tudo, inclusive suas próprias mensagens",+ "usage.caps.dailyUsd": "Por dia (USD)",+ "usage.caps.dailyTokens": "Por dia (tokens)",+ "usage.caps.monthlyUsd": "Por mês (USD)",+ "usage.caps.monthlyTokens": "Por mês (tokens)",+ "usage.caps.noCap": "Sem limite",+ "usage.caps.addBot": "Adicionar um limite para um bot",+ "usage.caps.removeBot": "Remover os limites de {bot}",+ "usage.caps.fromEnv": "Os valores em cinza são definidos no ambiente desta instalação e só podem ser alterados lá.",+ "usage.caps.hint": "Os dólares são a estimativa que esta página mostra: um valor de referência quando a IA está conectada por assinatura e $0 para um modelo sem preço, então o limite em tokens é o que sempre conta. Tokens são a entrada nova mais a saída. Só o dono vê isto.",+ "usage.caps.invalid": "Informe os dólares como 0 ou mais e os tokens como um número inteiro, ou deixe o campo vazio para não ter limite.","usage.prices.title": "Preços de venda","usage.prices.subtitle": "Quanto você cobra por milhão de tokens, por modelo. O histórico e a exportação em CSV ganham uma coluna com o valor a cobrar; o custo do próprio provedor continua ao lado.","usage.prices.currency": "Moeda",@@ -10079,6 +10111,12 @@"routines.server.restored": "Não rodou de novo: este agendamento foi restaurado de um backup feito antes de esta execução ter a vez dela","routines.server.restoredMany": "Não rodaram de novo: {count} execuções agendadas de antes de este agendamento ser restaurado de um backup","routines.server.duplicate": "Não iniciou: esta execução agendada já tinha iniciado uma vez",+ "routines.server.capSkippedOne": "Pulada: {why} ({amount}) foi atingido. As execuções voltam a começar depois de {resets}",+ "routines.server.capSkippedMany": "{count} execuções puladas: {why} ({amount}) foi atingido. As execuções voltam a começar depois de {resets}",+ "routines.server.part.capServerDay": "o limite diário de uso de todos os bots",+ "routines.server.part.capServerMonth": "o limite mensal de uso de todos os bots",+ "routines.server.part.capBotDay": "o limite diário de uso deste bot",+ "routines.server.part.capBotMonth": "o limite mensal de uso deste bot","approval.applied.waitFollowUp": "Depois da espera, {name} fará o seguinte: {followUp}","chat.notice.waitDone.urlContains": "Espera concluída: {label}. {url} agora contém “{text}”.","chat.notice.waitDone.urlMissing": "Espera concluída: {label}. {url} não contém mais “{text}”.",@@ -10895,6 +10933,8 @@"settings.plan.cancelAction": "Cancelar…","usage.page.summary": "Resumo","usage.page.estimated": "Cerca de {cost}",+ "usage.page.notBilled": "{cost} disso é estimado, não cobrado: rodou em uma IA conectada por assinatura.",+ "usage.page.unpriced": "Sessões contadas como $0 porque o modelo delas não tem preço: {count}. O total não as inclui.","settings.spending.aiLimits": "Limites do plano de IA","settings.plan.spent": "Gasto de {place}","settings.plan.spentWeek": "Cerca de {cost} nesta semana",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex c9c3ece8af..0143161c0b 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -3983,6 +3983,14 @@"server.botHeld": "5980b395f2c56023b870eacc8b6d9bdbc746171c7b8b5b44fcb07c657b64b6ce","server.botHeldDepartment": "ad3c5b51e8e3c5271f998a9ce283fe62a5fd23660096f757050a942168ab7361","server.botHeldAll": "bae5b35a054c94e0b4ef049f576d76eef48a47d11a66dc7405e09592b9f3f49c",+ "server.usageCap.name.serverDay": "04df9f6c0fedfe1a7af0c92e8f5ed7c5972448613624c2d7042138215e87bb7f",+ "server.usageCap.name.serverMonth": "b12ed87bc1369361433587d3de23f359264db81ace6f1662a6de5b602d8bcef7",+ "server.usageCap.name.botDay": "1ee447b48ae96cfba2ae1c6e30c03911a757e9ced41878eea7672a72a48fd771",+ "server.usageCap.name.botMonth": "46046f040fe6dd92a8d0b396031f6d60baccb6cae9dff6532111dab8c037526a",+ "server.usageCap.refused": "9b932f99745a4951183e9f1c431214a52df93e82f627f8a7bef57adc176de10e",+ "server.usageCap.noticeTitle": "03e949569669b310c759762e97a1a6a565f89336caa085665351f53df275542f",+ "server.usageCap.noticeUnattended": "1742e3a01876740777a21493d2f1a9e3469a3b4d2845eb618b76fc0f22c02d43",+ "server.usageCap.noticeEverything": "e282bdc4127c13afd02742cb6f5c80202e8a006eb2b5a74befd56377568015b6","devices.computers.pairButton": "60f8288e33f9f57d2b51409fdb540b47a89c25447061bd354122442818a36ee0","devices.computers.pairTitle": "b7cda6a11ab410daa4b8977624ca72261c0168e7c3d83ae0eed93ac4e3540bc8","devices.computers.typeCode": "2a528dfe78f6b331e8cca951872961169ca6f340a886e40e84cc0b53d441c174",@@ -29809,6 +29817,30 @@"usage.budget.warnAt": "995b516c77490aabc8167dd3736cf07d6af65c24007525ab2fe8d75349ba8474","usage.budget.hint": "6236275ec1def757754abdf75b3cd3d6506e61a7b9b2038fe466ee50251d2575","usage.budget.invalid": "c28a77e82c1677c2a163ce847a2f2ca3fe78357eef7cd2ad74bb76269d851ffe",+ "usage.caps.title": "474e1b23ca0dac558025e1a6bb21920336c40b111fbd98c86b0a7ac44c420865",+ "usage.caps.subtitle": "268a63f82ab12c0a66dd93200aaaf632782f933efe84fa3ea106da18f320c131",+ "usage.caps.none": "fd7f1b8bc672b03a2473865b73822325ee937ff1b03138d1831fbe3f67573ac6",+ "usage.caps.server": "3a098be7293bd2851048c6539622c44b567cd9e2b85258aa1f900f194c294fcc",+ "usage.caps.goneBot": "961defba0f84fd7b5c996ce4dcd70a6b86d278afedddff3ade2bc1034aa7de7d",+ "usage.caps.useDay": "6eadb6d5c4457e60b2f14ddc847c41e7a3998bfebd73242550d47c464ead16f8",+ "usage.caps.useMonth": "930fc14daae5f6a8b76fdc869c3e99dc277b908317477f7eb7a7e442d7f44bd8",+ "usage.caps.used": "2127648835ec5ff67fe7338c35ccfd4bbc1005753bb54dd95b04555636093d32",+ "usage.caps.tokens": "bc17ff48c05229eb1e7470573c5c85a0334cb3ea42c1672c50064261e387ead2",+ "usage.caps.reached": "a7106d5084266e0591d98e7ee0d4bd81318e0fcb587db6de8c6dfd29cd9e1bc6",+ "usage.caps.nearing": "5560b4ab7bff413d04d2c8de2ae7aa77227b0725a4af62ee47984a8470d3ebd3",+ "usage.caps.stops": "837ab5e5a04327b34d1a0500025193119702ebe70c58f9901f13d4214eb0a3d8",+ "usage.caps.stopsUnattended": "54454b23236b87e84685d37318df34986f9931494ec97c76023ad68791902bf7",+ "usage.caps.stopsEverything": "e2954ea147a6b23558f3a8f0cc64ee53884b46c35829d2c8077b881f948e12da",+ "usage.caps.dailyUsd": "1fb0997f02bc8668a7a4fb89bbcf16e4473bb8a4c88f4d74a20b6a2d7ea4ec68",+ "usage.caps.dailyTokens": "6231a8bf721376dd20d72b4f2d6043f49bcc6d91653d73960c416b99dac4686e",+ "usage.caps.monthlyUsd": "f8f2d630addc02d31ae860cd3bf327b9279a3c0dc88acd96f534a965c446dbf4",+ "usage.caps.monthlyTokens": "94d36e7131002220d5b4f863cd94640667896f8fa60749849bd42c59c6956ad8",+ "usage.caps.noCap": "59db2115b7b072e590aae53c8d80b1bcf1e6b08fe3c5edb4351a3d9c07e5aca6",+ "usage.caps.addBot": "02801166ca6f108d63344b46e06ccf4fa57e7e5712c6aa87ada70c5a58d57969",+ "usage.caps.removeBot": "4a9aa3a26577e5a1ffbbce706399089dfeefe70b1a1483dabcf416bf12daa49d",+ "usage.caps.fromEnv": "93ce077b960212a5afbc088a21975b3d8806c288d270522a891d2ab9c4cbb583",+ "usage.caps.hint": "32f5d9de8af4f366b0798b3e1c05435d1c19f5dc1d840c3ecd7f588117dd56ad",+ "usage.caps.invalid": "399569e354f66fcf735bd0881cf34728dd6a59dd0acd4dc612512d150882908e","usage.prices.title": "b95327f5e52ea717ac52ee4417140c4f6cd793d75fb4f65f76667fffa173f8dd","usage.prices.subtitle": "7c8157a1288879cd0fb63207678de938231a83299717e2dd6ad128af0e896577","usage.prices.currency": "3ac1a9ec4fa7a9fa612a30803f3d88fa479a45431f644190ebcc18d3eaafdb3a",@@ -36619,6 +36651,8 @@"settings.plan.cancelAction": "9442312ba5f90ad67927f8e27461d351e8f1645bbc7a66aba0d7458a6171415a","usage.page.summary": "8e76a94ac8320d515375e625bef1829238b097ecbd33611b59eeefd4ffefebfb","usage.page.estimated": "fab849e655e81513c90be9df016e3497b38b319fe187f7e8b2796d7ba6e2faf3",+ "usage.page.notBilled": "7349090b4fa34d0538f388f5e5223b7603c38b9ec7d44dcd6a7356d4bc7a4238",+ "usage.page.unpriced": "f4b745ef52e1e8b325c5c76ad136a21c07e4bb2e02936b39fed27d151009458f","settings.spending.aiLimits": "bbcc21b398aa4bd39c0e630289c8d7e80974bafaa311618bca73ada839687996","settings.plan.spent": "50f0582d2cb34e5d880ea6401197f7bb05d32c92f5057ff716cf083ab3e7797d","settings.plan.spentWeek": "9540781b6b098450acbc4ea577202b63e9eb4b1cbe8be52b778f3c547f330dcb",@@ -36876,6 +36910,14 @@"server.botHeld": "5980b395f2c56023b870eacc8b6d9bdbc746171c7b8b5b44fcb07c657b64b6ce","server.botHeldDepartment": "ad3c5b51e8e3c5271f998a9ce283fe62a5fd23660096f757050a942168ab7361","server.botHeldAll": "bae5b35a054c94e0b4ef049f576d76eef48a47d11a66dc7405e09592b9f3f49c",+ "server.usageCap.name.serverDay": "04df9f6c0fedfe1a7af0c92e8f5ed7c5972448613624c2d7042138215e87bb7f",+ "server.usageCap.name.serverMonth": "b12ed87bc1369361433587d3de23f359264db81ace6f1662a6de5b602d8bcef7",+ "server.usageCap.name.botDay": "1ee447b48ae96cfba2ae1c6e30c03911a757e9ced41878eea7672a72a48fd771",+ "server.usageCap.name.botMonth": "46046f040fe6dd92a8d0b396031f6d60baccb6cae9dff6532111dab8c037526a",+ "server.usageCap.refused": "9b932f99745a4951183e9f1c431214a52df93e82f627f8a7bef57adc176de10e",+ "server.usageCap.noticeTitle": "03e949569669b310c759762e97a1a6a565f89336caa085665351f53df275542f",+ "server.usageCap.noticeUnattended": "1742e3a01876740777a21493d2f1a9e3469a3b4d2845eb618b76fc0f22c02d43",+ "server.usageCap.noticeEverything": "e282bdc4127c13afd02742cb6f5c80202e8a006eb2b5a74befd56377568015b6","pause.pauseBot": "eada7664ee24f58006b5e94a3badd100143184249a6f6fa04ca647fa666deee0","pause.resumeBot": "44def306f4c23ef1938c7c7e4d6c48eceff18f800043cdeaecc897da0d46d70f","pause.pauseDepartment": "8007675f16f892b29ca6f032943976fa4e91041bb30aad4df2d9ca6c1a32648c",@@ -37017,6 +37059,12 @@"routines.server.restored": "00cd6b284581fcc1d33a42f19a12ff4900e11019a4db0359d0a18618f6c7bb12","routines.server.restoredMany": "39401539696f40bc0c2f3cd39a1d4a42fd1b76e740722dfc91f4c44c9e1e36f4","routines.server.duplicate": "7516b9e9ffcc2126a9074d00d7277d204e0887e1d13c77fe94920e0428006fcd",+ "routines.server.capSkippedOne": "1ba9bb4813d8584878152ead604e9ce50798316680976870f8fcfedf510ed884",+ "routines.server.capSkippedMany": "9d1075b395431af33b8e82eaa69e6e140c514b22afa59c7c16cfb43facc8361c",+ "routines.server.part.capServerDay": "04df9f6c0fedfe1a7af0c92e8f5ed7c5972448613624c2d7042138215e87bb7f",+ "routines.server.part.capServerMonth": "b12ed87bc1369361433587d3de23f359264db81ace6f1662a6de5b602d8bcef7",+ "routines.server.part.capBotDay": "6a8cbed4b7abb32fce2b85437932e668900c9eabb1f1ff2af3186a64e5a7ce46",+ "routines.server.part.capBotMonth": "46a4cd7faf882bd055d3b7354932b7ec35491fcecc52379e098eea0d930c5e17","engines.unhideAria": "69da7203caed81388e25e663947d80d80a2f54c62d5c4b49800c7225e539a9e8","accounts.signOutCliBody": "dec35f25acc8211621523f7a2d962b28a9a3e91a3aa4864e9c4e87894d40b0a2","accounts.signOutAria": "2986263f26f5e9fe9d5e4722b51d0c989a02d3ff6875adf711e66ed3ef50f4b6",