Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(budget): BudgetTracker capSource; unpriced models hard-fail only under a user cap

garrytan3c75ceee60ab
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index aacfa1d1f9..e7fb86de4a 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -190,6 +190,7 @@
"test/brainstorm/save.test.ts": 1598,
"test/budget-meter-fail-closed.test.ts": 481,
"test/budget-meter.test.ts": 10,
+ "test/budget-tracker-cap-source.test.ts": 1,
"test/budget/free-local-chat-pricing.test.ts": 4,
"test/budget/pricing-overrides.test.ts": 5,
"test/build-llms.test.ts": 9,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 3ed4c14d2e..83eb9d43e9 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -804,6 +804,7 @@
"unit:test/brainstorm/model-config.test.ts": 416,
"unit:test/brainstorm/save.test.ts": 3165,
"unit:test/budget-meter.test.ts": 338,
+ "unit:test/budget-tracker-cap-source.test.ts": 500,
"unit:test/budget/free-local-chat-pricing.test.ts": 262,
"unit:test/budget/pricing-overrides.test.ts": 169,
"unit:test/build-llms.test.ts": 185,
diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.ts
index 8ad381dd61..560d818bf0 100644
--- a/src/core/budget/budget-tracker.ts
+++ b/src/core/budget/budget-tracker.ts
@@ -13,9 +13,14 @@
* Contracts (locked by /plan-eng-review):
* - TX1: `record()` THROWS BudgetExhausted(reason:'cost') when cumulative
* spend > maxCostUsd. The cap is a real ceiling, not a suggestion.
- * - TX2: When `maxCostUsd` is set AND the model is not in the pricing
- * maps, `reserve()` HARD-FAILS with BudgetExhausted(reason:'no_pricing').
- * When `maxCostUsd` is unset, legacy warn-once behavior is preserved.
+ * - TX2: When a USER cap is set (`capSource: 'user'`, the default for an
+ * explicit `maxCostUsd`) AND the model is not in the pricing maps,
+ * `reserve()` HARD-FAILS with BudgetExhausted(reason:'no_pricing') whose
+ * `fix` registers the rate. A `derived` or `default` cap (A4) warns once
+ * and runs the model unmetered; so does an unset cap (legacy warn-once).
+ * - A4: exhausting a `derived` cap logs `derived_cap_exhausted` to the
+ * agent-contract log; callers report it with consent.ts's
+ * derivedCapExhaustedError (checkpoint + resume command, exit 1).
* - A3 amended: `record()` is best called from try/finally on every
* gateway site. When the call threw without usage, callers feed
* `extractUsageFromError(err, fallback)` — fallback is the pessimistic
@@ -42,7 +47,10 @@ import {
type PricingOverrides,
} from './reservation-cost.ts';
import { ModelLedger, type ModelUsageRow } from './models-used.ts';
-import { noPricingGuidance, noPricingMessage, pricingSetCommand, type NoPricingGuidance } from './no-pricing.ts';
+import { noPricingFix, noPricingGuidance, noPricingMessage, pricingSetCommand, type NoPricingGuidance } from './no-pricing.ts';
+import { recordAgentContractEvent } from '../agent-contract-log.ts';
+import type { Action, Transport } from '../agent-output.ts';
+import type { CapSource } from '../consent.ts';
export { isModelPriceable } from './reservation-cost.ts';
export type { BudgetKind, PricingOverrides, NoPricingGuidance };
@@ -107,6 +115,14 @@ export interface BudgetTrackerOpts {
* Models with neither a table row nor an override stay fail-closed.
*/
pricingOverrides?: PricingOverrides;
+ /**
+ * A4: where `maxCostUsd` came from. `user` (an explicit flag or configured
+ * cap; the default whenever `maxCostUsd` is set) hard-fails an unpriced
+ * model; `derived` (estimate x1.5 under `--yes`) and `default` warn and run.
+ */
+ capSource?: CapSource;
+ /** Caller's transport, for the no_pricing fix's actor (default `cli`). */
+ transport?: Transport;
}
/**
@@ -172,9 +188,13 @@ export class BudgetExhausted extends Error {
modelId?: string;
/** Set when reason is 'no_pricing': the lookup-and-register guidance (no-pricing.ts). */
pricing?: NoPricingGuidance;
+ /** A4: the exhausted cap's source (cost and no_pricing reasons). */
+ capSource?: CapSource;
+ /** Agent contract v1: the next step (no_pricing: register the rate). */
+ fix?: Action;
constructor(
message: string,
- opts: { reason: BudgetReason; spent: number; cap: number; modelId?: string; pricing?: NoPricingGuidance },
+ opts: { reason: BudgetReason; spent: number; cap: number; modelId?: string; pricing?: NoPricingGuidance; capSource?: CapSource; fix?: Action },
) {
super(message);
this.name = 'BudgetExhausted';
@@ -183,6 +203,8 @@ export class BudgetExhausted extends Error {
this.cap = opts.cap;
this.modelId = opts.modelId;
if (opts.pricing) this.pricing = opts.pricing;
+ if (opts.capSource) this.capSource = opts.capSource;
+ if (opts.fix) this.fix = opts.fix;
}
}
@@ -250,6 +272,12 @@ export class BudgetTracker {
return this.opts.maxCostUsd;
}
+ /** A4: the cap's source; an explicit cap with no declared source is a user cap (pre-A4 behaviour). */
+ get capSource(): CapSource | undefined {
+ if (this.opts.maxCostUsd === undefined) return undefined;
+ return this.opts.capSource ?? 'user';
+ }
+
/**
* Register a synchronous callback to fire the first time the tracker
* throws BudgetExhausted (from reserve OR record). Fires once. Useful for
@@ -283,7 +311,7 @@ export class BudgetTracker {
);
if (projected === null) {
- if (this.opts.maxCostUsd !== undefined) {
+ if (this.opts.maxCostUsd !== undefined && this.capSource === 'user') {
// TX2: hard-fail when a cap is set but pricing is missing — without
// pricing we can't enforce the cap, and silently ignoring it would
// void the contract. The refusal tells the agent to look the rate up
@@ -313,15 +341,20 @@ export class BudgetTracker {
cap: this.opts.maxCostUsd,
modelId: estimate.modelId,
pricing,
+ capSource: 'user',
+ fix: noPricingFix(pricing, this.opts.transport),
});
}
- // Legacy warn-once path — cap unset.
+ // Warn-once path — cap unset, or a derived/default cap (A4: new models must run).
const memoKey = `${estimate.modelId}:${estimate.kind}`;
if (!_unpricedWarnings.has(memoKey)) {
_unpricedWarnings.add(memoKey);
+ const gate = this.opts.maxCostUsd === undefined
+ ? 'Running it without a cost gate'
+ : `The ${this.capSource} $${this.opts.maxCostUsd.toFixed(2)} cap can't meter it, so it runs unmetered`;
process.stderr.write(
`[budget] BUDGET_TRACKER_NO_PRICING: model "${estimate.modelId}" (kind=${estimate.kind}) not in pricing maps. ` +
- `Running it without a cost gate; to meter it, register its rate: ${pricingSetCommand(estimate.modelId, estimate.kind)}\n`,
+ `${gate}; to meter it, register its rate: ${pricingSetCommand(estimate.modelId, estimate.kind)}\n`,
);
}
appendAuditLine(this.auditPath, {
@@ -354,11 +387,10 @@ export class BudgetTracker {
outstanding_usd: this.outstandingUsd,
max_cost_usd: this.opts.maxCostUsd,
});
- this.fireExhausted();
- throw new BudgetExhausted(
+ throw this.costExhausted(
`${this.opts.label}: projected cost $${after.toFixed(4)} exceeds --max-cost $${this.opts.maxCostUsd.toFixed(2)} ` +
`(cumulative $${this.cumulativeUsd.toFixed(4)} + outstanding $${this.outstandingUsd.toFixed(4)} + this call $${projected.toFixed(4)})`,
- { reason: 'cost', spent: this.cumulativeUsd, cap: this.opts.maxCostUsd, modelId: estimate.modelId },
+ this.opts.maxCostUsd, estimate.modelId,
);
}
// Admission passed — hold the projection until record() settles it so
@@ -458,10 +490,9 @@ export class BudgetTracker {
if (this.opts.maxCostUsd !== undefined && this.cumulativeUsd > this.opts.maxCostUsd) {
// TX1: hard-throw — a single under-estimated call exceeded the cap.
- this.fireExhausted();
- throw new BudgetExhausted(
+ throw this.costExhausted(
`${this.opts.label}: cumulative cost $${this.cumulativeUsd.toFixed(4)} exceeded --max-cost $${this.opts.maxCostUsd.toFixed(2)} after recording ${kind} call to ${actual.modelId}`,
- { reason: 'cost', spent: this.cumulativeUsd, cap: this.opts.maxCostUsd, modelId: actual.modelId },
+ this.opts.maxCostUsd, actual.modelId,
);
}
}
@@ -528,6 +559,15 @@ export class BudgetTracker {
}
}
+ /** The cost-cap BudgetExhausted; a derived cap's exhaustion is logged to E11 (A4). */
+ private costExhausted(message: string, cap: number, modelId: string): BudgetExhausted {
+ this.fireExhausted();
+ if (this.capSource === 'derived') {
+ recordAgentContractEvent({ command: this.opts.label, transport: this.opts.transport ?? 'cli', code: 'derived_cap_exhausted', effects: ['paid'], outcome: 'stopped' });
+ }
+ return new BudgetExhausted(message, { reason: 'cost', spent: this.cumulativeUsd, cap, modelId, capSource: this.capSource });
+ }
+
private fireExhausted(): void {
if (this.exhaustedFired) return;
this.exhaustedFired = true;
diff --git a/src/core/budget/no-pricing.ts b/src/core/budget/no-pricing.ts
index 59bed1bbfb..a8f9f29cae 100644
--- a/src/core/budget/no-pricing.ts
+++ b/src/core/budget/no-pricing.ts
@@ -13,6 +13,7 @@
* the brain's operator to run it.
*/
+import type { Action, Transport } from '../agent-output.ts';
import { ERROR_CATALOGUE } from '../error-catalogue.ts';
import { splitProviderModelId } from '../model-id.ts';
import type { BudgetKind } from './reservation-cost.ts';
@@ -40,12 +41,17 @@ function shellArg(value: string): string {
return /^[\w.:/@+=-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
}
+/** The registration argv for one model; `<name>` slots are the fix's `inputs`. */
+export function pricingSetArgv(modelId: string, kind: BudgetKind): string[] {
+ const rates = kind === 'chat'
+ ? ['--input', '<usd-per-1M-input-tokens>', '--output', '<usd-per-1M-output-tokens>']
+ : ['--rate', '<usd-per-1M-tokens>'];
+ return ['gbrain', 'pricing', 'set', modelId, ...rates, '--source', '<pricing-page-url>'];
+}
+
/** The registration command for one model, in the units its kind bills. */
export function pricingSetCommand(modelId: string, kind: BudgetKind): string {
- const rates = kind === 'chat'
- ? '--input <usd-per-1M-input-tokens> --output <usd-per-1M-output-tokens>'
- : '--rate <usd-per-1M-tokens>';
- return `gbrain pricing set ${shellArg(modelId)} ${rates} --source <pricing-page-url>`;
+ return pricingSetArgv(modelId, kind).map((a, i) => (i === 3 ? shellArg(a) : a)).join(' ');
}
export function noPricingGuidance(modelId: string, kind: BudgetKind): NoPricingGuidance {
@@ -84,3 +90,25 @@ export function noPricingMessage(g: NoPricingGuidance, opts: { label?: string; c
const prefix = opts.label ? `${opts.label}: ` : '';
return `${prefix}gbrain has no pricing for ${KIND_NOUN[g.kind]} model "${g.model}"${who}, so ${cap} can't be enforced. ${noPricingSteps(g)}`;
}
+
+/**
+ * The agent-contract `fix` for a `no_pricing` refusal under a user cap: the
+ * registration command with an `inputs` entry per rate to look up. Only the
+ * trusted local CLI can register a price, so the actor is `agent` on the CLI
+ * and `host_admin` on a remote transport.
+ */
+export function noPricingFix(g: NoPricingGuidance, transport: Transport = 'cli'): Action {
+ const rateInputs = g.kind === 'chat'
+ ? [{ name: 'usd-per-1M-input-tokens', how: g.lookup }, { name: 'usd-per-1M-output-tokens', how: g.lookup }]
+ : [{ name: 'usd-per-1M-tokens', how: g.lookup }];
+ return {
+ argv: pricingSetArgv(g.model, g.kind),
+ consent: [],
+ actor: transport === 'cli' ? 'agent' : 'host_admin',
+ why: `gbrain has no price for ${g.model}, so the cost cap the user set cannot be enforced; registering the rate lets the run retry under that cap.`,
+ inputs: [...rateInputs, { name: 'pricing-page-url', how: 'The provider pricing page the rates came from.' }],
+ verify: { argv: ['gbrain', 'pricing', 'list'] },
+ docs: g.docs,
+ requires_exclusive: false,
+ };
+}
diff --git a/test/budget-tracker-cap-source.test.ts b/test/budget-tracker-cap-source.test.ts
new file mode 100644
index 0000000000..b22475c750
--- /dev/null
+++ b/test/budget-tracker-cap-source.test.ts
@@ -0,0 +1,129 @@
+/**
+ * A4 cap sources on BudgetTracker: an unpriced model hard-fails only under a
+ * user cap (with a `fix` that registers the rate); derived and default caps
+ * warn once and run it. A tracker built without `capSource` keeps the pre-A4
+ * behaviour (an explicit cap is a user cap). Exhausting a derived cap logs
+ * `derived_cap_exhausted` to the agent-contract log.
+ *
+ * Hermetic: tmp audit path, GBRAIN_HOME redirected per test via withEnv.
+ */
+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { BudgetExhausted, BudgetTracker, _resetBudgetTrackerWarningsForTest, type BudgetTrackerOpts } from '../src/core/budget/budget-tracker.ts';
+import { pricingSetArgv, pricingSetCommand } from '../src/core/budget/no-pricing.ts';
+import { readAgentContractEvents } from '../src/core/agent-contract-log.ts';
+import { renderAction, cliRenderContext, shellQuote } from '../src/core/agent-output.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const UNPRICED = 'mystery:some-unreleased-model';
+const PRICED = 'claude-haiku-4-5-20251001';
+
+let tmp: string;
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), 'gbrain-cap-source-'));
+ _resetBudgetTrackerWarningsForTest();
+});
+afterEach(() => rmSync(tmp, { recursive: true, force: true }));
+
+const tracker = (opts: Partial<BudgetTrackerOpts>) => new BudgetTracker({ label: 'test.run', auditPath: join(tmp, 'audit.jsonl'), ...opts });
+const reserveUnpriced = (t: BudgetTracker) => t.reserve({ modelId: UNPRICED, kind: 'chat', estimatedInputTokens: 1000, maxOutputTokens: 500 });
+
+function stderrOf(fn: () => void): string {
+ let out = '';
+ const spy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => {
+ out += typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk);
+ return true;
+ }) as typeof process.stderr.write);
+ try {
+ fn();
+ } finally {
+ spy.mockRestore();
+ }
+ return out;
+}
+
+describe('unpriced model × cap source', () => {
+ test('no capSource + explicit cap = user cap: refuses with a register-the-rate fix (pre-A4 behaviour)', () => {
+ const t = tracker({ maxCostUsd: 1 });
+ expect(t.capSource).toBe('user');
+ let err: unknown;
+ try { reserveUnpriced(t); } catch (e) { err = e; }
+ expect(err).toBeInstanceOf(BudgetExhausted);
+ const be = err as BudgetExhausted;
+ expect(be.reason).toBe('no_pricing');
+ expect(be.capSource).toBe('user');
+ expect(be.message).toContain('gbrain pricing set');
+ expect(be.fix?.argv).toEqual(pricingSetArgv(UNPRICED, 'chat'));
+ expect(be.fix?.actor).toBe('agent');
+ expect(be.fix?.inputs?.map(i => i.name)).toEqual(['usd-per-1M-input-tokens', 'usd-per-1M-output-tokens', 'pricing-page-url']);
+ for (const input of be.fix!.inputs!) expect(be.fix!.argv).toContain(`<${input.name}>`);
+ expect(renderAction(be.fix!, cliRenderContext()).next).toBe('run');
+ });
+
+ test('explicit user cap on a remote transport: the fix is for the host admin', () => {
+ let err: BudgetExhausted | undefined;
+ try { reserveUnpriced(tracker({ maxCostUsd: 1, capSource: 'user', transport: 'http' })); } catch (e) { err = e as BudgetExhausted; }
+ expect(err?.reason).toBe('no_pricing');
+ expect(err?.fix?.actor).toBe('host_admin');
+ });
+
+ test.each(['derived', 'default'] as const)('%s cap: warns once and runs the model', (capSource) => {
+ const t = tracker({ maxCostUsd: 1, capSource });
+ const out = stderrOf(() => {
+ reserveUnpriced(t);
+ reserveUnpriced(t);
+ t.record({ modelId: UNPRICED, kind: 'chat', inputTokens: 1000, outputTokens: 500 });
+ });
+ expect(out.match(/BUDGET_TRACKER_NO_PRICING/g)?.length).toBe(1);
+ expect(out).toContain(`The ${capSource} $1.00 cap can't meter it`);
+ expect(out).toContain(pricingSetCommand(UNPRICED, 'chat'));
+ expect(t.totalSpent).toBe(0);
+ });
+
+ test('no cap at all: legacy warn-once, capSource undefined', () => {
+ const t = tracker({});
+ expect(t.capSource).toBeUndefined();
+ const out = stderrOf(() => reserveUnpriced(t));
+ expect(out).toContain('Running it without a cost gate');
+ });
+});
+
+describe('priced model × cap source', () => {
+ test.each(['derived', 'default', 'user'] as const)('%s cap is still enforced on priced calls', (capSource) => {
+ const t = tracker({ maxCostUsd: 0.000001, capSource });
+ let err: BudgetExhausted | undefined;
+ try { t.reserve({ modelId: PRICED, kind: 'chat', estimatedInputTokens: 100_000, maxOutputTokens: 10_000 }); } catch (e) { err = e as BudgetExhausted; }
+ expect(err?.reason).toBe('cost');
+ expect(err?.capSource).toBe(capSource);
+ });
+
+ test('derived-cap exhaustion logs derived_cap_exhausted to E11; a user cap does not', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-cap-home-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const derived = tracker({ maxCostUsd: 0.000001, capSource: 'derived' });
+ expect(() => derived.record({ modelId: PRICED, kind: 'chat', inputTokens: 100_000, outputTokens: 10_000 })).toThrow(BudgetExhausted);
+ const user = tracker({ maxCostUsd: 0.000001, capSource: 'user', label: 'other.run' });
+ expect(() => user.record({ modelId: PRICED, kind: 'chat', inputTokens: 100_000, outputTokens: 10_000 })).toThrow(BudgetExhausted);
+ const events = readAgentContractEvents();
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ command: 'test.run', transport: 'cli', code: 'derived_cap_exhausted', effects: ['paid'], outcome: 'stopped' });
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('pricing registration argv', () => {
+ test('pricingSetCommand is rendered from pricingSetArgv (one source)', () => {
+ for (const kind of ['chat', 'embed', 'rerank'] as const) {
+ const argv = pricingSetArgv('openai:text-embedding-3-large', kind);
+ expect(pricingSetCommand('openai:text-embedding-3-large', kind)).toBe(argv.join(' '));
+ }
+ expect(pricingSetCommand("odd'model", 'chat')).toContain(shellQuote(["odd'model"]));
+ });
+});
+