Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(probe): metered chat cost prices models the way the run budget does

time-attack16d3f7f4acc9
diff --git a/TODOS.md b/TODOS.md
index 15b3f020b5..c615bc8f03 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -5,7 +5,6 @@
- [ ] **P2 — Receipted publication for managed conversation facts.** **What:** `extract-conversation-facts` replaces a page's derived fact batch through `replaceDerivedFactsForPage` (`src/core/persistence/derived-facts.ts`), a coordinated transaction with no persistence request. On a managed brain a multi-message email thread is therefore skipped without writing and retried every run (`src/core/facts/conversation-skip.ts`), as are the single-email and prose outcomes; `test/helpers/managed-connector-job-contract.ts` case `extract_conversation_facts_thread` pins it. **Fix:** admit a persistence request for the derived batch (delete-by-prefix plus insert, page revision as the CAS) in the same transaction, so the write carries a receipt; then drop the managed gate and record the single-email/prose outcomes durably there too. **Effort:** M. **Priority:** P2.
- [ ] **P2 — Re-extract conversation facts misattributed to meeting-note labels.** **What:** before v0.60.70.0 the conversation parser read `**Date:**`, `**Attendees:**` and similar labels as speakers, so conversation facts were written with entity "Date" and an epoch date. The parser fix stops new ones; existing rows stay. **Fix:** a `gbrain` command that finds conversation facts whose provenance is a metadata-label speaker, previews them by default, and on `--apply` re-extracts the source pages under an explicit cost cap (never an automatic spend). **Effort:** M. **Priority:** P2.
- [ ] **P3 — Stall detection for subagent turns.** **What:** `ai.chat.per_turn_timeout_ms` bounds a whole turn (default 30 min) because gateway chat calls are not streamed, so a hung provider holds the turn for the full budget. **Fix:** once chat streams, abort a turn that produces no tokens for a shorter stall window. **Effort:** M. **Priority:** P3.
-- [ ] **P3 — Nightly probe metered cost and the budget tracker price models the same way.** **What:** the probe's `chat_cost_usd` / `unpriced_chat_calls` come from `estimateChatCostUsd` (canonical table only), while its run budget prices through `priceFor()` (operator overrides, claude-cli sibling rate, free local providers). A model priced only by `pricing.overrides`, a claude-cli model or a local model is metered as unpriced in the audit row while the cap counts it. **Fix:** price the meter through `priceFor()` with the brain's overrides, keeping cache-token pricing for table rows. **Effort:** S. **Priority:** P3.
## Contributor audit wave follow-ups (filed 2026-10-05, GBRA-40)
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 25535b3e70..5a3f29d584 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, re-exported by `src/cli.ts`. Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Delegates the file-plane API-key fold + env merge to `mergedProviderEnv` (`src/core/ai/provider-env.ts`); keeps ownership of threading local-server `*_BASE_URL` env vars into base_urls. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.
-- `src/core/ai/chat-usage.ts` + `src/core/ops/usage.ts` — durable per-call chat usage accounting. `gateway.chat()` calls `recordChatUsage` at its SUCCESS boundary (production provider path AND test-transport path) with the answering model + token usage; the record lands in the `chat_usage_log` table (migration v140) via an injected sink (`setChatUsageSink` — no engine import here, so the gateway imports this leaf statically without deepening a cycle). Phase attribution is best-effort via AsyncLocalStorage (`withChatPhase`): the minion worker AND the cycle's inline drain (`inline-drain.ts`) both wrap handler execution in `job:<name>`, a cycle phase that meters its own spend wraps itself in `phase:<name>` (dream synthesize does), and direct callers record phase NULL. The innermost wrap wins, which is the point — a child drained INSIDE a wrapped phase must carry its own `job:` tag or the phase tag absorbs every child's spend and the ledger double-counts (one ledger per surface: `minion_jobs` stays the child-spend authority, the phase row is the orchestrator's own calls). Pricing resolves through `CANONICAL_PRICING` (`estimateChatCostUsd`, cache_read/cache_write at provider cache rates when the table carries them); unknown models record `cost_usd = NULL`, never a fake 0. Accounting is strictly fail-open + fire-and-forget: a sink error must never break a chat call. `withChatCallMeter` counts successful calls on a `ChatCallMeter` (phase containment's `{ calls }`); a meter that declares `cost_usd` (the nightly probe's) also adds each call's price from the same `estimateChatCostUsd` value the record carries, counts an unpriced call in `unpriced_calls` instead of as 0, and is priced even when no sink is registered. The `get_usage` op (admin scope, NOT read — `chat_usage_log` has no source dimension, so a source-restricted/federated token must not see brain-wide spend telemetry) returns per-model/per-phase aggregates only, plus an explicit `coverage` block stating what the ledger does NOT capture (subagent raw-SDK path, embeddings, pre-sink/pre-v140 calls, failed calls); `budget-tracker.ts` remains the pessimistic in-flight spend gate — this table is the after-the-fact ledger.
+- `src/core/ai/chat-usage.ts` + `src/core/ops/usage.ts` — durable per-call chat usage accounting. `gateway.chat()` calls `recordChatUsage` at its SUCCESS boundary (production provider path AND test-transport path) with the answering model + token usage; the record lands in the `chat_usage_log` table (migration v140) via an injected sink (`setChatUsageSink` — no engine import here, so the gateway imports this leaf statically without deepening a cycle). Phase attribution is best-effort via AsyncLocalStorage (`withChatPhase`): the minion worker AND the cycle's inline drain (`inline-drain.ts`) both wrap handler execution in `job:<name>`, a cycle phase that meters its own spend wraps itself in `phase:<name>` (dream synthesize does), and direct callers record phase NULL. The innermost wrap wins, which is the point — a child drained INSIDE a wrapped phase must carry its own `job:` tag or the phase tag absorbs every child's spend and the ledger double-counts (one ledger per surface: `minion_jobs` stays the child-spend authority, the phase row is the orchestrator's own calls). Pricing resolves through `CANONICAL_PRICING` (`estimateChatCostUsd`, cache_read/cache_write at provider cache rates when the table carries them); unknown models record `cost_usd = NULL`, never a fake 0. Accounting is strictly fail-open + fire-and-forget: a sink error must never break a chat call. `withChatCallMeter` counts successful calls on a `ChatCallMeter` (phase containment's `{ calls }`); a meter that declares `cost_usd` (the nightly probe's) also prices each call with the budget tracker's resolver (`priceFor` with the meter's `pricing_overrides`; a table row uses the same cache-aware `estimateChatCostUsd` value the record carries), counts an unpriced call in `unpriced_calls` instead of as 0, and is priced even when no sink is registered. The `get_usage` op (admin scope, NOT read — `chat_usage_log` has no source dimension, so a source-restricted/federated token must not see brain-wide spend telemetry) returns per-model/per-phase aggregates only, plus an explicit `coverage` block stating what the ledger does NOT capture (subagent raw-SDK path, embeddings, pre-sink/pre-v140 calls, failed calls); `budget-tracker.ts` remains the pessimistic in-flight spend gate — this table is the after-the-fact ledger.
- `src/core/ai/defaults.ts` — leaf module for canonical embedding and reranker defaults, without a gateway import. Voyage `voyage:voyage-4` at 1024 dimensions is the new-install embedding default; `voyage:rerank-2.5` is the runtime/mode-bundle reranker default. `renderCanonicalMigrationCommands` supplies an explicit-target cost preview and an OpenAI keep-width alternative where supported. These constants do not establish the identity of vectors in an existing database and must never authorize automatic provider conversion. Init preserves explicit choices, writes no reranker row when the Voyage key is available, disables reranking for keyed installs without that key, and preserves keyless setup.
diff --git a/src/core/ai/chat-usage.ts b/src/core/ai/chat-usage.ts
index 88a2472b02..1579210f82 100644
--- a/src/core/ai/chat-usage.ts
+++ b/src/core/ai/chat-usage.ts
@@ -31,6 +31,7 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import { canonicalLookup } from '../model-pricing.ts';
+import { priceFor, type PricingOverrides } from '../budget/reservation-cost.ts';
export interface ChatUsageRecord {
/** "provider:modelId" of the model that actually answered. */
@@ -63,14 +64,17 @@ export function currentChatPhase(): string | null {
/**
* Successful chat calls counted for one cycle phase (phase containment,
* dream_paid_loop) or one nightly probe run. A meter that declares
- * `cost_usd` also prices each call from canonical pricing: priced calls add
- * to `cost_usd`, unpriced ones (`estimateChatCostUsd` null) add to
+ * `cost_usd` also prices each call with the budget tracker's resolver
+ * (`priceFor`: `pricing_overrides`, then the shipped tables, the claude-cli
+ * sibling rate and free local providers; table rows keep their cache-token
+ * rates): priced calls add to `cost_usd`, unpriced ones add to
* `unpriced_calls` instead of counting as 0.
*/
export interface ChatCallMeter {
calls: number;
cost_usd?: number;
unpriced_calls?: number;
+ pricing_overrides?: PricingOverrides;
}
const __chatMeterStore = new AsyncLocalStorage<ChatCallMeter>();
@@ -158,8 +162,13 @@ export function recordChatUsage(input: {
try {
const cost_usd = estimateChatCostUsd(input.model, input.usage);
if (pricedMeter) {
- if (cost_usd === null) pricedMeter.unpriced_calls = (pricedMeter.unpriced_calls ?? 0) + 1;
- else pricedMeter.cost_usd = (pricedMeter.cost_usd ?? 0) + cost_usd;
+ const price = priceFor(input.model, 'chat', pricedMeter.pricing_overrides);
+ const { input_tokens, output_tokens, cache_read_tokens = 0, cache_write_tokens = 0 } = input.usage;
+ const meterCost = price === null ? null
+ : price.source === 'table' && cost_usd !== null ? cost_usd
+ : ((input_tokens + cache_read_tokens + cache_write_tokens) * price.pricing.input + output_tokens * price.pricing.output) / 1_000_000;
+ if (meterCost === null) pricedMeter.unpriced_calls = (pricedMeter.unpriced_calls ?? 0) + 1;
+ else pricedMeter.cost_usd = (pricedMeter.cost_usd ?? 0) + meterCost;
}
if (!sink) return;
const record: ChatUsageRecord = {
diff --git a/src/core/cycle/nightly-quality-probe.ts b/src/core/cycle/nightly-quality-probe.ts
index 15dc8329ce..79161d67d4 100644
--- a/src/core/cycle/nightly-quality-probe.ts
+++ b/src/core/cycle/nightly-quality-probe.ts
@@ -408,7 +408,7 @@ export async function runNightlyQualityProbe(deps: NightlyProbeDeps): Promise<Ni
});
capFields = { cap_usd: maxUsd, cap_source: policy.capSource };
const runTracker = tracker;
- meter = { calls: 0, cost_usd: 0, unpriced_calls: 0 };
+ meter = { calls: 0, cost_usd: 0, unpriced_calls: 0, ...(policy.pricingOverrides ? { pricing_overrides: policy.pricingOverrides } : {}) };
const runMeter = meter;
await withBudgetTracker(runTracker, () => withChatCallMeter(runMeter, () =>
deps.runLongMemEval({ fixturePath, outputPath: lmeOutPath, searchConfigSnapshot, modelRoutes })));
diff --git a/test/chat-usage.test.ts b/test/chat-usage.test.ts
index 1af262cdbd..c742771486 100644
--- a/test/chat-usage.test.ts
+++ b/test/chat-usage.test.ts
@@ -138,7 +138,7 @@ describe('estimateChatCostUsd — canonical pricing incl. cache tokens', () => {
describe('#5506: chat call meter prices what it counts', () => {
const usage = { input_tokens: 1000, output_tokens: 500 };
const PRICED = 'anthropic:claude-haiku-4-5';
- const UNPRICED = 'claude-cli:claude-opus-5-5';
+ const UNPRICED = 'acme:unpriced-model-9000';
function meterCalls(meter: ChatCallMeter, models: string[]): void {
withChatCallMeter(meter, () => {
@@ -163,6 +163,15 @@ describe('#5506: chat call meter prices what it counts', () => {
expect(records.map(r => r.cost_usd)).toEqual([meter.cost_usd!, null]);
});
+ test('the meter prices with the budget tracker resolver: overrides, the claude-cli sibling rate and free local models', () => {
+ setChatUsageSink(null);
+ const meter: ChatCallMeter = { calls: 0, cost_usd: 0, unpriced_calls: 0, pricing_overrides: { [UNPRICED]: { input: 2, output: 4 } } };
+ meterCalls(meter, [UNPRICED, 'claude-cli:claude-haiku-4-5', 'ollama:llama3']);
+ expect(meter.unpriced_calls).toBe(0);
+ const overridden = (usage.input_tokens * 2 + usage.output_tokens * 4) / 1_000_000;
+ expect(meter.cost_usd).toBeCloseTo(overridden + estimateChatCostUsd('anthropic:claude-haiku-4-5', usage)!, 12);
+ });
+
test('a { calls } meter still only counts calls', () => {
const meter: ChatCallMeter = { calls: 0 };
meterCalls(meter, [PRICED, UNPRICED]);
diff --git a/test/nightly-probe-run-budget.test.ts b/test/nightly-probe-run-budget.test.ts
index baba293adc..ec79f9d39c 100644
--- a/test/nightly-probe-run-budget.test.ts
+++ b/test/nightly-probe-run-budget.test.ts
@@ -219,6 +219,9 @@ describe('pricing policy for the run cap', () => {
}));
expect(r.outcome).toBe('pass');
expect(providerCalls).toEqual([UNPRICED, UNPRICED]);
+ const [event] = readRecentQualityProbeEvents(1);
+ expect(event!.unpriced_chat_calls).toBe(0);
+ expect(event!.chat_cost_usd).toBeCloseTo(2 * (1000 * 1 + 200 * 2) / 1_000_000, 9);
});
});
});