Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(budget): agent-actionable no_pricing refusal under an explicit cost cap
garrytan181ac34fae65
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 2525f1e0b0..47c482dc16 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -63,6 +63,7 @@ of making a duplicate.| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. || <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. || <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |+| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |### Other error codesdiff --git a/src/commands/enrich.ts b/src/commands/enrich.tsindex 8c10574921..26e25c741f 100644--- a/src/commands/enrich.ts+++ b/src/commands/enrich.ts@@ -38,7 +38,9 @@ import { preserveCanonicalFences } from '../core/cycle/concept-publication.ts';import type { WriteReceipt } from '../core/persistence/types.ts';import type { OperationContext } from '../core/operations.ts';import { configureGatewayIfUninitialized, isAvailable, chat, getChatModel, withBudgetTracker } from '../core/ai/gateway.ts';-import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason } from '../core/budget/budget-tracker.ts';+import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason, type NoPricingGuidance } from '../core/budget/budget-tracker.ts';+import { noPricingSteps } from '../core/budget/no-pricing.ts';+import { ERROR_CATALOGUE } from '../core/error-catalogue.ts';import { hybridSearch } from '../core/search/hybrid.ts';import { INTERNAL_BREADTH_SEARCH_OPTS } from '../core/search/internal-breadth.ts';import { serializeMarkdown } from '../core/markdown.ts';@@ -169,6 +171,8 @@ export interface EnrichResult {budget_exhausted_reason?: BudgetReason;/** Model that triggered a no_pricing abort, when the tracker knew it (#4032). */budget_exhausted_model?: string;+ /** no_pricing abort: the lookup-and-register guidance (model, provider, kind, units, command, docs). */+ budget_exhausted_pricing?: NoPricingGuidance;/** #2504 — first pool failure ('slug: message'), so pages_failed > 0 always* carries a WHY (pool.failures was previously write-only). */first_failure?: string;@@ -666,6 +670,7 @@ export async function runEnrichCore(// branch its advice instead of collapsing every abort into "raise the cap".result.budget_exhausted_reason = err.reason;if (err.modelId) result.budget_exhausted_model = err.modelId;+ if (err.pricing) result.budget_exhausted_pricing = err.pricing;return result; // partial run; caller surfaces it (NOT a thrown failure)}throw err;@@ -909,6 +914,7 @@ function addInto(agg: EnrichResult, r: EnrichResult): void {) {agg.budget_exhausted_reason = r.budget_exhausted_reason;agg.budget_exhausted_model = r.budget_exhausted_model;+ agg.budget_exhausted_pricing = r.budget_exhausted_pricing;}// #2504 — first failure seen across sources sticks (a sample, not a log).if (r.first_failure && agg.first_failure === undefined) {@@ -922,13 +928,13 @@ function addInto(agg: EnrichResult, r: EnrichResult): void {* A no_pricing TX2 hard-fail is not a cost overrun — "raise --max-usd"* sends the operator after the wrong knob. Exported for tests.*/-export function budgetExhaustedMessage(reason?: BudgetReason, modelId?: string): string {+export function budgetExhaustedMessage(reason?: BudgetReason, modelId?: string, pricing?: NoPricingGuidance): string {if (reason === 'no_pricing') {const m = modelId ? ` for ${modelId}` : '';- return (- ` No pricing${m} — the cost cap cannot be enforced. ` +- 'Add a pricing entry for the model, or re-run uncapped (--max-usd off).'- );+ const steps = pricing+ ? noPricingSteps(pricing)+ : `Look up the model's per-token price and register it with \`gbrain pricing set\` (see ${ERROR_CATALOGUE.no_pricing.docs}), then retry.`;+ return ` No pricing${m} — the cost cap cannot be enforced. ${steps} Or re-run uncapped (--max-usd off).`;}return ' Budget cap reached. Re-run with a higher --max-usd to continue.';}@@ -1088,7 +1094,7 @@ export async function runEnrich(engine: BrainEngine, args: string[]): Promise<vo);if (anyBudgetExhausted) {console.log(- budgetExhaustedMessage(aggregate.budget_exhausted_reason, aggregate.budget_exhausted_model),+ budgetExhaustedMessage(aggregate.budget_exhausted_reason, aggregate.budget_exhausted_model, aggregate.budget_exhausted_pricing),);}}diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex dd0a2ad52d..9e2b303dfc 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -75,7 +75,8 @@ import {import { configureGatewayIfUninitialized, isAvailable, withBudgetTracker } from '../core/ai/gateway.ts';import { managedDerivedFactsPreflight, replaceDerivedFactsForPage, writeDerivedFacts } from '../core/persistence/derived-facts.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';-import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason } from '../core/budget/budget-tracker.ts';+import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason, type NoPricingGuidance } from '../core/budget/budget-tracker.ts';+import { noPricingMessage } from '../core/budget/no-pricing.ts';import { conversationFactsCostCap } from '../core/facts/conversation-budget.ts';import { listSources } from '../core/sources-ops.ts';import {@@ -353,6 +354,8 @@ export interface ExtractConversationFactsResult {budget_exhausted?: boolean;budget_reason?: BudgetReason;budget_model?: string;+ /** no_pricing halt: the lookup-and-register guidance (model, provider, kind, units, command, docs). */+ budget_pricing?: NoPricingGuidance;spent_usd?: number;}@@ -1601,9 +1604,8 @@ export async function runExtractConversationFactsCore(}} catch (err) {if (err instanceof BudgetExhausted) {- result.budget_exhausted = true;- result.budget_reason = err.reason;- result.budget_model = err.modelId;+ Object.assign(result, { budget_exhausted: true, budget_reason: err.reason, budget_model: err.modelId });+ if (err.pricing) result.budget_pricing = err.pricing;if (opts.budgetTracker) {result.spent_usd = opts.budgetTracker.totalSpent;}@@ -1883,7 +1885,7 @@ sources from gbrain sources list. Per-source budget cap defaults to--max-cost-usd; the brain-wide cap when running via the autopilot cyclephase is cycle.conversation_facts_backfill.max_total_cost_usd.Default USD caps are not enforced for unpriced chat models (a warning is emitted).-Explicit caps remain fail-closed; configure pricing.overrides to supply missing prices.+Explicit caps remain fail-closed; register a missing price with gbrain pricing set <model> --input <usd-per-1M> --output <usd-per-1M>.Resumability: per-page completion is durable via a terminal audit rowin the facts table (source='${TERMINAL_AUDIT_SOURCE}'). gbrain doctor's@@ -1981,6 +1983,7 @@ export async function runExtractConversationFacts(let totalSpent = 0;let anyBudgetExhausted = false;const unpricedModels = new Set<string>();+ const pricingGuidance = new Map<string, NoPricingGuidance>();const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));@@ -2032,6 +2035,7 @@ export async function runExtractConversationFacts(aggregate.resolution_errors += perSource.resolution_errors;if (perSource.budget_exhausted) anyBudgetExhausted = true;if (perSource.budget_reason === 'no_pricing') unpricedModels.add(perSource.budget_model ?? 'unknown model');+ if (perSource.budget_pricing) pricingGuidance.set(perSource.budget_pricing.model, perSource.budget_pricing);if (perSource.spent_usd) totalSpent += perSource.spent_usd;progress.tick(1, `${sourceId}: ${perSource.facts_inserted} facts inserted`);@@ -2055,6 +2059,7 @@ export async function runExtractConversationFacts(spent_usd: totalSpent,budget_exhausted: anyBudgetExhausted,no_pricing_models: [...unpricedModels],+ no_pricing: [...pricingGuidance.values()],}, null, 2));} else {console.log(@@ -2105,8 +2110,9 @@ export async function runExtractConversationFacts(}if (anyBudgetExhausted) {console.log(unpricedModels.size > 0- ? ` no_pricing: ${[...unpricedModels].join(', ')}. Configure pricing.overrides; raising --max-cost-usd cannot resolve missing pricing.`+ ? ` no_pricing: ${[...unpricedModels].join(', ')}. Raising --max-cost-usd cannot resolve missing pricing.`: ` Budget cap reached. Re-run with a higher --max-cost-usd to continue.`);+ for (const g of pricingGuidance.values()) console.log(` ${noPricingMessage(g)}`);}}diff --git a/src/commands/skillopt.ts b/src/commands/skillopt.tsindex 2af043d50c..84af325d24 100644--- a/src/commands/skillopt.ts+++ b/src/commands/skillopt.ts@@ -376,8 +376,10 @@ export function formatRunSummary(outcome: RunSkillOptOutcome, receipt: RunReceipconst detail = receipt.abort_detail ?? '(no detail captured)';lines.push(`[skillopt] Failure reason: ${receipt.abort_reason ?? 'unknown'}`);lines.push(`[skillopt] Detail: ${detail}`);- if (detail.includes('no_pricing')) {- lines.push(`[skillopt] Hint: model has no pricing entry; pass --no-max-cost (or --max-cost-usd 0) to run uncapped with a warn-once.`);+ if (receipt.no_pricing) {+ lines.push(`[skillopt] Hint: ${receipt.no_pricing.lookup} Register it with: ${receipt.no_pricing.register_command} — then retry; or pass --no-max-cost (or --max-cost-usd 0) to run uncapped with a warn-once.`);+ } else if (detail.includes('no_pricing')) {+ lines.push(`[skillopt] Hint: gbrain has no price for the model, so the cap can't be enforced. Look up its per-token price and register it with \`gbrain pricing set\` (see the detail above), then retry; or pass --no-max-cost (or --max-cost-usd 0) to run uncapped with a warn-once.`);}}if (receipt.stop_reason === 'early_stop_unusable_output') {diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.tsindex 3d3dc4e348..8ad381dd61 100644--- a/src/core/budget/budget-tracker.ts+++ b/src/core/budget/budget-tracker.ts@@ -42,9 +42,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';export { isModelPriceable } from './reservation-cost.ts';-export type { BudgetKind, PricingOverrides };+export type { BudgetKind, PricingOverrides, NoPricingGuidance };export type BudgetReason = 'cost' | 'runtime' | 'no_pricing';@@ -169,9 +170,11 @@ export class BudgetExhausted extends Error {spent: number;cap: number;modelId?: string;+ /** Set when reason is 'no_pricing': the lookup-and-register guidance (no-pricing.ts). */+ pricing?: NoPricingGuidance;constructor(message: string,- opts: { reason: BudgetReason; spent: number; cap: number; modelId?: string },+ opts: { reason: BudgetReason; spent: number; cap: number; modelId?: string; pricing?: NoPricingGuidance },) {super(message);this.name = 'BudgetExhausted';@@ -179,6 +182,7 @@ export class BudgetExhausted extends Error {this.spent = opts.spent;this.cap = opts.cap;this.modelId = opts.modelId;+ if (opts.pricing) this.pricing = opts.pricing;}}@@ -282,12 +286,12 @@ export class BudgetTracker {if (this.opts.maxCostUsd !== undefined) {// 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.+ // void the contract. The refusal tells the agent to look the rate up+ // and register it (`gbrain pricing set`), then retry.+ const pricing = noPricingGuidance(estimate.modelId, estimate.kind);const pricingFile = estimate.kind === 'chat' ? 'model-pricing.ts' : 'embedding-pricing.ts';- const msg = `${this.opts.label}: no pricing entry for model "${estimate.modelId}" (kind=${estimate.kind}). ` +- `Add it to src/core/${pricingFile}, declare an operator rate via ` +- `\`gbrain config set pricing.overrides '{"${estimate.modelId}": <usd-per-1M-tokens>}'\` (#4312), ` +- `or drop --max-cost.`;+ const msg = `${noPricingMessage(pricing, { label: this.opts.label, capUsd: this.opts.maxCostUsd })} ` ++ `(To ship the rate with gbrain itself, add it to src/core/${pricingFile}.)`;appendAuditLine(this.auditPath, {schema_version: 1,ts: new Date().toISOString(),@@ -308,6 +312,7 @@ export class BudgetTracker {spent: this.cumulativeUsd,cap: this.opts.maxCostUsd,modelId: estimate.modelId,+ pricing,});}// Legacy warn-once path — cap unset.@@ -316,7 +321,7 @@ export class BudgetTracker {_unpricedWarnings.add(memoKey);process.stderr.write(`[budget] BUDGET_TRACKER_NO_PRICING: model "${estimate.modelId}" (kind=${estimate.kind}) not in pricing maps. ` +- `Cost gate disabled for this call.\n`,+ `Running it without a cost gate; to meter it, register its rate: ${pricingSetCommand(estimate.modelId, estimate.kind)}\n`,);}appendAuditLine(this.auditPath, {diff --git a/src/core/budget/no-pricing.ts b/src/core/budget/no-pricing.tsnew file mode 100644index 0000000000..59bed1bbfb--- /dev/null+++ b/src/core/budget/no-pricing.ts@@ -0,0 +1,86 @@+/**+ * The one `no_pricing` refusal: what an agent needs when a cost cap the user+ * set cannot be enforced because gbrain has no price for the model.+ *+ * Every surface that reports `no_pricing` (BudgetTracker.reserve, enrich,+ * conversation facts, skillopt, the embedding migration authorization, and+ * the cycle warnings that point at the same registration) builds its text and+ * structured fields here, so the guidance cannot drift between them.+ *+ * Registration (`gbrain pricing set`) is trusted-local CLI only: a remote MCP+ * caller could otherwise declare a $0 rate and void the cap. The guidance+ * therefore always names the exact command and tells a remote caller to ask+ * the brain's operator to run it.+ */++import { ERROR_CATALOGUE } from '../error-catalogue.ts';+import { splitProviderModelId } from '../model-id.ts';+import type { BudgetKind } from './reservation-cost.ts';++export interface NoPricingGuidance {+ /** Stable wire code. */+ code: 'no_pricing';+ model: string;+ provider: string | null;+ kind: BudgetKind;+ /** Rates `gbrain pricing set` needs, each in USD per 1M tokens. */+ units: Array<'usd_per_1m_input_tokens' | 'usd_per_1m_output_tokens' | 'usd_per_1m_tokens'>;+ /** What to look up before registering. */+ lookup: string;+ /** The literal registration command, with placeholders for the rates and source URL. */+ register_command: string;+ /** Registration runs only through the trusted local CLI on the brain host; never over MCP. */+ register_scope: 'local_cli';+ docs: string;+}++const KIND_NOUN: Record<BudgetKind, string> = { chat: 'chat', embed: 'embedding', rerank: 'reranker', decide: 'decision' };++function shellArg(value: string): string {+ return /^[\w.:/@+=-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;+}++/** 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>`;+}++export function noPricingGuidance(modelId: string, kind: BudgetKind): NoPricingGuidance {+ const provider = splitProviderModelId(modelId).provider;+ const units: NoPricingGuidance['units'] = kind === 'chat'+ ? ['usd_per_1m_input_tokens', 'usd_per_1m_output_tokens']+ : ['usd_per_1m_tokens'];+ const rate = kind === 'chat' ? 'USD per 1M input tokens and USD per 1M output tokens' : 'USD per 1M tokens';+ return {+ code: 'no_pricing',+ model: modelId,+ provider,+ kind,+ units,+ lookup: `Look up ${provider ?? 'the provider'}'s current price for ${modelId} (for example, web-search its pricing page): ${rate}.`,+ register_command: pricingSetCommand(modelId, kind),+ register_scope: 'local_cli',+ docs: ERROR_CATALOGUE.no_pricing.docs,+ };+}++/** The steps after the cause: look up, register, retry, and the remote-caller route. */+export function noPricingSteps(g: NoPricingGuidance): string {+ return `${g.lookup} Register it on the brain host (saved in pricing.overrides) with: ${g.register_command} — then retry. ` ++ `Over MCP or another remote connection you cannot register prices; ask the brain's operator to run that command. ` ++ `See ${g.docs}`;+}++/**+ * The full refusal text: a one-line cause, then the steps. `label` prefixes+ * the cause (the tracker's phase/command label); `capUsd` names the cap.+ */+export function noPricingMessage(g: NoPricingGuidance, opts: { label?: string; capUsd?: number } = {}): string {+ const cap = opts.capUsd !== undefined && Number.isFinite(opts.capUsd) ? `the $${opts.capUsd.toFixed(2)} cost cap` : 'the cost cap';+ const who = g.provider ? ` (provider ${g.provider})` : '';+ 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)}`;+}diff --git a/src/core/cycle/budget-meter.ts b/src/core/cycle/budget-meter.tsindex ff95096d90..d8aac0e13d 100644--- a/src/core/cycle/budget-meter.ts+++ b/src/core/cycle/budget-meter.ts@@ -34,6 +34,7 @@ import { canonicalLookup, type ModelPricing } from '../model-pricing.ts';import type { BrainEngine } from '../engine.ts';import { splitProviderModelId } from '../model-id.ts';import { overrideFor, type PricingOverrides } from '../budget/reservation-cost.ts';+import { pricingSetCommand } from '../budget/no-pricing.ts';// Re-exported beside loadAllowUnpriced so meter call sites read both knobs from one module.export { loadPricingOverrides } from '../budget/budget-tracker.ts';@@ -189,8 +190,9 @@ export class BudgetMeter {process.stderr.write(`[budget] BUDGET_METER_NO_PRICING: model "${estimate.modelId}" has no canonical pricing. ` +(this.opts.allowUnpriced- ? `Budget gate disabled for this model (dream.budget.allow_unpriced=true).\n`- : `Metering it at the Sonnet-tier fallback rate; set dream.budget.allow_unpriced=true to bypass.\n`),+ ? `Budget gate disabled for this model (dream.budget.allow_unpriced=true). `+ : `Metering it at the Sonnet-tier fallback rate; set dream.budget.allow_unpriced=true to bypass. `) ++ `To meter its real price, look it up and register it: ${pricingSetCommand(estimate.modelId, 'chat')}\n`,);}}diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.tsindex b9f6266b2c..98fe57acfe 100644--- a/src/core/cycle/conversation-facts-backfill.ts+++ b/src/core/cycle/conversation-facts-backfill.ts@@ -60,6 +60,7 @@ import {// the drift-guarded set in test/conversation-facts-type-allowlist-drift.test.ts.import { ALLOWED_TYPES, type AllowedType } from '../facts/conversation-types.ts';import { conversationFactsCostCap } from '../facts/conversation-budget.ts';+import { noPricingMessage } from '../budget/no-pricing.ts';/** Per-phase wrapper opts. */export interface ConversationFactsBackfillPhaseOpts {@@ -337,6 +338,7 @@ export async function runPhaseConversationFactsBackfill(budget_exhausted: true,budget_reason: err.reason,budget_model: err.modelId,+ ...(err.pricing ? { budget_pricing: err.pricing } : {}),error: err.message,};} else if (isAbortError(err)) {@@ -416,7 +418,10 @@ export async function runPhaseConversationFactsBackfill((r) => r.error || r.pages_failed > 0 || r.budget_reason === 'no_pricing',);const status = anyError ? 'warn' : 'ok';- const summary = `${totals.facts_inserted} facts inserted across ${totals.sources_processed}/${sources.length} sources, ~$${totalSpent.toFixed(4)} spent`;+ const noPricing = [...new Map(Object.values(perSourceResults)+ .flatMap((r) => r.budget_pricing ? [[r.budget_pricing.model, r.budget_pricing] as const] : [])).values()];+ const summary = `${totals.facts_inserted} facts inserted across ${totals.sources_processed}/${sources.length} sources, ~$${totalSpent.toFixed(4)} spent` ++ noPricing.map((g) => `. ${noPricingMessage(g)}`).join('');return {phase: 'conversation_facts_backfill',@@ -446,6 +451,7 @@ export async function runPhaseConversationFactsBackfill(// #3627: per-source cap enforcement observability.sources_budget_exhausted: sourcesBudgetExhausted,sources_walltime_exhausted: sourcesWalltimeExhausted,+ no_pricing: noPricing,types: cfg.types,max_cost_usd: cfg.maxCostUsd,cost_cap_enforced: costCap !== undefined,diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 81e6f592d1..4db5e241c7 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -71,6 +71,7 @@ import { truncateUtf8 } from '../text-safe.ts';import { corpusTextForExtraction } from '../context/corpus-segments.ts';import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';+import { pricingSetCommand } from '../budget/no-pricing.ts';import type { MaintenanceWriteWait } from '../persistence/maintenance-wait.ts';import { connectorAtomExclusionSql } from './connector-atoms.ts';import { resolveExtractAtomsCostGate, resolveEmbedModelForCostGate } from './extract-atoms-cost-gate.ts';@@ -967,15 +968,14 @@ export async function runPhaseExtractAtoms(console.error(`[extract_atoms] ${costGate.unpricedKind} model "${costGate.unpricedModel}" is not in the pricing maps; ` +`running without a cost gate (a cap cannot be enforced on an unpriced model). ` +- `Declare an operator rate to restore the cap: ` +- `gbrain config set pricing.overrides '{"${costGate.unpricedModel}": <usd-per-1M-tokens>}' (0 for local inference).`,+ `Look up its per-token price and register it to restore the cap: ` ++ `${pricingSetCommand(costGate.unpricedModel!, costGate.unpricedKind === 'embed' ? 'embed' : 'chat')} (--rate 0 for local inference).`,);} else if (costGate.zeroPricedEmbedModel) {console.error(`[extract_atoms] embed model "${costGate.zeroPricedEmbedModel}" is not in the pricing maps; ` +`cycle.extract_atoms.budget_usd is set, so the $${budgetCap.toFixed(2)} cap stays enforced and embeds bill at $0 under it. ` +- `Declare its real rate to meter them: ` +- `gbrain config set pricing.overrides '{"${costGate.zeroPricedEmbedModel}": <usd-per-1M-tokens>}'.`,+ `Look up its real price and register it to meter them: ${pricingSetCommand(costGate.zeroPricedEmbedModel, 'embed')}.`,);}const budgetTracker = opts.attempt?.budgetTracker ?? new BudgetTracker({diff --git a/src/core/embedding-migration-budget.ts b/src/core/embedding-migration-budget.tsindex c0c1edaa13..7a4a4bfd66 100644--- a/src/core/embedding-migration-budget.ts+++ b/src/core/embedding-migration-budget.ts@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';import type { BrainEngine } from './engine.ts';import { loadPricingOverrides } from './budget/budget-tracker.ts';import { reservationCostUsd, usageCostUsd, type BudgetKind } from './budget/reservation-cost.ts';+import { noPricingGuidance, noPricingSteps } from './budget/no-pricing.ts';import type { AIInvocation, AIInvocationPermit, AIInvocationUsage } from './ai/invocation-guard.ts';import { MIGRATION_STATE_KEY, readMigrationState, type EmbeddingMigrationPlan, type MigrationState } from './embedding-migration.ts';import type { DbLockHandle } from './db-lock.ts';@@ -147,7 +148,7 @@ export async function authorizeMigrationBudget(engine: BrainEngine, plan: Embeddconst kind: BudgetKind = call.kind === 'embedding' ? 'embed' : 'rerank';const reserved = reservationCostUsd(call.model, kind, call.maxInputTokens!, 0, pricingOverrides);if (reserved === null) {- throw new Error(`Migration authorization cannot price ${call.model} (${kind}); no request dispatched. Declare an operator rate with gbrain config set pricing.overrides '{"${call.model}": <usd-per-1M-tokens>}'.`);+ throw new Error(`Migration authorization cannot price ${call.model} (${kind}); no request dispatched. ${noPricingSteps(noPricingGuidance(call.model, kind))}`);}const attempt = randomUUID();await engine.transaction(async tx => {diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 9e81a0b87d..3653765244 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -37,6 +37,7 @@ export const ERROR_CATALOGUE = {repair_kind_unavailable: { code: 'unavailable', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' },colon_slug_windows_write_through: { code: 'colon_slug_windows_write_through', docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through' },embedding_auth_failed: { code: 'embedding_auth_failed', docs: 'docs/guides/write-refusals.md#embedding_auth_failed' },+ no_pricing: { code: 'no_pricing', docs: 'docs/guides/write-refusals.md#no_pricing' },} as const satisfies Record<string, CatalogueEntry>;export type CatalogueName = keyof typeof ERROR_CATALOGUE;diff --git a/src/core/facts/conversation-budget.ts b/src/core/facts/conversation-budget.tsindex a390b3a00d..253afded1a 100644--- a/src/core/facts/conversation-budget.ts+++ b/src/core/facts/conversation-budget.ts@@ -3,6 +3,7 @@ import { getFactsExtractionModel } from './extract.ts';import { resolveModel, resolveTierDefault } from '../model-config.ts';import { normalizeModelId } from '../model-id.ts';import { isModelPriceable, type PricingOverrides } from '../budget/budget-tracker.ts';+import { pricingSetCommand } from '../budget/no-pricing.ts';/** Default USD ceilings cannot account for unpriced chat routes. Explicit* ceilings stay fail-closed, including either of the cycle's two cost caps.@@ -22,6 +23,6 @@ export async function conversationFactsCostCap(}const unpriced = models.find(model => !isModelPriceable(model, 'chat', overrides));if (!unpriced) return cap;- console.error(`[conversation-facts] ${unpriced} has no pricing; default USD cap is not enforced. Configure pricing.overrides to enforce a USD cap; explicit caps remain fail-closed.`);+ console.error(`[conversation-facts] ${unpriced} has no pricing; default USD cap is not enforced. To enforce it, look up the model's price and register it: ${pricingSetCommand(unpriced, 'chat')}. Explicit caps remain fail-closed.`);return undefined;}diff --git a/src/core/minions/handlers/embed-backfill.ts b/src/core/minions/handlers/embed-backfill.tsindex 44254d623d..432ae8f04c 100644--- a/src/core/minions/handlers/embed-backfill.ts+++ b/src/core/minions/handlers/embed-backfill.ts@@ -42,6 +42,7 @@ import {loadPricingOverrides,type PricingOverrides,} from '../../budget/budget-tracker.ts';+import { pricingSetCommand } from '../../budget/no-pricing.ts';import { getEmbeddingModel, withBudgetTracker } from '../../ai/gateway.ts';import { embedStaleForSource } from '../../embed-stale.ts';import { createEmbedStallWatchdog, resolveEmbedStallAbortSeconds } from '../../embed-stall.ts';@@ -187,7 +188,8 @@ function capForModel(if (cap.defaulted && modelId && !isModelPriceable(modelId, 'embed', pricingOverrides)) {console.error(`[embed-backfill] model "${modelId}" is not in the pricing maps; ` +- `running without the default per-job cost gate. Add pricing.overrides ` ++ `running without the default per-job cost gate. Look up its price and register it ` ++ `(${pricingSetCommand(modelId, 'embed')}) ` +`or set embed.backfill_max_usd to an explicit numeric cap to fail closed.`,);return undefined;diff --git a/src/core/skillopt/orchestrator.ts b/src/core/skillopt/orchestrator.tsindex c82ce1fd65..75f4b36dd9 100644--- a/src/core/skillopt/orchestrator.ts+++ b/src/core/skillopt/orchestrator.ts@@ -99,7 +99,7 @@import { assertLegacySkillWriter } from '../skillpack/writer-guard.ts';import { randomUUID } from 'node:crypto';import * as fs from 'node:fs';-import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';+import { BudgetExhausted, BudgetTracker, loadPricingOverrides, type NoPricingGuidance } from '../budget/budget-tracker.ts';import type { PricingOverrides } from '../budget/reservation-cost.ts';import { buildModelsUsed } from '../budget/models-used.ts';import { withBudgetTracker } from '../ai/gateway.ts';@@ -372,6 +372,8 @@ export function classifyAbortError(outcome: 'aborted' | 'errored';abortReason: 'budget_exhausted' | 'runtime_exceeded' | 'sigint' | 'error';abortDetail: string;+ /** A no_pricing abort's lookup-and-register guidance. */+ pricing?: NoPricingGuidance;} {const msg = err instanceof Error ? err.message : String(err);if (err instanceof BudgetExhausted) {@@ -379,6 +381,7 @@ export function classifyAbortError(outcome: 'aborted',abortReason: err.reason === 'runtime' ? 'runtime_exceeded' : 'budget_exhausted',abortDetail: msg,+ ...(err.pricing ? { pricing: err.pricing } : {}),};} else if (msg.includes(SKILLOPT_RUNTIME_EXCEEDED)) {return {@@ -1044,7 +1047,7 @@ async function runOptimizationLoop(// #3516: abort/error detail rides the receipt so --json consumers and the// CLI's stderr summary both see WHY, not just that the run died....(abortReason !== undefined ? { abort_reason: abortReason } : {}),- ...(abortDetail !== undefined ? { abort_detail: abortDetail } : {}),+ ...(abortDetail !== undefined ? { abort_detail: abortDetail, ...(caught?.pricing ? { no_pricing: caught.pricing } : {}) } : {}),stop_reason: stopReason,...(tally.reflect_errors.length > 0 ? { reflect_errors: [...tally.reflect_errors] } : {}),...(tally.invalid_edits_dropped > 0 ? { reflect_invalid_edits_dropped: tally.invalid_edits_dropped } : {}),diff --git a/src/core/skillopt/types.ts b/src/core/skillopt/types.tsindex 43ee4b10e5..0b37bf70c7 100644--- a/src/core/skillopt/types.ts+++ b/src/core/skillopt/types.ts@@ -16,6 +16,7 @@ import type { BrainEngine } from '../engine.ts';import type { OperationContext } from '../ops/contract.ts';import type { ToolLoopStopReason } from '../ai/gateway.ts';import type { ModelUsageRow } from '../budget/models-used.ts';+import type { NoPricingGuidance } from '../budget/no-pricing.ts';import type { ModelsPlanEntry, SkillOptModels, StrictVerdict } from './models-plan.ts';// ─── Benchmarks + judges ──────────────────────────────────────────────────@@ -250,6 +251,8 @@ export interface RunReceipt {// reason + the underlying error message, mirrored from the audit trail.abort_reason?: 'budget_exhausted' | 'runtime_exceeded' | 'sigint' | 'error';abort_detail?: string;+ /** no_pricing abort: look up the model's price and register it (`register_command`), then retry. */+ no_pricing?: NoPricingGuidance;/** #5584: why the loop stopped. */stop_reason?: 'completed' | 'early_stop_unusable_output' | 'aborted';/** #5584: optimizer-reply errors (reflect + one-shot), deduped, max 20 x 300 chars. */