Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
usage: report the budget the runtime enforces, not the file's snapshot (#245)
tournierjc57e9f8cd00a1
diff --git a/src/web/api/availability.test.ts b/src/web/api/availability.test.tsindex a9113305..8180bc13 100644--- a/src/web/api/availability.test.ts+++ b/src/web/api/availability.test.ts@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { tmpdir } from 'node:os';import system, { setScheduler } from './system.js';-import status from './status.js';+import status, { getStatus, updateStatus } from './status.js';import type { Scheduler } from '../../core/scheduler.js';/**@@ -57,12 +57,21 @@ describe('GET /api/usage', () => {],});- const res = await system.request('/api/usage');- const body = (await res.json()) as Record<string, unknown>;-- expect(body.available).toBe(true);- expect(body.dailyUsed).toBe(1234);- expect(body.dailyBudget).toBe(80000000);+ // A live budget announced by the runtime wins over the tracker's snapshot, so this case pins+ // the fallback: nobody announced one (`tokenBudget: 0`), and the file is the answer. The live+ // case has its own tests in usage-budget.test.ts.+ const live = getStatus().tokenBudget;+ updateStatus({ tokenBudget: 0 });+ try {+ const res = await system.request('/api/usage');+ const body = (await res.json()) as Record<string, unknown>;++ expect(body.available).toBe(true);+ expect(body.dailyUsed).toBe(1234);+ expect(body.dailyBudget).toBe(80000000);+ } finally {+ updateStatus({ tokenBudget: live });+ }});it('is NOT available when the tracker exists and cannot be read', async () => {diff --git a/src/web/api/system.ts b/src/web/api/system.tsindex b0db6d77..79616d97 100644--- a/src/web/api/system.ts+++ b/src/web/api/system.ts@@ -10,6 +10,7 @@ import { RegistryClient, isValidSkillId } from '../../skills/registry.js';import { SkillStore } from '../../skills/store.js';import { PermissionManager, type PermissionsManifest } from '../../capabilities/permissions.js';import { getMercuryHome } from '../../utils/config.js';+import { getStatus } from './status.js';import type { Scheduler } from '../../core/scheduler.js';import cron from 'node-cron';@@ -246,12 +247,18 @@ system.get('/api/usage', (c) => {byChannel[row.channelType] = (byChannel[row.channelType] || 0) + (row.totalTokens || 0);}+ // The budget the runtime enforces is the live one. The tracker file carries whatever was+ // configured the last time tokens were written, so raising the limit used to leave this endpoint+ // reporting the old number — and `remaining` computed from it — until some turn happened to+ // rewrite the file. The file stays the fallback for a runtime that never reported one.+ const live = getStatus().tokenBudget;+ const dailyBudget = Number.isFinite(live) && live > 0 ? live : (data.dailyBudget || 0);return c.json({available,dailyUsed: data.dailyUsed || 0,- dailyBudget: data.dailyBudget || 0,+ dailyBudget,lastResetDate: data.lastResetDate,- remaining: Math.max(0, (data.dailyBudget || 0) - (data.dailyUsed || 0)),+ remaining: Math.max(0, dailyBudget - (data.dailyUsed || 0)),requestLog: (data.requestLog || []).slice(-100).reverse(),byProvider,byChannel,diff --git a/src/web/api/usage-budget.test.ts b/src/web/api/usage-budget.test.tsnew file mode 100644index 00000000..4fd2af8f--- /dev/null+++ b/src/web/api/usage-budget.test.ts@@ -0,0 +1,70 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import system from './system.js';+import { updateStatus } from './status.js';++/**+ * The number the console reads for "how much is left today".+ *+ * `/api/usage` used to answer with the budget recorded in `token-usage.json` — a snapshot written+ * the last time tokens were counted — so raising the limit left the console showing the old one,+ * with a `remaining` computed from it, until some turn happened to rewrite the file. These tests+ * pin that the runtime's budget wins, and that a tracker without one still answers.+ */++let home = '';++/** The budget a bare test runtime starts with, restored after each case. */+const DEFAULT_BUDGET = 1_000_000;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-usage-budget-'));+ process.env.MERCURY_HOME = home;+});++afterEach(() => {+ updateStatus({ tokenBudget: DEFAULT_BUDGET });+ delete process.env.MERCURY_HOME;+ rmSync(home, { recursive: true, force: true });+});++const writeUsage = (payload: unknown) => writeFileSync(join(home, 'token-usage.json'), JSON.stringify(payload));++const usage = async () => {+ const res = await system.request('/api/usage');+ return (await res.json()) as Record<string, number | boolean>;+};++describe('GET /api/usage budget', () => {+ it('reports the budget the runtime enforces, not the snapshot in the tracker', async () => {+ writeUsage({ dailyUsed: 152_867_556, dailyBudget: 80_000_000, lastResetDate: '2026-10-28', requestLog: [] });+ updateStatus({ tokenBudget: 500_000_000 });++ const body = await usage();++ expect(body.dailyBudget).toBe(500_000_000);+ expect(body.remaining).toBe(500_000_000 - 152_867_556);+ });++ it('falls back to the tracker when the runtime announced no budget', async () => {+ writeUsage({ dailyUsed: 10, dailyBudget: 80_000_000, lastResetDate: '2026-10-28', requestLog: [] });+ updateStatus({ tokenBudget: 0 });++ const body = await usage();++ expect(body.dailyBudget).toBe(80_000_000);+ expect(body.remaining).toBe(80_000_000 - 10);+ });++ it('counts what has been used once, and does not invent a negative remainder', async () => {+ writeUsage({ dailyUsed: 600_000_000, dailyBudget: 1, lastResetDate: '2026-10-28', requestLog: [] });+ updateStatus({ tokenBudget: 500_000_000 });++ const body = await usage();++ expect(body.dailyBudget).toBe(500_000_000);+ expect(body.remaining).toBe(0);+ });+});