Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

Budget: a zero daily budget is no ceiling, and a spent one says so (#260)

tournierjce58d1101e755
diff --git a/src/utils/redact.test.ts b/src/utils/redact.test.ts
index 64de020e..80463ea4 100644
--- a/src/utils/redact.test.ts
+++ b/src/utils/redact.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
// Secret-shaped fixtures are assembled at runtime: contiguous literals in
// this file would trip GitHub push protection's secret scanner.
const join = (...parts: string[]) => parts.join('');
-import { redactSecrets, redactDeep, registerSecretValue } from './redact.js';
+import { redactSecrets, redactDeep, registerSecretValue, userFacingAiError } from './redact.js';
describe('secret redaction', () => {
it('masks registered secret values wherever they appear', () => {
@@ -48,4 +48,20 @@ describe('secret redaction', () => {
expect((out.meta as any).responseBody).not.toContain(join('sk-', 'abcdefghijklmnopqrstuvwx'));
expect(err.message).toContain(join('sk-ant-', 'ABC')); // original untouched
});
+});
+
+describe('user-facing AI errors', () => {
+ it('names a spent token budget instead of falling back to the generic line', () => {
+ // The exact shape the daemon builds when isOverBudget() refuses a turn.
+ const refusal = new Error(
+ "I've exceeded my daily token budget (Token budget: 9,907,679 / 500,000,000 used (2%), 490,092,321 remaining).",
+ );
+ const message = userFacingAiError(refusal);
+ expect(message).toMatch(/daily token budget/);
+ expect(message).not.toMatch(/could not complete this request/);
+ });
+
+ it('keeps a provider quota error as a provider problem', () => {
+ expect(userFacingAiError(new Error('429 quota exceeded for this project'))).toMatch(/temporarily busy/);
+ });
});
\ No newline at end of file
diff --git a/src/utils/redact.ts b/src/utils/redact.ts
index 8e2341c8..7e39d0f2 100644
--- a/src/utils/redact.ts
+++ b/src/utils/redact.ts
@@ -89,6 +89,11 @@ export function userFacingAiError(error: unknown): string {
if (/context(?:_|\s|-)?length|too many tokens|maximum context|request too large|payload too large/.test(normalized)) {
return 'This request is too large for the selected model. Shorten the conversation or choose another model.';
}
+ // Before the rate-limit rule: a budget refusal is our own decision, not the provider's, and
+ // "please try again shortly" is exactly wrong advice — a ceiling does not lift by itself.
+ if (/daily token budget|token budget|budget (?:exhausted|exceeded)|exceeded (?:my|its) (?:daily )?budget/.test(normalized)) {
+ return 'Mercury has used its whole daily token budget, so it stopped answering. Raise the budget, or wait for the daily reset.';
+ }
if (/rate.?limit|too many requests|quota|capacity|overloaded|\b429\b/.test(normalized)) {
return 'The selected model is temporarily busy. Please try again shortly.';
}
diff --git a/src/utils/tokens.test.ts b/src/utils/tokens.test.ts
index 40af8da0..736494ca 100644
--- a/src/utils/tokens.test.ts
+++ b/src/utils/tokens.test.ts
@@ -2,9 +2,14 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
+import { TokenBudget } from './tokens.js';
+import type { MercuryConfig } from './config.js';
let mercuryHome = '';
+/** Only the slice TokenBudget reads: a whole config would be noise in every assertion. */
+const configWith = (dailyBudget: number) => ({ tokens: { dailyBudget } } as unknown as MercuryConfig);
+
vi.mock('./config.js', () => ({
getMercuryHome: () => mercuryHome,
saveConfig: vi.fn(),
@@ -17,8 +22,6 @@ vi.mock('./logger.js', () => ({
},
}));
-import { TokenBudget } from './tokens.js';
-
describe('TokenBudget hardening', () => {
beforeEach(() => {
mercuryHome = mkdtempSync(join(tmpdir(), 'mercury-token-test-'));
@@ -97,4 +100,37 @@ describe('TokenBudget hardening', () => {
const persisted = JSON.parse(readFileSync(usagePath, 'utf-8')) as { dailyUsed: number };
expect(persisted.dailyUsed).toBe(100);
});
+
+ it('reads a zero budget as no ceiling, not as no answers', () => {
+ const budget = new TokenBudget(configWith(0));
+ budget.recordUsage({
+ provider: 'deepseek',
+ model: 'deepseek-flash',
+ inputTokens: 900,
+ outputTokens: 100,
+ totalTokens: 1_000,
+ channelType: 'cli',
+ });
+
+ expect(budget.isOverBudget()).toBe(false);
+ expect(budget.canAfford(5_000_000)).toBe(true);
+ expect(budget.getStatusText()).toContain('no daily ceiling');
+ expect(budget.getStatusText()).not.toContain('0 remaining');
+ });
+
+ it('still refuses once a real ceiling is crossed', () => {
+ const budget = new TokenBudget(configWith(1_000));
+ budget.recordUsage({
+ provider: 'deepseek',
+ model: 'deepseek-flash',
+ inputTokens: 900,
+ outputTokens: 100,
+ totalTokens: 1_000,
+ channelType: 'cli',
+ });
+
+ expect(budget.canAfford(1)).toBe(false);
+ expect(budget.isOverBudget()).toBe(true);
+ expect(budget.getRemaining()).toBe(0);
+ });
});
\ No newline at end of file
diff --git a/src/utils/tokens.ts b/src/utils/tokens.ts
index a09fb26f..2395c030 100644
--- a/src/utils/tokens.ts
+++ b/src/utils/tokens.ts
@@ -60,8 +60,21 @@ export class TokenBudget {
}
}
+ /**
+ * A budget of zero (or less) is not a ceiling, it is the absence of one.
+ *
+ * The console has always read `dailyBudget: 0` as "unlimited", and an owner who clears the
+ * field in the app means the same thing. Comparing `used >= 0` instead turned that request
+ * into "every turn is refused from the first token" — a config that reads as *no limit* and
+ * behaves as *no answers*, with nothing in the UI able to tell the two apart.
+ */
+ private hasCeiling(): boolean {
+ return safeNumber(this.dailyBudget) > 0;
+ }
+
canAfford(estimatedTokens: number): boolean {
this.resetIfNewDay();
+ if (!this.hasCeiling()) return true;
return safeNumber(this.dailyUsed) + estimatedTokens <= safeNumber(this.dailyBudget);
}
@@ -71,6 +84,7 @@ export class TokenBudget {
this.forceNext = false;
return false;
}
+ if (!this.hasCeiling()) return false;
return safeNumber(this.dailyUsed) >= safeNumber(this.dailyBudget);
}
@@ -172,6 +186,9 @@ export class TokenBudget {
getStatusText(): string {
const used = this.sanitizeCount(this.dailyUsed);
+ if (!this.hasCeiling()) {
+ return `Token budget: ${formatNumber(used)} used today, no daily ceiling`;
+ }
const pct = Math.round(this.getUsagePercentage());
const remaining = this.getRemaining();
return `Token budget: ${formatNumber(used)} / ${formatNumber(this.dailyBudget)} used (${pct}%), ${formatNumber(remaining)} remaining`;
diff --git a/website/docs/cli-commands/in-chat-commands.mdx b/website/docs/cli-commands/in-chat-commands.mdx
index b406bd63..5ca9846a 100644
--- a/website/docs/cli-commands/in-chat-commands.mdx
+++ b/website/docs/cli-commands/in-chat-commands.mdx
@@ -38,7 +38,7 @@ Type these during a conversation with Mercury. Most work in both CLI and Telegra
| `/budget` | Show token budget status |
| `/budget override` | Override budget for one request |
| `/budget reset` | Reset usage to zero |
-| `/budget set <n>` | Change daily token budget |
+| `/budget set <n>` | Change daily token budget (`0` removes the ceiling: no limit) |
## Token Saver Mode