Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(pricing): one priceFor resolver, claude-cli:* wildcard (D20), synthesize_concepts honors siblings and overrides (A-N2, #5166)

time-attackddd7abd42387
diff --git a/src/commands/pricing.ts b/src/commands/pricing.ts
index c09de8e9f5..475e46162e 100644
--- a/src/commands/pricing.ts
+++ b/src/commands/pricing.ts
@@ -23,6 +23,8 @@
import type { BrainEngine } from '../core/engine.ts';
import { parsePricingOverrides } from '../core/budget/budget-tracker.ts';
+import { isAllowedPricingOverrideKey } from '../core/budget/reservation-cost.ts';
+import { getRecipe } from '../core/ai/recipes/index.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
const KEY = 'pricing.overrides';
@@ -43,6 +45,12 @@ Prices merge into the pricing.overrides config: other entries are kept.
They win over gbrain's shipped price tables. A $0 rate is accepted with a
warning: every call to that model then counts as free against all cost caps.
+A provider wildcard (<provider>:*) prices every model of a provider that
+bills by subscription, today only claude-cli:
+ gbrain pricing set 'claude-cli:*' --rate 0 --source <plan-url>
+An exact model entry still wins over the wildcard. Per-token API providers
+and a bare * are refused: one rate cannot be right for all their models.
+
This command runs only on the brain host's local CLI. Agents connected over
MCP cannot register prices; they ask the operator to run the command.
See docs/operations/spend-controls.md#registering-a-model-price.
@@ -123,15 +131,32 @@ function fail(message: string): void {
setCliExitVerdict(1);
}
-function describeEntry(value: unknown): { input: number; output: number } | null {
+function describeEntry(model: string, value: unknown): { input: number; output: number } | null {
+ if (!isAllowedPricingOverrideKey(model)) return null;
const parsed = parsePricingOverrides({ probe: value });
return parsed?.probe ?? null;
}
+/** The recipe models a `<provider>:*` key prices (empty for an exact model key). */
+export function wildcardMatches(key: string): string[] {
+ const k = normalize(key);
+ if (!k.endsWith(':*')) return [];
+ const recipe = getRecipe(k.slice(0, -2));
+ if (!recipe) return [];
+ const models = new Set<string>();
+ for (const tp of Object.values(recipe.touchpoints)) {
+ for (const m of (tp as { models?: string[] } | undefined)?.models ?? []) models.add(`${recipe.id}:${m}`);
+ }
+ return [...models];
+}
+
async function runSet(engine: BrainEngine, args: string[]): Promise<void> {
const model = args[0];
if (!model || model.startsWith('--')) return fail('missing <model>. Usage: gbrain pricing set <model> --input <usd-per-1M> --output <usd-per-1M>');
const has = (flag: string) => args.includes(flag);
+ if (!isAllowedPricingOverrideKey(model)) {
+ return fail(`"${model}" is not a model id gbrain can price. A provider wildcard (<provider>:*) is accepted only for providers that bill by subscription (claude-cli); register each model of a per-token provider separately.`);
+ }
const req: PricingSetRequest = { model: model.trim() };
if (has('--rate')) {
if (has('--input') || has('--output')) return fail('use either --rate, or --input with --output, not both.');
@@ -176,6 +201,9 @@ async function runSet(engine: BrainEngine, args: string[]): Promise<void> {
if (req.rate === 0 || (req.input === 0 && req.output === 0)) {
console.error(`gbrain pricing: warning: ${normalize(req.model)} is registered at $0, so its calls count as free against every cost cap. Use $0 only for local or flat-rate routes.`);
}
+ if (normalize(req.model).endsWith(':*')) {
+ console.error(`gbrain pricing: ${normalize(req.model)} is an operator assumption that prices every ${normalize(req.model).slice(0, -2)} model, including ones gbrain ships a rate for, so cost caps no longer use those shipped rates. An exact model entry still wins.`);
+ }
}
async function runList(engine: BrainEngine, args: string[]): Promise<void> {
@@ -186,7 +214,7 @@ async function runList(engine: BrainEngine, args: string[]): Promise<void> {
return fail((err as Error).message);
}
const rows = Object.entries(current).map(([model, value]) => {
- const priced = describeEntry(value);
+ const priced = describeEntry(model, value);
const meta = value && typeof value === 'object' ? value as PricingEntry : {};
return {
model,
@@ -195,6 +223,7 @@ async function runList(engine: BrainEngine, args: string[]): Promise<void> {
valid: priced !== null,
source: meta.source ?? null,
set_at: meta.set_at ?? null,
+ ...(model.trim().endsWith(':*') ? { matches: wildcardMatches(model) } : {}),
};
});
if (args.includes('--json')) {
@@ -210,6 +239,7 @@ async function runList(engine: BrainEngine, args: string[]): Promise<void> {
const rate = r.valid ? `input $${r.input}, output $${r.output}` : 'invalid entry, ignored by cost caps';
const extra = [r.source && `source ${r.source}`, r.set_at && `set ${r.set_at}`].filter(Boolean).join('; ');
console.log(` ${r.model}: ${rate}${extra ? ` (${extra})` : ''}`);
+ if (r.valid && r.matches) console.log(` provider wildcard, operator assumption; prices every ${r.model.trim().slice(0, -2)} model without an exact entry, e.g. ${r.matches.join(', ')}`);
}
}
diff --git a/src/core/ai/recipes/claude-cli.ts b/src/core/ai/recipes/claude-cli.ts
index c89d00a34c..b30f562673 100644
--- a/src/core/ai/recipes/claude-cli.ts
+++ b/src/core/ai/recipes/claude-cli.ts
@@ -28,6 +28,10 @@ export const claudeCli: Recipe = {
name: 'Claude (via CLI)',
tier: 'native',
implementation: 'claude-cli',
+ // Calls bill against the operator's Claude subscription, not per token, so
+ // `pricing.overrides` accepts a `claude-cli:*` provider wildcard (e.g. $0).
+ // Without one, claude-cli models price at Anthropic's API list rate.
+ billing: 'subscription',
// The CLI owns auth; no env vars are required from the gateway side.
auth_env: {
required: [],
diff --git a/src/core/ai/types.ts b/src/core/ai/types.ts
index b3a58c327b..f200a9a9d2 100644
--- a/src/core/ai/types.ts
+++ b/src/core/ai/types.ts
@@ -344,6 +344,14 @@ export interface Recipe {
tier: 'native' | 'openai-compat';
/** Maps to the gateway's implementation switch. */
implementation: Implementation;
+ /**
+ * How the provider bills. `subscription`: calls draw on a flat-rate plan
+ * (claude-cli), so the operator may price every model of the provider at
+ * once with a `<provider>:*` key in `pricing.overrides`. Unset means per
+ * token, where a provider wildcard is refused (one rate cannot be right
+ * for every model of a per-token API).
+ */
+ billing?: 'subscription';
/** For openai-compatible tier: default base URL. May be overridden by env or wizard. */
base_url_default?: string;
/** Env var name(s) for auth; first is required, rest are optional. */
diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.ts
index 560d818bf0..6e73400304 100644
--- a/src/core/budget/budget-tracker.ts
+++ b/src/core/budget/budget-tracker.ts
@@ -41,6 +41,7 @@ import { EMBEDDING_PRICING } from '../embedding-pricing.ts';
import { isoWeekFilename, resolveAuditDir } from '../audit-week-file.ts';
import {
canonicalPricingKey,
+ isAllowedPricingOverrideKey,
reservationCostUsd,
usageCostUsd,
type BudgetKind,
@@ -129,7 +130,9 @@ export interface BudgetTrackerOpts {
* Parse the raw `pricing.overrides` config value (JSON string or object) into
* a normalized PricingOverrides map. Invalid entries are DROPPED (the model
* stays unpriced → the TX2 fail-closed contract still applies to it); a
- * wholly-unparseable value yields undefined. Never throws.
+ * provider wildcard on a per-token provider and a bare `*` are invalid keys
+ * (isAllowedPricingOverrideKey). A wholly-unparseable value yields undefined.
+ * Never throws.
*/
export function parsePricingOverrides(raw: unknown): PricingOverrides | undefined {
let value: unknown = raw;
@@ -148,7 +151,7 @@ export function parsePricingOverrides(raw: unknown): PricingOverrides | undefine
const out: PricingOverrides = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
const key = k.trim().toLowerCase();
- if (!key) continue;
+ if (!isAllowedPricingOverrideKey(key)) continue;
if (isRate(v)) {
out[key] = { input: v, output: v };
continue;
diff --git a/src/core/budget/reservation-cost.ts b/src/core/budget/reservation-cost.ts
index 447e70c0bf..dfb775e173 100644
--- a/src/core/budget/reservation-cost.ts
+++ b/src/core/budget/reservation-cost.ts
@@ -11,6 +11,7 @@ import { canonicalLookup } from '../model-pricing.ts';
import { lookupEmbeddingPrice } from '../embedding-pricing.ts';
import { splitProviderModelId } from '../model-id.ts';
import { resolveRecipe } from '../ai/model-resolver.ts';
+import { getRecipe } from '../ai/recipes/index.ts';
export type BudgetKind = 'chat' | 'embed' | 'rerank' | 'decide';
@@ -38,16 +39,43 @@ export function canonicalPricingKey(modelId: string): string {
}
}
+/**
+ * Whether `key` may stand in `pricing.overrides`. A model id always may. A
+ * provider wildcard (`claude-cli:*`) may only for a provider whose recipe
+ * bills by subscription: one rate is honest for every model of a flat-rate
+ * plan and wrong for every model of a per-token API. A bare `*` never may.
+ */
+export function isAllowedPricingOverrideKey(key: string): boolean {
+ const k = key.trim().toLowerCase();
+ if (!k.includes('*')) return k.length > 0;
+ if (!k.endsWith(':*') || k.slice(0, -2).includes('*')) return false;
+ return getRecipe(k.slice(0, -2))?.billing === 'subscription';
+}
+
+/** Where a price came from: an operator model override, an operator provider wildcard, or the shipped tables. */
+export type PricingSource = 'override' | 'provider_wildcard' | 'table';
+
+function overrideWithSource(modelId: string, overrides?: PricingOverrides): { pricing: ModelPricing; source: PricingSource } | null {
+ if (!overrides) return null;
+ const raw = modelId.trim().toLowerCase();
+ const key = canonicalPricingKey(modelId.trim()).toLowerCase();
+ const exact = overrides[raw] ?? overrides[key];
+ if (exact) return { pricing: exact, source: 'override' };
+ const provider = splitProviderModelId(key).provider;
+ const wildcard = provider ? overrides[`${provider}:*`] : undefined;
+ return wildcard ? { pricing: wildcard, source: 'provider_wildcard' } : null;
+}
+
/**
* Override lookup (keys normalized to lowercase at parse time): the raw key
* first, then the recipe-canonical key — an override written against the
* dated id must also price the alias the operator configured, or the alias
* silently bills at list price while the table lookup below resolves it.
+ * Then the provider wildcard (`claude-cli:*`), which parsePricingOverrides
+ * admits only for subscription-billed providers: exact > wildcard > tables.
*/
export function overrideFor(modelId: string, overrides?: PricingOverrides): ModelPricing | null {
- if (!overrides) return null;
- const raw = modelId.trim().toLowerCase();
- return overrides[raw] ?? overrides[canonicalPricingKey(modelId.trim()).toLowerCase()] ?? null;
+ return overrideWithSource(modelId, overrides)?.pricing ?? null;
}
/**
@@ -168,7 +196,24 @@ function lookupPricing(modelId: string, kind: BudgetKind): ModelPricing | null {
* caller silently does no work.
*/
export function isModelPriceable(modelId: string, kind: BudgetKind, overrides?: PricingOverrides): boolean {
- return overrideFor(modelId, overrides) !== null || lookupPricing(modelId, kind) !== null;
+ return priceFor(modelId, kind, overrides) !== null;
+}
+
+/**
+ * The one price resolver: operator overrides (exact model, then provider
+ * wildcard), then the shipped tables (aliases, the claude-cli → Anthropic
+ * sibling, canonical rows, free local providers). `null` means unpriced;
+ * each caller keeps its own miss policy.
+ */
+export function priceFor(
+ modelId: string,
+ kind: BudgetKind,
+ overrides?: PricingOverrides,
+): { pricing: ModelPricing; source: PricingSource } | null {
+ const override = overrideWithSource(modelId, overrides);
+ if (override) return override;
+ const table = lookupPricing(modelId, kind);
+ return table ? { pricing: table, source: 'table' } : null;
}
export function usageCostUsd(
@@ -181,7 +226,7 @@ export function usageCostUsd(
// #4312: operator overrides win — the operator owns their bill (negotiated
// rates, proxy routes the shipped tables can't know about). Missing both →
// null, and the TX2 fail-closed contract in reserve() still applies.
- const p = overrideFor(modelId, overrides) ?? lookupPricing(modelId, kind);
+ const p = priceFor(modelId, kind, overrides)?.pricing;
if (!p) return null;
return (inputTokens / 1_000_000) * p.input + (outputTokens / 1_000_000) * p.output;
}
diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts
index b3497dcf76..4c30ea447f 100644
--- a/src/core/cycle/synthesize-concepts.ts
+++ b/src/core/cycle/synthesize-concepts.ts
@@ -35,6 +35,9 @@ import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } f
import { importFromContent } from '../import-file.ts';
import { serializeMarkdown } from '../markdown.ts';
import { canonicalLookup, type ModelPricing } from '../model-pricing.ts';
+import { priceFor } from '../budget/reservation-cost.ts';
+import { loadPricingOverrides } from '../budget/budget-tracker.ts';
+import { pricingSetCommand } from '../budget/no-pricing.ts';
import { createHash } from 'node:crypto';
import { slugifySegment } from '../sync.ts';
import { validatePageSlug } from '../ops/context.ts';
@@ -43,10 +46,11 @@ import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';
import { addManagedProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishManagedConcept } from './concept-publication.ts';
const DEFAULT_BUDGET_USD = 1.5;
-// Canonical-miss policy — mirrors skillopt/preflight.ts's lookupPrice:
-// assume Sonnet-tier pricing for models absent from CANONICAL_PRICING.
-// Conservative and non-throwing; keeps the budget gate effective (and
-// matches this file's pre-canonical behavior) instead of letting an
+// Miss policy for the shared resolver (`priceFor`: operator overrides, the
+// claude-cli → Anthropic sibling, canonical rows): assume Sonnet-tier
+// pricing for a model nothing prices, and name it in the phase details
+// (`pricing_fallback_models`) plus one stderr line. Conservative and
+// non-throwing; keeps this default budget effective instead of letting an
// unpriced model run unmetered. The rates are DERIVED from the canonical
// table (never hand-copied — CLAUDE.md invariant); the literal pair only
// fires if the Sonnet key itself ever leaves the table.
@@ -301,6 +305,8 @@ export async function runPhaseSynthesizeConcepts(
const skippedHumanOwned: string[] = [];
const skippedUnchanged: string[] = [];
const keptExistingNarrative: string[] = [];
+ const pricingOverrides = await loadPricingOverrides(engine);
+ const pricingFallbackModels = new Set<string>();
for (const group of atomGroups) {
const conceptSlug = `concepts/${group.conceptSlug}`;
// A concept page this phase did not write belongs to a human (or another
@@ -358,10 +364,14 @@ export async function runPhaseSynthesizeConcepts(
// refresh rate.
await maybeYield();
llmHalt.reset();
- // Price from the model that actually answered, through the one
- // canonical chat-pricing table (CLAUDE.md invariant). Canonical
- // miss → Sonnet-tier FALLBACK_PRICING (see constant above).
- const pricing = canonicalLookup(result.model) ?? FALLBACK_PRICING;
+ // Price from the model that actually answered, through the shared
+ // resolver. A miss → Sonnet-tier FALLBACK_PRICING (see constant above).
+ const priced = priceFor(result.model, 'chat', pricingOverrides);
+ if (!priced && !pricingFallbackModels.has(result.model)) {
+ pricingFallbackModels.add(result.model);
+ console.error(`[synthesize_concepts] ${result.model} has no pricing; metering it at Sonnet-tier rates against the $${budgetCap.toFixed(2)} phase budget. To meter its real price, look it up and register it: ${pricingSetCommand(result.model, 'chat')}`);
+ }
+ const pricing = priced?.pricing ?? FALLBACK_PRICING;
estimatedSpendUsd +=
(result.usage.input_tokens * pricing.input +
result.usage.output_tokens * pricing.output) /
@@ -581,6 +591,7 @@ export async function runPhaseSynthesizeConcepts(
...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),
estimated_spend_usd: estimatedSpendUsd,
budget_usd: budgetCap,
+ pricing_fallback_models: [...pricingFallbackModels],
dry_run: opts.dryRun ?? false,
},
};
diff --git a/test/budget/provider-wildcard-pricing.test.ts b/test/budget/provider-wildcard-pricing.test.ts
new file mode 100644
index 0000000000..f93e5bec2f
--- /dev/null
+++ b/test/budget/provider-wildcard-pricing.test.ts
@@ -0,0 +1,99 @@
+/**
+ * D20 provider wildcard overrides and the one price resolver (`priceFor`).
+ *
+ * `"claude-cli:*": 0` lets a subscription operator price every claude-cli
+ * model at once. It is accepted only for providers whose recipe declares
+ * `billing: 'subscription'`; a bare `*` and a wildcard on a per-token API
+ * provider are dropped at parse, and `gbrain pricing set` refuses them.
+ * Precedence: exact model override > provider wildcard > shipped tables.
+ *
+ * #5847: `deepseek:deepseek-flash` is priced, so the dream BudgetMeter meters
+ * it instead of warning NO_PRICING and charging the Sonnet fallback.
+ *
+ * Hermetic: pure functions plus a BudgetMeter/BudgetTracker with a tmp audit path.
+ */
+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 { isAllowedPricingOverrideKey, isModelPriceable, priceFor } from '../../src/core/budget/reservation-cost.ts';
+import { BudgetTracker, parsePricingOverrides, _resetBudgetTrackerWarningsForTest } from '../../src/core/budget/budget-tracker.ts';
+import { BudgetMeter } from '../../src/core/cycle/budget-meter.ts';
+import { mergePricing, wildcardMatches } from '../../src/commands/pricing.ts';
+
+let tmp: string;
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), 'gbrain-wildcard-'));
+ _resetBudgetTrackerWarningsForTest();
+});
+afterEach(() => rmSync(tmp, { recursive: true, force: true }));
+
+describe('provider wildcard keys', () => {
+ test('claude-cli:* is accepted; openai:*, a bare *, and an embedded * are rejected', () => {
+ expect(isAllowedPricingOverrideKey('claude-cli:*')).toBe(true);
+ expect(isAllowedPricingOverrideKey('CLAUDE-CLI:*')).toBe(true);
+ expect(isAllowedPricingOverrideKey('openai:*')).toBe(false);
+ expect(isAllowedPricingOverrideKey('anthropic:*')).toBe(false);
+ expect(isAllowedPricingOverrideKey('*')).toBe(false);
+ expect(isAllowedPricingOverrideKey('claude-cli:claude-*')).toBe(false);
+ expect(isAllowedPricingOverrideKey('no-such-provider:*')).toBe(false);
+ expect(isAllowedPricingOverrideKey('openai:gpt-5.5')).toBe(true);
+ });
+
+ test('parsePricingOverrides drops the rejected wildcards and keeps the accepted one', () => {
+ const parsed = parsePricingOverrides({ 'claude-cli:*': 0, 'openai:*': 0, '*': 0 });
+ expect(parsed).toEqual({ 'claude-cli:*': { input: 0, output: 0 } });
+ });
+
+ test('precedence: exact > provider wildcard > shipped table', () => {
+ const overrides = parsePricingOverrides({
+ 'claude-cli:*': 0,
+ 'claude-cli:claude-opus-5-5': { input: 1, output: 2 },
+ });
+ expect(priceFor('claude-cli:claude-opus-5-5', 'chat', overrides)).toEqual({ pricing: { input: 1, output: 2 }, source: 'override' });
+ expect(priceFor('claude-cli:claude-sonnet-5-5', 'chat', overrides)).toEqual({ pricing: { input: 0, output: 0 }, source: 'provider_wildcard' });
+ expect(priceFor('claude-cli:claude-sonnet-5-5', 'chat')?.source).toBe('table');
+ expect(priceFor('claude-cli:claude-sonnet-5-5', 'chat')?.pricing.input).toBe(2);
+ expect(priceFor('anthropic:claude-sonnet-5-5', 'chat', overrides)?.source).toBe('table');
+ });
+
+ test('a wildcard prices a model no table knows, under a user cap', () => {
+ const overrides = parsePricingOverrides({ 'claude-cli:*': 0 });
+ expect(isModelPriceable('claude-cli:claude-next-unreleased', 'chat')).toBe(false);
+ expect(isModelPriceable('claude-cli:claude-next-unreleased', 'chat', overrides)).toBe(true);
+ const t = new BudgetTracker({ label: 't', auditPath: join(tmp, 'a.jsonl'), maxCostUsd: 1, pricingOverrides: overrides });
+ expect(() => t.reserve({ modelId: 'claude-cli:claude-next-unreleased', kind: 'chat', estimatedInputTokens: 1000, maxOutputTokens: 1000 })).not.toThrow();
+ });
+
+ test('gbrain pricing list names the recipe models a wildcard prices', () => {
+ const models = wildcardMatches('claude-cli:*');
+ expect(models).toContain('claude-cli:claude-opus-5-5');
+ expect(models.every((m) => m.startsWith('claude-cli:'))).toBe(true);
+ expect(wildcardMatches('claude-cli:claude-opus-5-5')).toEqual([]);
+ });
+
+ test('mergePricing keeps the wildcard key as written', () => {
+ const { next } = mergePricing({}, { model: 'claude-cli:*', rate: 0 }, new Date(0));
+ expect(Object.keys(next)).toEqual(['claude-cli:*']);
+ });
+});
+
+describe('#5847 deepseek:deepseek-flash is priced', () => {
+ test('BudgetMeter meters it at the peak row without the NO_PRICING warning', () => {
+ let err = '';
+ const spy = spyOn(process.stderr, 'write').mockImplementation(((c: string | Uint8Array) => {
+ err += typeof c === 'string' ? c : new TextDecoder().decode(c);
+ return true;
+ }) as typeof process.stderr.write);
+ let res;
+ try {
+ const meter = new BudgetMeter({ budgetUsd: 1, phase: 'test', auditPath: join(tmp, 'm.jsonl') });
+ res = meter.check({ modelId: 'deepseek:deepseek-flash', estimatedInputTokens: 0, maxOutputTokens: 32_000 });
+ } finally {
+ spy.mockRestore();
+ }
+ expect(err).not.toContain('NO_PRICING');
+ expect(res.unpriced).toBeFalsy();
+ expect(res.estimatedCostUsd).toBeCloseTo(32_000 / 1_000_000 * 1.2, 9);
+ });
+});
diff --git a/test/cycle/synthesize-concepts-pricing.test.ts b/test/cycle/synthesize-concepts-pricing.test.ts
new file mode 100644
index 0000000000..90134400fd
--- /dev/null
+++ b/test/cycle/synthesize-concepts-pricing.test.ts
@@ -0,0 +1,83 @@
+// A-N2 / #5166: synthesize_concepts metered its narrative calls through
+// `canonicalLookup` alone, so a claude-cli model (priced through its Anthropic
+// sibling everywhere else) and an operator's `pricing.overrides` row were both
+// ignored, and an unpriced model fell back to Sonnet rates without a word. The
+// phase now prices through the shared `priceFor` and names the fallback.
+//
+// Hermetic: PGLite + injected `_atoms` and `_chat`. No provider credentials and
+// no network.
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.ts';
+
+const t2Atoms = () =>
+ Array.from({ length: 5 }, (_, i) => ({
+ slug: `atoms/a${i}`,
+ concept_refs: ['concepts/x'],
+ body: `body ${i}`,
+ title: `A${i}`,
+ }));
+
+/** Answers as `served`, reporting 1M input tokens and no output, so spend == the input rate. */
+function chatAs(served: string): (o: ChatOpts) => Promise<ChatResult> {
+ return async () => ({
+ text: 'narrative text',
+ blocks: [{ type: 'text', text: 'narrative text' }],
+ stopReason: 'end',
+ usage: { input_tokens: 1_000_000, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: served,
+ providerId: served.split(':')[0]!,
+ });
+}
+
+describe('synthesize_concepts prices through the shared resolver', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60000);
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');
+ });
+
+ test('a claude-cli model is metered at its Anthropic sibling rate, not the Sonnet fallback', async () => {
+ const r = await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), _chat: chatAs('claude-cli:claude-opus-5-5') });
+ expect(r.details.estimated_spend_usd).toBeCloseTo(4, 6);
+ expect(r.details.pricing_fallback_models).toEqual([]);
+ });
+
+ test('an operator pricing.overrides row wins', async () => {
+ await engine.setConfig('pricing.overrides', JSON.stringify({ 'claude-cli:claude-opus-5-5': { input: 1, output: 1 } }));
+ const r = await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), _chat: chatAs('claude-cli:claude-opus-5-5') });
+ expect(r.details.estimated_spend_usd).toBeCloseTo(1, 6);
+ });
+
+ test('a claude-cli:* wildcard prices every claude-cli model', async () => {
+ await engine.setConfig('pricing.overrides', JSON.stringify({ 'claude-cli:*': 0 }));
+ const r = await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), _chat: chatAs('claude-cli:claude-opus-5-5') });
+ expect(r.details.estimated_spend_usd).toBe(0);
+ });
+
+ test('deepseek:deepseek-flash is priced at the peak row (#5847)', async () => {
+ const r = await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), _chat: chatAs('deepseek:deepseek-flash') });
+ expect(r.details.estimated_spend_usd).toBeCloseTo(0.3, 6);
+ expect(r.details.pricing_fallback_models).toEqual([]);
+ });
+
+ test('an unpriced model is metered at the Sonnet fallback and named in the phase details', async () => {
+ const r = await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), _chat: chatAs('litellm:house-model') });
+ expect(r.details.estimated_spend_usd).toBeCloseTo(3, 6);
+ expect(r.details.pricing_fallback_models).toEqual(['litellm:house-model']);
+ });
+});