Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): capped jobs honor pricing.overrides (#6546)

time-attack677c356aeb91
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.md
index dc138f9bbb..87df997df0 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/delegated-policy.ts` — immutable submitted grant ceiling intersected with the current OAuth grant. Tools, explicit operation authority, source-only reads, write prefixes, concurrency and finite budget may narrow but never widen during execution; changed source/brain, revoked clients, archived sources or unusable intersections fail closed. Explicit job namespaces resolve to `wiki/agents/<job-id>/*`. Removing `submit_agent` stops the next execution boundary; explicit operation allowlists also constrain delegated tools, while legacy null operation lists preserve separately bound agent-only tools. Surface controls transport discovery. Empty tools never mean all tools. Legacy running jobs adopt the ceiling frozen in their persisted payload by grant rescope; host/current brain aliases mean the serving brain.
-- `src/core/minions/delegated-spend.ts` + `src/core/ai/invocation-guard.ts` + `guarded-generation.ts` — async-local admission (with `src/core/ai/invocation-guard.ts` available as `gbrain/ai/invocation-guard` for a companion capped evaluator) around each owned provider attempt, including nested paid tool work; unrelated local calls retain their transport behavior. Finite caps require canonical pricing and a declared input ceiling plus enforced output maximum before IO; unknown pricing/bounds refuse. Hidden SDK retries are disabled for owned attempts. Actual reported usage is settled with cache categories normalized across SDK/raw responses; absent usage remains explicit unresolved liability. The current grant is checked again under the reservation's client lock. The delegated guard nests inside an outer guard (a job's spend-group guard), so both must admit an attempt.
+- `src/core/minions/delegated-spend.ts` + `src/core/ai/invocation-guard.ts` + `guarded-generation.ts` — async-local admission (with `src/core/ai/invocation-guard.ts` available as `gbrain/ai/invocation-guard` for a companion capped evaluator) around each owned provider attempt, including nested paid tool work; unrelated local calls retain their transport behavior. Finite caps require a known price (operator `pricing.overrides` first, loaded once per guarded run, then the shipped tables; a rerank prices only by override or its embedding-table rate) and a declared input ceiling plus enforced output maximum before IO (embedding and rerank calls bill no output, so a missing `maxOutputTokens` counts as 0); unknown pricing/bounds refuse. `runWithJobSpend` uses the same pricing, and `reserveGroup` admits a known-zero call at zero remaining headroom (#6546). Hidden SDK retries are disabled for owned attempts. Actual reported usage is settled with cache categories normalized across SDK/raw responses; absent usage remains explicit unresolved liability. The current grant is checked again under the reservation's client lock. The delegated guard nests inside an outer guard (a job's spend-group guard), so both must admit an attempt.
- `src/core/minions/detached-stderr.ts` — durable stderr sink + spawn helper for `gbrain jobs supervisor start --detach`. `openDetachedStderrSink()` opens an append-mode log in the audit dir (`${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/supervisor-stderr.log`, next to the JSONL lifecycle audit), falling back to the null device, then `'ignore'`; never throws (a sink failure must not block the supervisor start). The detached supervisor gets the fd as `stdio[2]` and its worker inherits it, so ONE durable descriptor covers both processes — not a per-call EPIPE swallow. Prevents the SIGPIPE failure of inheriting the INVOKER's stderr: a short-lived automation runner closing its capture pipe after the start payload would make the worker exit 141 on its next stderr write (and could take the supervisor down writing its own crash event), leaving active jobs and DB locks stale while producers keep enqueueing. Pinned by `test/detached-stderr.test.ts`.
diff --git a/src/core/minions/budget-meter.ts b/src/core/minions/budget-meter.ts
index 29c47120d6..4b7a7e0fde 100644
--- a/src/core/minions/budget-meter.ts
+++ b/src/core/minions/budget-meter.ts
@@ -261,7 +261,8 @@ export async function reserveGroup(engine: BrainEngine, opts: GroupReserveOpts):
if (opts.capCents !== null) {
const spend = await readGroupSpend(tx, key);
const remaining = opts.capCents - spend.committedCents - spend.overdueCents;
- if (remaining <= 0) throw new GroupBudgetRefusal('exhausted', key, spend, opts.capCents);
+ const knownFree = estimated === 0 && opts.estimateKnown !== false;
+ if (remaining < 0 || remaining === 0 && !knownFree) throw new GroupBudgetRefusal('exhausted', key, spend, opts.capCents);
estimated = Math.min(estimated, remaining);
if (spend.liveCents > 0 && spend.liveCents + estimated > remaining) {
throw new GroupBudgetRefusal('pressure', key, spend, opts.capCents);
diff --git a/src/core/minions/delegated-spend.ts b/src/core/minions/delegated-spend.ts
index fa9fe3d591..1eaea338d2 100644
--- a/src/core/minions/delegated-spend.ts
+++ b/src/core/minions/delegated-spend.ts
@@ -1,6 +1,8 @@
import type { BrainEngine } from '../engine.ts';
-import { canonicalLookup } from '../model-pricing.ts';
+import { loadPricingOverrides } from '../budget/budget-tracker.ts';
+import { overrideFor, priceFor, type PricingOverrides } from '../budget/reservation-cost.ts';
import { lookupEmbeddingPrice } from '../embedding-pricing.ts';
+import type { ModelPricing } from '../model-pricing.ts';
import { withAIInvocationGuard, type AIInvocation, type AIInvocationUsage } from '../ai/invocation-guard.ts';
import { reserve, settle } from './budget-meter.ts';
import { effectiveDelegation, type DelegationSnapshot } from './delegated-policy.ts';
@@ -10,29 +12,33 @@ export class DelegationPricingError extends UnrecoverableError {
constructor(reason: string) { super(`agent_spend_unbounded: ${reason}`); this.name = 'DelegationPricingError'; }
}
-function prices(call: AIInvocation): { input: number; output: number; read: number; write: number } | null {
- if (call.kind === 'chat') {
- const p = canonicalLookup(call.model);
- if (!p) return null;
- return { input: p.input, output: p.output, read: p.cache_read ?? p.input,
- write: call.cacheWriteTtl === '1h' ? p.input * 2 : p.cache_write ?? p.input };
- }
- if (call.kind !== 'embedding') return null;
- const p = lookupEmbeddingPrice(call.model);
- return p.kind === 'known' ? { input: p.pricePerMTok, output: 0, read: 0, write: 0 } : null;
+function rowFor(call: AIInvocation, overrides?: PricingOverrides): ModelPricing | null {
+ if (call.kind === 'chat') return priceFor(call.model, 'chat', overrides)?.pricing ?? null;
+ if (call.kind === 'embedding') return priceFor(call.model, 'embed', overrides)?.pricing ?? null;
+ if (call.kind !== 'rerank') return null;
+ const known = lookupEmbeddingPrice(call.model);
+ return overrideFor(call.model, overrides) ?? (known.kind === 'known' ? { input: known.pricePerMTok, output: 0 } : null);
}
-export function maximumInvocationCents(call: AIInvocation): number | null {
- const p = prices(call);
+function prices(call: AIInvocation, overrides?: PricingOverrides): { input: number; output: number; read: number; write: number } | null {
+ const p = rowFor(call, overrides);
+ if (!p) return null;
+ return { input: p.input, output: p.output, read: p.cache_read ?? p.input,
+ write: call.cacheWriteTtl === '1h' ? p.input * 2 : p.cache_write ?? p.input };
+}
+
+export function maximumInvocationCents(call: AIInvocation, overrides?: PricingOverrides): number | null {
+ const p = prices(call, overrides);
+ const maxOutputTokens = call.maxOutputTokens ?? (call.kind === 'embedding' || call.kind === 'rerank' ? 0 : undefined);
if (!p || !Number.isSafeInteger(call.maxInputTokens) || call.maxInputTokens! < 0
- || !Number.isSafeInteger(call.maxOutputTokens) || call.maxOutputTokens! < 0) return null;
+ || !Number.isSafeInteger(maxOutputTokens) || maxOutputTokens! < 0) return null;
// Full declared input ceiling covers cache, tools and provider framing.
// 1h cache writes can cost 2x base input; reserve that worst case.
- return Math.ceil((call.maxInputTokens! * Math.max(p.input * 2, p.read, p.write) + call.maxOutputTokens! * p.output) / 100) / 100;
+ return Math.ceil((call.maxInputTokens! * Math.max(p.input * 2, p.read, p.write) + maxOutputTokens! * p.output) / 100) / 100;
}
-export function actualCents(call: AIInvocation, usage: AIInvocationUsage | null): number | null {
- const p = prices(call);
+export function actualCents(call: AIInvocation, usage: AIInvocationUsage | null, overrides?: PricingOverrides): number | null {
+ const p = prices(call, overrides);
if (!p || !usage) return null;
const values = [usage.inputTokens, usage.outputTokens, usage.cacheReadTokens ?? 0, usage.cacheWriteTokens ?? 0];
if (values.some(v => !Number.isFinite(v) || v < 0)) return null;
@@ -41,17 +47,19 @@ export function actualCents(call: AIInvocation, usage: AIInvocationUsage | null)
export function withDelegatedSpend<T>(engine: BrainEngine, snapshot: DelegationSnapshot | null, jobId: number, run: () => Promise<T>): Promise<T> {
if (!snapshot) return run();
+ let pricing: Promise<PricingOverrides | undefined> | undefined;
return withAIInvocationGuard(async call => {
const effective = await effectiveDelegation(engine, snapshot, jobId);
const cap = effective.budgetUsdPerDay === null ? null : Math.round(Number(effective.budgetUsdPerDay) * 100);
- const max = maximumInvocationCents(call);
+ const overrides = await (pricing ??= loadPricingOverrides(engine));
+ const max = maximumInvocationCents(call, overrides);
if (cap !== null && max === null) throw new DelegationPricingError(`${call.operation} has no known price and enforced maximum for ${call.model}; no provider call was made`);
const hold = await reserve(engine, { clientId: snapshot.clientId, capCents: cap,
estimatedCents: max ?? 0, estimateKnown: max !== null, model: call.model,
provider: call.model.split(':')[0] || 'unknown', jobId,
validateAdmission: async tx => { await effectiveDelegation(tx, snapshot, jobId); } });
return { async settle(usage) {
- const cents = actualCents(call, usage);
+ const cents = actualCents(call, usage, overrides);
if (cents !== null) await settle(engine, hold.reservationId, cents, call.operation);
else await engine.executeRaw(
`UPDATE mcp_spend_reservations SET usage_unknown_reason = $2 WHERE reservation_id = $1 AND status IN ('pending','expired')`,
diff --git a/src/core/minions/spend-authorization.ts b/src/core/minions/spend-authorization.ts
index 13b2f104b1..55394e1b30 100644
--- a/src/core/minions/spend-authorization.ts
+++ b/src/core/minions/spend-authorization.ts
@@ -20,6 +20,7 @@ import type { BrainEngine } from '../engine.ts';
import { shellQuote, type Action, type Effect } from '../agent-output.ts';
import { DEFAULT_PAID_CAP_USD, resumeMaxUsd, type Authorization } from '../consent.ts';
import { opError } from '../ops/contract.ts';
+import { loadPricingOverrides } from '../budget/budget-tracker.ts';
import { withAIInvocationGuard } from '../ai/invocation-guard.ts';
import { GroupBudgetRefusal, RESERVATION_TTL_MS, readGroupSpend, reserveGroup, settle, type GroupSpend } from './budget-meter.ts';
import { actualCents, maximumInvocationCents } from './delegated-spend.ts';
@@ -290,8 +291,9 @@ export async function runWithJobSpend<T>(
const capCents = cents(record.cap_usd!);
const seen: { refusal: SpendGroupRefusedError | SpendGroupPressureError | null } = { refusal: null };
let warned = false;
+ const pricingOverrides = await loadPricingOverrides(engine);
const guard = async (call: Parameters<Parameters<typeof withAIInvocationGuard>[0]>[0]) => {
- const max = maximumInvocationCents(call);
+ const max = maximumInvocationCents(call, pricingOverrides);
if (max === null) {
if (record.cap_source === 'user') throw (seen.refusal = await spendRefusal(engine, job, record, { kind: 'no_pricing', model: call.model }));
if (!warned) {
@@ -311,7 +313,7 @@ export async function runWithJobSpend<T>(
throw (seen.refusal = await spendRefusal(engine, job, record, { kind: 'cost', overdueHolds: true }));
}
return { async settle(usage: Parameters<typeof actualCents>[1]) {
- const c = actualCents(call, usage);
+ const c = actualCents(call, usage, pricingOverrides);
if (c !== null) await settle(engine, hold.reservationId, c, call.operation);
else await engine.executeRaw(
`UPDATE mcp_spend_reservations SET usage_unknown_reason = $2 WHERE reservation_id = $1 AND status IN ('pending','expired')`,
diff --git a/test/minions-delegated-pricing.test.ts b/test/minions-delegated-pricing.test.ts
new file mode 100644
index 0000000000..6a64ba20f0
--- /dev/null
+++ b/test/minions-delegated-pricing.test.ts
@@ -0,0 +1,33 @@
+import { expect, test } from 'bun:test';
+import { actualCents, maximumInvocationCents } from '../src/core/minions/delegated-spend.ts';
+import type { AIInvocation } from '../src/core/ai/invocation-guard.ts';
+
+const call = (c: Partial<AIInvocation> & Pick<AIInvocation, 'kind' | 'model'>) => ({ operation: 'test', ...c }) as AIInvocation;
+
+test('#6546 a known-price embedding with no maxOutputTokens has a finite maximum', () => {
+ expect(maximumInvocationCents(call({ kind: 'embedding', model: 'openai:text-embedding-3-small', maxInputTokens: 1_000_000 }))).toBeGreaterThan(0);
+});
+
+test('#6546 pricing.overrides prices chat and rerank routes the tables cannot', () => {
+ const chat = call({ kind: 'chat', model: 'litellm:quality', maxInputTokens: 1000, maxOutputTokens: 1000 });
+ const rerank = call({ kind: 'rerank', model: 'litellm:rerank-local', maxInputTokens: 1000 });
+ expect(maximumInvocationCents(chat)).toBeNull();
+ expect(maximumInvocationCents(rerank)).toBeNull();
+ const overrides = { 'litellm:quality': { input: 0, output: 0 }, 'litellm:rerank-local': { input: 0, output: 0 } };
+ expect(maximumInvocationCents(chat, overrides)).toBe(0);
+ expect(maximumInvocationCents(rerank, overrides)).toBe(0);
+ const paid = { 'litellm:quality': { input: 100, output: 100 } };
+ expect(maximumInvocationCents(chat, paid)).toBe(30);
+ expect(actualCents(chat, { inputTokens: 1000, outputTokens: 50 }, paid)).toBe(10.5);
+});
+
+test('#6546 an override row keeps the table cache-write semantics', () => {
+ const overrides = { 'litellm:quality': { input: 1, output: 1, cache_read: 0.1, cache_write: 1.25 } };
+ const chat = call({ kind: 'chat', model: 'litellm:quality', maxInputTokens: 1000, maxOutputTokens: 0, cacheWriteTtl: '1h' });
+ expect(actualCents(chat, { inputTokens: 0, outputTokens: 0, cacheReadTokens: 1000, cacheWriteTokens: 1000 }, overrides)).toBe(0.21);
+ expect(actualCents({ ...chat, cacheWriteTtl: undefined }, { inputTokens: 0, outputTokens: 0, cacheReadTokens: 1000, cacheWriteTokens: 1000 }, overrides)).toBe(0.135);
+});
+
+test('#6546 an unpriced route stays unpriced', () => {
+ expect(maximumInvocationCents(call({ kind: 'chat', model: 'example:unpriced-model', maxInputTokens: 10, maxOutputTokens: 10 }), {})).toBeNull();
+});
diff --git a/test/minions-spend-authorization.serial.test.ts b/test/minions-spend-authorization.serial.test.ts
index 47cb161789..1746011019 100644
--- a/test/minions-spend-authorization.serial.test.ts
+++ b/test/minions-spend-authorization.serial.test.ts
@@ -49,6 +49,7 @@ afterAll(async () => {
});
beforeEach(async () => {
+ await engine.setConfig('pricing.overrides', '');
for (const t of ['mcp_spend_reservations', 'mcp_spend_log', 'minion_lease_pressure_log', 'minion_jobs']) await engine.executeRaw(`DELETE FROM ${t}`);
});
@@ -144,6 +145,38 @@ describe('unpriced models', () => {
});
});
+describe('operator pricing under a user cap', () => {
+ test('a registered zero-price local route runs and settles at zero', async () => {
+ await engine.setConfig('pricing.overrides', '{"litellm:quality":{"input":0,"output":0}}');
+ let called = false;
+ const spend = group(0.05, 'user', 1);
+ const [job] = await runJobs('subagent', async () => {
+ await invokeAI({ operation: 'test', kind: 'chat', model: 'litellm:quality', maxInputTokens: 1000, maxOutputTokens: 100 },
+ async () => { called = true; return 'ok'; }, () => ({ inputTokens: 900, outputTokens: 50 }));
+ }, [{ data: {}, spend }]);
+ expect(called).toBe(true);
+ expect(job!.status).toBe('completed');
+ const costs = await readGroupSpend(engine, `group:${spend.group_id}`);
+ expect(costs.committedCents).toBe(0);
+ expect(costs.liveCents).toBe(0);
+ });
+
+ test('a nonzero override is metered and stops the next call when the group is spent', async () => {
+ await engine.setConfig('pricing.overrides', '{"litellm:quality":{"input":100,"output":100}}');
+ let called = 0;
+ const spend = group(0.05, 'user', 1);
+ const [job] = await runJobs('subagent', async () => {
+ for (let i = 0; i < 2; i++) await invokeAI({ operation: 'test', kind: 'chat', model: 'litellm:quality', maxInputTokens: 1000, maxOutputTokens: 100 },
+ async () => { called++; return 'ok'; }, () => ({ inputTokens: 1000, outputTokens: 50 }));
+ }, [{ data: {}, spend }]);
+ expect(called).toBe(1);
+ expect(job!.status).toBe('dead');
+ expect(job!.error_text).toStartWith('cost_cap_exceeded:');
+ expect((await readGroupSpend(engine, `group:${spend.group_id}`)).committedCents).toBe(10.5);
+ });
+
+});
+
describe('enrich under a spend authorization', () => {
test('an exhausted enrich job dies instead of completing, and a rerun with a higher cap inserts a fresh group', async () => {
const spend = jobSpendAuthorization(auth(0.75, 'derived'), { command: 'enrich', of: 1, argv: ['gbrain', 'enrich', '--background', '--source', 'default'] });
diff --git a/test/minions-spend-authorization.test.ts b/test/minions-spend-authorization.test.ts
index f270dba905..3b01461e51 100644
--- a/test/minions-spend-authorization.test.ts
+++ b/test/minions-spend-authorization.test.ts
@@ -187,3 +187,36 @@ describe('uncapped records', () => {
expect(await engine.executeRaw('SELECT 1 FROM mcp_spend_reservations')).toEqual([]);
});
});
+
+// Protect registered operator pricing in a user-capped worker, which canonical-only
+// tests do not cover. Reverting override loading refuses before IO or fails settlement.
+// Uses the existing production invocation guard and isolated PGLite, no new seam.
+test('a user-capped job admits and settles a registered zero-price local model', async () => {
+ const previous = await engine.getConfig('pricing.overrides');
+ await engine.setConfig('pricing.overrides', JSON.stringify({ 'litellm:local-test': { input: 0, output: 0 }, 'llama-server-reranker:local-test': 0 }));
+ try {
+ const job = await claimed('subagent', {}, record(0.000001, 'user'));
+ let calls = 0;
+ await runWithJobSpend(engine, job, ctxFor(job), async () => invokeAI(
+ { operation: 'test-local', kind: 'chat', model: 'litellm:local-test', maxInputTokens: 10000, maxOutputTokens: 1000 },
+ async () => { calls++; return 'ok'; }, () => ({ inputTokens: 900, outputTokens: 40 }),
+ ));
+ await runWithJobSpend(engine, job, ctxFor(job), async () => invokeAI(
+ { operation: 'test-rerank', kind: 'rerank', model: 'llama-server-reranker:local-test', maxInputTokens: 10000 },
+ async () => { calls++; return 'ranked'; }, () => ({ inputTokens: 900, outputTokens: 0 }),
+ ));
+ expect(calls).toBe(2);
+ const holds = await engine.executeRaw<{ status: string; actual_cents: string }>('SELECT status, actual_cents FROM mcp_spend_reservations');
+ expect(holds).toHaveLength(2);
+ expect(holds.every(h => h.status === 'settled' && Number(h.actual_cents) === 0)).toBe(true);
+ for (const [model, refusal] of [['anthropic:claude-sonnet-5', 'cost_cap_exceeded'], ['example:unpriced-model', 'no_pricing']]) {
+ await expect(runWithJobSpend(engine, job, ctxFor(job), async () => invokeAI(
+ { operation: 'test-denied', kind: 'chat', model: model!, maxInputTokens: 10000, maxOutputTokens: 1000 },
+ async () => { calls++; return 'unexpected'; }, () => ({ inputTokens: 1, outputTokens: 1 }),
+ ))).rejects.toThrow(refusal);
+ }
+ expect(calls).toBe(2);
+ } finally {
+ await engine.setConfig('pricing.overrides', previous ?? '{}');
+ }
+});
diff --git a/test/minions/delegated-execution.serial.test.ts b/test/minions/delegated-execution.serial.test.ts
index b7be8eff39..356200b4b2 100644
--- a/test/minions/delegated-execution.serial.test.ts
+++ b/test/minions/delegated-execution.serial.test.ts
@@ -266,6 +266,20 @@ describe('durable delegated provider accounting', () => {
const rows = await engine.executeRaw<{ status: string; actual_cents: string }>('SELECT status,actual_cents::text FROM mcp_spend_reservations');
expect(rows[0].status).toBe('settled'); expect(Number(rows[0].actual_cents)).toBeCloseTo(0.0105, 4);
});
+ it('delegated local calls honor registered prices while retaining finite caps', async () => {
+ const previous = await engine.getConfig('pricing.overrides');
+ await engine.setConfig('pricing.overrides', '{"litellm:quality":{"input":0,"output":0}}');
+ try {
+ const ctx = await ownedJob(0.05);
+ let calls = 0;
+ await owned(ctx, () => invokeAI({ ...CALL, model: 'litellm:quality' }, async () => { calls++; return result(); }, sdkInvocationUsage));
+ const rows = await engine.executeRaw<{ status: string; actual_cents: string }>('SELECT status,actual_cents::text FROM mcp_spend_reservations');
+ expect(calls).toBe(1);
+ expect(rows).toHaveLength(1);
+ expect(rows[0].status).toBe('settled');
+ expect(Number(rows[0].actual_cents)).toBe(0);
+ } finally { await engine.setConfig('pricing.overrides', previous ?? '{}'); }
+ });
it('finite caps refuse unknown prices or absent enforced bounds before IO', async () => {
const ctx = await ownedJob(1); let calls = 0;
for (const call of [{ ...CALL, model: 'custom:unpriced' }, { ...CALL, maxInputTokens: undefined }, { ...CALL, kind: 'rerank' as const }]) {