Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: 修正 bot 用量查询的权限与额度展示
Zhehui Bi540be63988a6
diff --git a/docs/usage-caps.md b/docs/usage-caps.mdindex 5647f08725..61ed423f01 100644--- a/docs/usage-caps.md+++ b/docs/usage-caps.md@@ -36,10 +36,13 @@ cost and usage cap headroom. The UTC period defaults to `today` and alsosupports `month`. Pass `thread: "this"` to limit the usage totals to thecurrent conversation.-The tool includes exact cap totals only when the calling turn can read all-usage counted toward that cap. If `capsComplete` is false, some cap totals-are unavailable in the conversation. A running turn can still read visible-headroom and the reset time after a cap is reached.+Context occupancy comes from the latest visible reading in the current+conversation, regardless of the requested usage period.++Exact cap totals are available to owner-only conversations on a single-user+server or personal Cloud. In shared conversations, `capsComplete: false` means+exact headroom is unavailable. If a cap would refuse unattended work, the tool+still shows that cap's configured limit, `reached: true` and reset time.## What a reached cap stopsdiff --git a/server/bot-usage.e2e.test.ts b/server/bot-usage.e2e.test.tsindex 5a1a5267de..cc10a82f5a 100644--- a/server/bot-usage.e2e.test.ts+++ b/server/bot-usage.e2e.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { mkdtempSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { expect, it } from "vitest";@@ -10,7 +10,7 @@ import { removeTempDir } from "./testing/cleanup.ts";import { hostTimeout } from "./testing/host-timeout.ts";import { appendUsage } from "./usage-ledger.ts";-it("reads actual headroom through an active turn's capability, even once the cap is reached", async () => {+it("shows exact headroom to a solo turn and keeps restricted usage out of a chat-only device's turn", async () => {const folder = mkdtempSync(join(tmpdir(), "omb-bot-usage-e2e-"));const gate = join(folder, "finish");let fixture: VerificationServer | undefined;@@ -38,14 +38,24 @@ it("reads actual headroom through an active turn's capability, even once the capexpect(response.status).toBe(200);};await setCap(24);- await runControlOmb(["send", "--bot", scout.id, "--task", scout.threadId, "--text", "Check usage before handing off work", "--url", url]);- let token = "";- await expect.poll(() => {- try { token = JSON.parse(readFileSync(fixtureDumpPath, "utf8")).mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN; } catch { return false; }- return Boolean(token);- }, { timeout: hostTimeout(15_000) }).toBe(true);- const client = createHarnessClient(url, token);const botUsagePath = "/api/internal/engine-limits?scope=bot";+ const activeClient = async () => {+ let active: ReturnType<typeof createHarnessClient> | undefined;+ await expect.poll(async () => {+ let token: string;+ try { token = JSON.parse(readFileSync(fixtureDumpPath, "utf8")).mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN; } catch { return false; }+ if (!token) return false;+ active = createHarnessClient(url, token);+ return (await active.apiResponse(botUsagePath)).status === 200;+ }, { timeout: hostTimeout(15_000) }).toBe(true);+ return active!;+ };+ const finishTurn = async () => {+ writeFileSync(gate, "finish");+ await runControlOmb(["wait", "--bot", scout.id, "--task", scout.threadId, "--timeout", "30", "--url", url]);+ };+ await runControlOmb(["send", "--bot", scout.id, "--task", scout.threadId, "--text", "Check usage before handing off work", "--url", url]);+ const client = await activeClient();expect((await createHarnessClient(url, "wrong").apiResponse(botUsagePath)).status).toBe(401);expect((await client.apiResponse(`${botUsagePath}&botId=${peer.id}`)).status).toBe(403);const subscription = await callUsageLimitsTool({ client });@@ -61,9 +71,57 @@ it("reads actual headroom through an active turn's capability, even once the capawait setCap(12);const reached = await callUsageLimitsTool({ client }, { scope: "bot", period: "month" });expect(JSON.parse(reached.text)).toMatchObject({ caps: [{ used: 12, remaining: 0, reached: true, resetsAt: expect.any(Number) }] });- writeFileSync(gate, "finish");- await runControlOmb(["wait", "--bot", scout.id, "--task", scout.threadId, "--timeout", "30", "--url", url]);+ await finishTurn();expect((await client.apiResponse(botUsagePath)).status).toBe(401);+ unlinkSync(gate);++ const room = await request("/api/groups", { method: "POST", body: JSON.stringify({+ name: "Restricted fixture", memberIds: [scout.id, peer.id], setup: { bulletin: "", defaultResponder: { kind: "everyone" } },+ }) });+ const roomBody = await room.json() as { group: { id: string; threadId: string }; error?: string };+ expect(room.status, roomBody.error).toBe(201);+ const { group } = roomBody;+ expect((await request(`/api/bots/${peer.id}`, { method: "PATCH", body: JSON.stringify({ visibility: "admins" }) })).status).toBe(200);+ const pairing = await request("/api/auth/pairing", { method: "POST", body: JSON.stringify({ label: "Chat phone", scopes: ["client"] }) });+ expect(pairing.status).toBe(200);+ const { code } = await pairing.json() as { code: string };+ const paired = await request("/api/auth/pair", { method: "POST", body: JSON.stringify({ code }) });+ expect(paired.status).toBe(200);+ const { token: phone } = await paired.json() as { token: string };+ const visible = await request("/api/bots?messages=0", { headers: { authorization: `Bearer ${phone}` } });+ expect(visible.status).toBe(200);+ const phoneView = await visible.text();+ expect(phoneView).toContain(scout.threadId);+ expect(phoneView).not.toContain(group.id);+ await setCap(200_000);+ const sent = await request(`/api/bots/${scout.id}/messages`, {+ method: "POST", headers: { authorization: `Bearer ${phone}` }, body: JSON.stringify({ text: "Check our usage", threadId: scout.threadId }),+ });+ expect(sent.status, await sent.text()).toBe(202);+ const phoneClient = await activeClient();+ const sharedUsage = async () => {+ const result = await callUsageLimitsTool({ client: phoneClient }, { scope: "bot", period: "month" });+ expect(result.isError).toBeUndefined();+ return JSON.parse(result.text);+ };+ const beforePrivateUsage = await sharedUsage();+ expect(beforePrivateUsage).toMatchObject({ totals: { turns: expect.any(Number) }, caps: [], capsComplete: false });+ expect(await appendUsage(dataDir, {+ at: new Date().toISOString(), botId: scout.id, botName: "Scout", threadId: group.threadId, instanceId: "test-account",+ driverKind: "claude", model: "fixture", input: 100_000, output: 2, costUsd: 1, trigger: { kind: "owner" },+ })).toBe(true);+ expect(await sharedUsage()).toEqual(beforePrivateUsage);++ expect((await request(`/api/groups/${group.id}`, { method: "PATCH", body: JSON.stringify({ memberIds: [scout.id] }) })).status).toBe(200);+ expect(await sharedUsage()).toEqual(beforePrivateUsage);++ await setCap(12);+ expect(await sharedUsage()).toEqual({+ ...beforePrivateUsage, stops: "unattended",+ caps: [{ scope: "bot", period: "month", unit: "tokens", limit: 12, reached: true, resetsAt: nextMonth.getTime() }],+ });+ await finishTurn();+ expect((await phoneClient.apiResponse(botUsagePath)).status).toBe(401);} finally {try { await fixture?.close(); } finally { await removeTempDir(folder); }}diff --git a/server/drivers/agents-usage-tool.test.ts b/server/drivers/agents-usage-tool.test.tsindex 37e3655a5e..5188a8918f 100644--- a/server/drivers/agents-usage-tool.test.ts+++ b/server/drivers/agents-usage-tool.test.ts@@ -34,6 +34,21 @@ describe("the usage_limits tool", () => {expect(asked.client.apiResponse).not.toHaveBeenCalled();});+ it("normalizes omitted and variant optional arguments before validating them", async () => {+ const asked = context({ ok: true, body: { text: "{}" } });+ await expect(callTool(USAGE_LIMITS_TOOL, { scope: " Bot ", period: null, thread: " " }, asked))+ .resolves.toEqual({ text: "{}" });+ expect(asked.client.apiResponse).toHaveBeenLastCalledWith("/api/internal/engine-limits?scope=bot");+ await callTool(USAGE_LIMITS_TOOL, { scope: "BOT", period: " MONTH ", thread: " THIS " }, asked);+ expect(asked.client.apiResponse).toHaveBeenLastCalledWith("/api/internal/engine-limits?scope=bot&period=month&thread=this");+ await callTool(USAGE_LIMITS_TOOL, { scope: null, period: "", thread: null }, asked);+ expect(asked.client.apiResponse).toHaveBeenLastCalledWith("/api/internal/engine-limits");++ await expect(callTool(USAGE_LIMITS_TOOL, { scope: "bot", period: false }, asked))+ .resolves.toEqual({ text: expect.stringContaining('{"scope":"bot","period":"today","thread":"this"}'), isError: true });+ expect(asked.client.apiResponse).toHaveBeenCalledTimes(3);+ });+it("hands the bot the route's answer, and its refusal as an error", async () => {const asked = context({ ok: true, body: { text: '{"accounts":[]}' } });await expect(callUsageLimitsTool(asked)).resolves.toEqual({ text: '{"accounts":[]}' });diff --git a/server/drivers/agents-usage-tool.ts b/server/drivers/agents-usage-tool.tsindex fd07d245b8..6f83ee07e6 100644--- a/server/drivers/agents-usage-tool.ts+++ b/server/drivers/agents-usage-tool.ts@@ -2,12 +2,22 @@ import type { ToolCallContext, ToolCallResult } from "./agents-call.ts";export const USAGE_LIMITS_TOOL = "usage_limits";+function optionalChoice(value: unknown): unknown {+ if (typeof value === "string") return value.trim().toLowerCase() || undefined;+ return value ?? undefined;+}+export async function callUsageLimitsTool(context: Pick<ToolCallContext, "client">, args: Record<string, unknown> = {}): Promise<ToolCallResult> {- const { scope, period, thread } = args;- if (scope !== undefined && scope !== "subscription" && scope !== "bot") return { text: "scope must be subscription or bot.", isError: true };- if (scope !== "bot" && (period !== undefined || thread !== undefined)) return { text: "period and thread require scope: bot.", isError: true };- if (period !== undefined && period !== "today" && period !== "month") return { text: "period must be today or month.", isError: true };- if (thread !== undefined && thread !== "this") return { text: "thread must be this or omitted.", isError: true };+ const scope = optionalChoice(args.scope);+ const period = optionalChoice(args.period);+ const thread = optionalChoice(args.thread);+ const error = (message: string): ToolCallResult => ({+ text: `${message} Try {} for subscription limits or {"scope":"bot","period":"today","thread":"this"} for bot usage.`, isError: true,+ });+ if (scope !== undefined && scope !== "subscription" && scope !== "bot") return error("scope must be subscription or bot.");+ if (scope !== "bot" && (period !== undefined || thread !== undefined)) return error("period and thread require scope: bot.");+ if (period !== undefined && period !== "today" && period !== "month") return error("period must be today or month.");+ if (thread !== undefined && thread !== "this") return error("thread must be this or omitted.");const path = "/api/internal/engine-limits";const query = new URLSearchParams({ scope: "bot", ...(period ? { period } : {}), ...(thread ? { thread } : {}) });diff --git a/server/host/visibility-host.ts b/server/host/visibility-host.tsindex abe0ed3993..bed2617d55 100644--- a/server/host/visibility-host.ts+++ b/server/host/visibility-host.ts@@ -5,7 +5,7 @@import { basename } from "node:path";import { baseBotId } from "../audience.ts";-import { audienceEquals, narrowestAudience, roomFeeds, routineRunVisible, routineVisible, SEES_EVERYTHING, VisibleSet, type PathSubject, type ThreadAudiences, type ThreadOwner, type Viewer } from "../bot-visibility.ts";+import { audienceEquals, audienceWithin, narrowestAudience, roomFeeds, routineRunVisible, routineVisible, SEES_EVERYTHING, VisibleSet, type PathSubject, type ThreadAudiences, type ThreadOwner, type Viewer } from "../bot-visibility.ts";import type { RequestAuth } from "../request-auth.ts";import type { RoutineManager } from "../routines.ts";import type { BotRecord, GroupRecord, Store } from "../store.ts";@@ -125,6 +125,21 @@ export function createVisibilityHost(deps: VisibilityHostDeps) {function roomFeedsBot(group: GroupRecord, bot: Pick<BotRecord, "visibility">): boolean {return roomFeeds([...roomMemberAudiences(group), group.audienceFloor], bot.visibility);}++ function readableByThreadAudience(threadId: string, canRead: (otherThreadId: string) => boolean): (otherThreadId: string) => boolean {+ const audienceOf = (id: string) => {+ const group = store.groupByThread(id);+ if (group) return narrowestAudience([...roomMemberAudiences(group), group.audienceFloor]);+ const bot = store.botByThread(id);+ return bot ? narrowestAudience([bot.visibility]) : null;+ };+ const audience = audienceOf(threadId);+ return (other) => {+ if (audience === null || !canRead(other)) return false;+ const source = audienceOf(other);+ return source !== null && audienceWithin(audience, source);+ };+ }/** A room's floor stays at the narrowest audience it ever had, set before a restricted bot can leave; only an admin's* explicit reset widens it. */function settleRoomFloor(group: GroupRecord): void {@@ -134,5 +149,5 @@ export function createVisibilityHost(deps: VisibilityHostDeps) {deps.store().patchGroup(group.id, { audienceFloor: next === "everyone" ? undefined : next });}- return { viewerFor, threadOwner, visibleTo, forgetVisibility, threadShown, subjectVisible, hiddenRoutineTarget, roomFeedsBot, roomMemberAudiences, settleRoomFloor };+ return { viewerFor, threadOwner, visibleTo, forgetVisibility, threadShown, subjectVisible, hiddenRoutineTarget, roomFeedsBot, readableByThreadAudience, roomMemberAudiences, settleRoomFloor };}diff --git a/server/index.ts b/server/index.tsindex 3b17319a22..283186a4e6 100644--- a/server/index.ts+++ b/server/index.ts@@ -1123,7 +1123,7 @@ async function answeringCardAs(auth: RequestAuth, threadId: string, requestId: s}}-const { viewerFor, threadOwner, visibleTo, forgetVisibility, threadShown, subjectVisible, hiddenRoutineTarget, roomFeedsBot, settleRoomFloor } = createVisibilityHost({ store: () => store, routines: () => routines,+const { viewerFor, threadOwner, visibleTo, forgetVisibility, threadShown, subjectVisible, hiddenRoutineTarget, roomFeedsBot, readableByThreadAudience, settleRoomFloor } = createVisibilityHost({ store: () => store, routines: () => routines,team: Boolean(CLOUD_TEAM), audiencesFor: (viewer) => { const audiences = teamHost.audiencesFor(viewer), person = audiences?.person; return audiences && person ? { ...audiences, routineHome: teamRoutines.home, ownTask: (task) => conversationShares.forViewer(personRooms.taskForPerson(task, person), person, teamHost.personName) } : audiences && { ...audiences, routineHome: teamRoutines.home }; }, threadsReferencing }); if (CLOUD_TEAM) hideOthersSyncFolders(() => store.bots, threadShown); const notificationListed = notificationListedFor(threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) && conversationShares.reaches(entry, auth.kind === "session" ? personKey(auth.session) : null) : undefined, CLOUD_TEAM ? (auth) => (auth.kind === "session" ? personKey(auth.session) : null) : undefined); const botAccess = createBotAccessHost({ visibleFor: (auth) => visibleTo(viewerFor(auth)), store: () => store, routines: () => routines, threadOwner, routineWriter: (id) => cloudRoutineAuthors?.writer(id) }), { levelOf } = botAccess; const accessRequests = createAccessRequests({ team: CLOUD_TEAM, store: () => store, people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, inbox: () => teamMessages.inbox, visibleTo, levelOf, writeAccess: (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access), record: (row, by) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: by, email: by } }) });function recentWorkFilter(threadId: string): { include?: (threadId: string) => boolean; privateThread?: (threadId: string) => boolean } {@@ -1208,11 +1208,7 @@ function memberFrameContext(visible: VisibleSet): FrameContext {}function adminActivityRecording(): boolean {- if (DESKTOP_MANAGED) return false;- if (HOSTED_WORKSPACE || CLOUD_TEAM) return true;- const chatOnly = (scopes: readonly string[]) => !scopes.includes("admin");- return sharedSignIn(signInAllowList()) || sessions.list().some((session) => chatOnly(session.scopes)) ||- sessions.openPairings().some((pairing) => chatOnly(pairing.scopes));+ return !DESKTOP_MANAGED && (Boolean(HOSTED_WORKSPACE || CLOUD_TEAM) || sharedSignIn(signInAllowList()) || sessions.hasChatOnlyAccess());}function adminActorFor(auth: RequestAuth, req: IncomingMessage): AdminActor {@@ -12329,7 +12325,7 @@ ROUTES.push(createBrowserViewerRoutes({restartRefusal: (session) => browserRestartRefusal(browserRuntime.interrupted(session), store.bots.filter((candidate) => candidate.busy&& browserSessionsOf(candidate.id, candidate.browserProfile).includes(session)).map((candidate) => ({ waitingOnBrowser: computerControl.snapshot(candidate.id).help?.place === "browser" }))),}));-const internalToolRoutes = createInternalToolRoutes({ botUsage: { dataDir: DATA_DIR, guestDriven: cloudGuestDriven, caps: () => cfg.usageCaps, onPlan: (id) => registry.lastSnapshot(id)?.billing === "subscription", bot: (id) => store.bot(id), readableFrom: threadReadableFrom, crossThreadReads: () => Boolean(CLOUD_HOME || ownHome.ownServer()), knownThread: (botId, threadId) => Boolean(connectorThread(botId, threadId)) }, engineLimits: { instances: () => registry.instances(), configs: () => instanceConfigs(cfg), status: (instanceId) => registry.knownSnapshot(instanceId), load: (accounts) => loadPlanUsage({ accounts }), audienceOf: (threadId) => teamHost.audienceOf(threadId), guestDriven: cloudGuestDriven, dataDir: DATA_DIR }, helpers: { decider, extractor }, notifications: { bot: (id) => store.bot(id), team: sharedMembership, broadcast }, xResearch: { credential: () => researchCredential(cfg.treg?.key), botEnabled: (botId) => store.bot(botId)?.xResearch !== false, cloudHome: CLOUD_HOME !== null, researchOff: () => researchAvailability.refused() }, appPublisher }); const waitRoutes = createWaitRoutes({ waits: botWaits, cloudHome: Boolean(CLOUD_HOME), sleeps: Boolean(CLOUD_HOME) && CLOUD_TEAM === null }); ROUTES.push(createXConnectorRoutes({ credential: () => researchCredential(cfg.treg?.key), included: () => xCredential(), unavailable: () => xResearchStatus().unavailable === true }));+const internalToolRoutes = createInternalToolRoutes({ botUsage: { dataDir: DATA_DIR, guestDriven: cloudGuestDriven, caps: () => cfg.usageCaps, onPlan: (id) => registry.lastSnapshot(id)?.billing === "subscription", readableFrom: (threadId) => readableByThreadAudience(threadId, threadReadableFrom(threadId)), crossThreadReads: () => Boolean(CLOUD_HOME || ownHome.ownServer()), canReadCapTotals: () => Boolean(ownHome.ownServer() || (CLOUD_PERSONAL && cloudHome?.solo())) && !sessions.hasChatOnlyAccess(), knownThread: (botId, threadId) => Boolean(connectorThread(botId, threadId)) }, engineLimits: { instances: () => registry.instances(), configs: () => instanceConfigs(cfg), status: (instanceId) => registry.knownSnapshot(instanceId), load: (accounts) => loadPlanUsage({ accounts }), audienceOf: (threadId) => teamHost.audienceOf(threadId), guestDriven: cloudGuestDriven, dataDir: DATA_DIR }, helpers: { decider, extractor }, notifications: { bot: (id) => store.bot(id), team: sharedMembership, broadcast }, xResearch: { credential: () => researchCredential(cfg.treg?.key), botEnabled: (botId) => store.bot(botId)?.xResearch !== false, cloudHome: CLOUD_HOME !== null, researchOff: () => researchAvailability.refused() }, appPublisher }); const waitRoutes = createWaitRoutes({ waits: botWaits, cloudHome: Boolean(CLOUD_HOME), sleeps: Boolean(CLOUD_HOME) && CLOUD_TEAM === null }); ROUTES.push(createXConnectorRoutes({ credential: () => researchCredential(cfg.treg?.key), included: () => xCredential(), unavailable: () => xResearchStatus().unavailable === true }));// Live calls: the client holds the WebRTC audio; the key never leaves the harness, which creates the session.function liveBotFor(botId: string): LiveBot {diff --git a/server/routes/bot-usage.test.ts b/server/routes/bot-usage.test.tsindex e4f6f797cb..5a0d5d25b0 100644--- a/server/routes/bot-usage.test.ts+++ b/server/routes/bot-usage.test.ts@@ -31,7 +31,7 @@ async function query(args: string, deps: Partial<Parameters<typeof createBotUsagconst json = vi.fn();const route = createBotUsageRoute({ dataDir, env: {}, now: () => now, guestDriven: () => false, caps: () => undefined,readableFrom, crossThreadReads: () => true, knownThread: (_botId, threadId) => audiences.has(threadId),- bot: (id) => ({ id, name: id }), onPlan: () => false, ...deps });+ canReadCapTotals: () => false, onPlan: () => false, ...deps });const url = new URL(`http://localhost${path}${args}`);url.searchParams.set("scope", "bot");await route({ method: "GET", path, url, res: {} as ServerResponse, json, botId, threadId: "here", requireActive() {} });@@ -63,20 +63,46 @@ it("reports only the caller's visible usage and never returns the ledger row", aexpect((await query("", {}, "other")).result.totals).toMatchObject({ turns: 1, input: 222 });});-it("shows exact cap headroom only when all contributing rows are readable", async () => {+it("uses enforcement's cap totals for a reply authorized to read the entire cap scope", async () => {await appendUsage(dataDir, row({ costUsd: 0.01 }));await appendUsage(dataDir, row({ threadId: "private", costUsd: 0.10 }));const caps = () => ({ server: { dailyUsd: 0.20 }, bots: { scout: { dailyTokens: 18, monthlyUsd: 0.11 }, other: { dailyTokens: 45 } } });- const own = await query("", { caps, readableFrom: () => () => true });+ const own = await query("?thread=this", { caps, canReadCapTotals: () => true });expect(own.result.capsComplete).toBe(true);expect(own.result.caps).toEqual([expect.objectContaining({ scope: "server", used: 0.11, reached: false }),expect.objectContaining({ scope: "bot", unit: "usd", remaining: 0, reached: true, resetsAt: Date.parse("2026-12-01T00:00:00Z") }),expect.objectContaining({ scope: "bot", unit: "tokens", used: 18, remaining: 0, reached: true, resetsAt: Date.parse("2026-11-19T00:00:00Z") }),]);- const shared = await query("", { caps });- expect(shared.result).toMatchObject({ caps: [], capsComplete: false, stops: null, totals: { turns: 1, costUsd: 0.01 } });- expect(shared.body.text).not.toContain("0.11");+ expect(own.result.totals).toMatchObject({ turns: 1, costUsd: 0.01 });+});++it("keeps cap output stable for hidden usage until the cap that would block work is reached", async () => {+ await appendUsage(dataDir, row({ costUsd: 0.01 }));+ const caps = () => ({ bots: { scout: { dailyTokens: 20, monthlyTokens: 28 } } });+ const initial = await query("", { caps });+ expect(initial.result).toMatchObject({ caps: [], capsComplete: false, stops: null, totals: { turns: 1, costUsd: 0.01 } });+ await appendUsage(dataDir, row({ threadId: "private", input: 9, output: 0, cachedInput: 0 }));+ const read = (seconds: number) => query("", { caps, now: () => new Date(now.getTime() + seconds * 1000) });+ expect((await read(20)).result).toEqual(initial.result);++ await appendUsage(dataDir, row({ at: "2026-11-18T13:00:00Z", threadId: "private", input: 20, output: 0, cachedInput: 0 }));+ const reached = await read(40);+ expect(reached.result.caps).toEqual([+ { scope: "bot", period: "month", unit: "tokens", limit: 28, reached: true, resetsAt: Date.parse("2026-12-01T00:00:00Z") },+ ]);+ expect(reached.result).toMatchObject({ capsComplete: false, stops: "unattended", totals: { turns: 1, costUsd: 0.01 } });+});++it("keeps the current conversation's latest context across the UTC month boundary", async () => {+ await appendUsage(dataDir, row({ at: "2026-10-30T23:59:59Z", contextTokens: 18, contextWindow: 120 }));+ await appendUsage(dataDir, row({ at: "2026-10-31T23:59:59Z", contextTokens: 53, contextWindow: 120 }));+ await appendUsage(dataDir, row({ at: "2026-11-01T00:00:00Z", threadId: "private", contextTokens: 90, contextWindow: 200 }));+ await appendUsage(dataDir, row({ at: "2026-11-02T00:00:00Z", contextTokens: 100, contextWindow: 120 }));+ const deps = { now: () => new Date("2026-11-01T00:05:00Z") };+ const expected = { totals: { turns: 0 }, context: { contextTokens: 53, contextWindow: 120 } };+ expect((await query("", deps)).result).toMatchObject(expected);+ expect((await query("?period=month&thread=this", deps)).result).toMatchObject(expected);});it("refuses guest turns and unbounded filters", async () => {@@ -89,7 +115,7 @@ it("refuses guest turns and unbounded filters", async () => {it("reports a failed month read without claiming zero usage or full headroom", async () => {const caps = () => ({ server: { dailyTokens: 20 } });- expect((await query("", { caps })).result.caps[0]).toMatchObject({ used: 0, remaining: 20 });+ expect((await query("", { caps, canReadCapTotals: () => true })).result.caps[0]).toMatchObject({ used: 0, remaining: 20 });mkdirSync(join(dataDir, "usage", "2026-11.jsonl"), { recursive: true });const failed = await query("", { caps });expect(failed.status).toBe(503);diff --git a/server/routes/bot-usage.ts b/server/routes/bot-usage.tsindex 71c76b3573..4959052d27 100644--- a/server/routes/bot-usage.ts+++ b/server/routes/bot-usage.ts@@ -1,9 +1,8 @@import type { ServerResponse } from "node:http";import type { json as sendJson } from "../harness/http.ts";-import { canReach, type RosterMember } from "../peer-roster.ts";-import { capStates, capTokens, dayKey, effectiveCaps, type CapState, type UsageCapsConfig } from "../usage-caps.ts";-import { flushUsageLedger, parseUsageRange, readUsage, summarizeUsage, type UsageRow } from "../usage-ledger.ts";+import { blockingCap, capStates, dayKey, effectiveCaps, type CapState, type UsageCapsConfig } from "../usage-caps.ts";+import { flushUsageLedger, parseUsageRange, readLatestUsage, readUsage, summarizeUsage, type UsageRow } from "../usage-ledger.ts";import { PASS } from "./table.ts";import { notBilledShare } from "./usage.ts";@@ -13,7 +12,7 @@ interface BotUsageDeps {readableFrom(threadId: string): (otherThreadId: string) => boolean;crossThreadReads(): boolean;knownThread(botId: string, threadId: string): boolean;- bot(botId: string): RosterMember | null;+ canReadCapTotals(threadId: string): boolean;caps(): UsageCapsConfig | undefined;onPlan(instanceId: string): boolean;env?: NodeJS.ProcessEnv;@@ -22,42 +21,27 @@ interface BotUsageDeps {const GUEST_REFUSAL = "Bot usage belongs to this workspace, and this conversation was started by someone else.";-function visibleUsageRows(rows: UsageRow[], deps: BotUsageDeps, botId: string, threadId: string): Set<UsageRow> {- const caller = deps.bot(botId);+function usageReadableFrom(deps: BotUsageDeps, botId: string, threadId: string, currentOnly: boolean) {const canReadThread = deps.readableFrom(threadId);- const crossThread = deps.crossThreadReads();- const checked = new Map<string, Map<string, boolean>>();- return new Set(rows.filter((row) => {- if (typeof row.threadId !== "string" || !row.threadId || (!crossThread && row.threadId !== threadId)) return false;- let threads = checked.get(row.botId);- if (!threads) checked.set(row.botId, threads = new Map());- const cached = threads.get(row.threadId);+ const checked = new Map<string, boolean>();+ return (other: string): boolean => {+ if (typeof other !== "string" || !other || (currentOnly && other !== threadId)) return false;+ const cached = checked.get(other);if (cached !== undefined) return cached;- const source = deps.bot(row.botId);- const visible = Boolean(caller && source && (source.id === caller.id || canReach(caller, source))- && deps.knownThread(row.botId, row.threadId) && canReadThread(row.threadId) && !deps.guestDriven(row.threadId));- threads.set(row.threadId, visible);+ const visible = deps.knownThread(botId, other) && canReadThread(other) && !deps.guestDriven(other);+ checked.set(other, visible);return visible;- }));+ };}-function capUsedBy(row: UsageRow, cap: CapState): number {- if (cap.unit === "tokens") return capTokens(row);- return typeof row.costUsd === "number" && Number.isFinite(row.costUsd) && row.costUsd > 0 ? row.costUsd : 0;+function capStatus(cap: CapState) {+ const { scope, period, unit, limit, reached, resetsAt } = cap;+ return { scope, period, unit, limit, reached, resetsAt };}-function visibleCap(cap: CapState, rows: UsageRow[], visible: ReadonlySet<UsageRow>) {- const { scope, period, unit, limit, used, percent, warn, reached, resetsAt } = cap;- let visibleUsed = 0;- for (const row of rows) {- if (!row.at.startsWith(cap.periodKey) || (scope === "bot" && row.botId !== cap.botId)) continue;- const amount = capUsedBy(row, cap);- if (amount > 0 && !visible.has(row)) return null;- visibleUsed += amount;- }- // Never disclose a cap total that includes a contribution outside the visible ledger snapshot.- if (visibleUsed !== used) return null;- return { scope, period, unit, limit, used, remaining: Math.max(0, limit - used), percent, warn, reached, resetsAt };+function capHeadroom(cap: CapState) {+ const { used, limit, percent, warn } = cap;+ return { ...capStatus(cap), used, remaining: Math.max(0, limit - used), percent, warn };}export function createBotUsageRoute(deps: BotUsageDeps) {@@ -81,23 +65,27 @@ export function createBotUsageRoute(deps: BotUsageDeps) {} catch {return void ctx.json(ctx.res, 503, { error: "The usage ledger could not be read. Try again shortly." });}- const visible = visibleUsageRows(ledger, deps, ctx.botId, ctx.threadId);+ const readable = usageReadableFrom(deps, ctx.botId, ctx.threadId, thread === "this" || !deps.crossThreadReads());const today = dayKey(now);- const rows = [...visible].filter((row) => row.botId === ctx.botId- && (period === "month" || row.at.startsWith(today)) && (thread === null || row.threadId === ctx.threadId));+ const rows = ledger.filter((row) => row.botId === ctx.botId+ && (period === "month" || row.at.startsWith(today)) && readable(row.threadId));const { turns, input, output, cachedInput, barTokens, costUsd, unpriced } = summarizeUsage(rows, "bot").total;- const latest = rows.filter((row) => row.threadId === ctx.threadId && Number.isFinite(row.contextTokens) && Number.isFinite(row.contextWindow))- .reduce<UsageRow | undefined>((previous, row) => !previous || row.at >= previous.at ? row : previous, undefined);+ const currentReadable = readable(ctx.threadId);+ const latest = currentReadable ? readLatestUsage(deps.dataDir, now, (row) => row.botId === ctx.botId && row.threadId === ctx.threadId+ && Number.isFinite(row.contextTokens) && Number.isFinite(row.contextWindow)) : undefined;const config = deps.caps();const states = capStates(config, deps.dataDir, now, deps.env, ctx.botId);- const caps = states.map((cap) => visibleCap(cap, ledger, visible)).filter((cap) => cap !== null);+ const exactCaps = currentReadable && deps.canReadCapTotals(ctx.threadId);+ // A shared reply can carry only the cap details that a refusal would disclose.+ const blocking = exactCaps ? null : blockingCap(states);+ const caps = exactCaps ? states.map(capHeadroom) : blocking ? [capStatus(blocking)] : [];return void ctx.json(ctx.res, 200, { text: JSON.stringify({period, thread: thread ?? "visible", timeZone: "UTC",totals: { turns, input, output, cachedInput, barTokens, costUsd, unpricedTurns: unpriced, notBilled: notBilledShare(rows, deps.onPlan) },context: latest ? { contextTokens: latest.contextTokens, contextWindow: latest.contextWindow } : null,- caps, capsComplete: states.length === caps.length, stops: caps.length ? effectiveCaps(config, deps.env).stops : null,- note: "Usage covers settled turns visible to this conversation. Dollar amounts are estimates; unpriced turns have no cost estimate. An incomplete cap list means some cap totals are unavailable here.",+ caps, capsComplete: exactCaps || states.length === 0, stops: caps.length ? effectiveCaps(config, deps.env).stops : null,+ note: "Usage covers settled turns visible to this conversation. Dollar amounts are estimates; unpriced turns have no cost estimate. When exact headroom is unavailable, only the cap that would refuse work is shown.",}) });};}diff --git a/server/sessions.ts b/server/sessions.tsindex d620760bf7..bb818bbc95 100644--- a/server/sessions.ts+++ b/server/sessions.ts@@ -396,6 +396,12 @@ export class SessionRegistry {return this.pairings.map((p) => ({ id: p.id, label: p.label, scopes: [...p.scopes], createdAt: p.createdAt, expiresAt: p.expiresAt }));}+ hasChatOnlyAccess(): boolean {+ this.prune();+ const chatOnly = ({ scopes }: Pick<SessionRecord, "scopes">) => !scopes.includes("admin");+ return this.sessions.some(chatOnly) || this.pairings.some(chatOnly);+ }+/** Only a browser sign-in's 256-bit credential matches, so this consumes nothing and counts toward no lockout. */previewBrowserSignIn(credential: string): { owner: string | null; expiresAt: number } | null {this.prune();diff --git a/server/usage-caps.ts b/server/usage-caps.tsindex 5edc6811da..a3eba707f3 100644--- a/server/usage-caps.ts+++ b/server/usage-caps.ts@@ -249,12 +249,16 @@ export function capStates(saved: UsageCapsConfig | undefined, dataDir: string, nreturn [...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. */+/** Of several reached caps, the one that resets last: the work cannot start before it does. */+export function blockingCap(states: readonly CapState[]): CapState | null {+ return states.reduce<CapState | null>((blocking, state) =>+ state.reached && (!blocking || state.resetsAt > blocking.resetsAt) ? state : blocking, null);+}++/** The reached cap that keeps this work from starting, or null. A person's own message is stopped only by `everything`. */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;+ return blockingCap(capStates(saved, dataDir, now, env, work.botId ?? ""));}/** What the harness already knows of the conversation a turn runs in. */diff --git a/server/usage-ledger.ts b/server/usage-ledger.tsindex 34a523a5d9..53d200888a 100644--- a/server/usage-ledger.ts+++ b/server/usage-ledger.ts@@ -1,6 +1,6 @@// Append-only usage rows under <data>/usage/ (0600): bookkeeping never fails the turn, and rows never carry message text.import { personOf } from "./usage-attribution.ts";-import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";+import { closeSync, fstatSync, openSync, readdirSync, readFileSync } from "node:fs";import { appendFile, mkdir } from "node:fs/promises";import { join } from "node:path";import type { TraceParent, TraceStatus, TraceUsageStatus } from "../shared/usage-trace.ts";@@ -241,6 +241,31 @@ export function readUsage(dataDir: string, range: { from: Date; to: Date }, { rereturn rows;}+export function readLatestUsage(dataDir: string, now: Date, matches: (row: UsageRow) => boolean): UsageRow | undefined {+ const directory = join(dataDir, DIR);+ const current = `${monthKey(now)}.jsonl`;+ const before = now.getTime();+ const latestIn = (file: string) => {+ let latestAt = -Infinity;+ let latest: UsageRow | undefined;+ for (const { at, row } of monthRows(join(directory, file), false)) {+ if (at <= before && at >= latestAt && matches(row)) {+ latestAt = at;+ latest = row;+ }+ }+ return latest;+ };+ const latest = latestIn(current);+ if (latest) return latest;+ let files: string[];+ try { files = readdirSync(directory); } catch { return undefined; }+ for (const file of files.filter((name) => /^\d{4}-\d{2}\.jsonl$/.test(name) && name < current).sort().reverse()) {+ const row = latestIn(file);+ if (row) return row;+ }+}+export function parseUsageRange(from: string | null | undefined, to: string | null | undefined, now = new Date()): { from: Date; to: Date } | null {const day = /^(\d{4})-(\d{2})-(\d{2})$/;const parse = (value: string, endOfDay: boolean): Date | null => {