Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(skillopt): #5563 + A-N4 default cap warns on unpriced models, explicit cap refuses before spend, preflight stops inventing prices

time-attack03c52f742c72
diff --git a/src/commands/skillopt.ts b/src/commands/skillopt.ts
index 84af325d24..f4da79badd 100644
--- a/src/commands/skillopt.ts
+++ b/src/commands/skillopt.ts
@@ -26,6 +26,10 @@ import { parsePositiveInt } from '../core/skillopt/output-cap.ts';
import { serializeError, StructuredAgentError } from '../core/errors.ts';
import type { BrainEngine } from '../core/engine.ts';
import type { RunReceipt, SkillOptOpts } from '../core/skillopt/types.ts';
+import { capNotice, mergeCapFlag, parseCapFlag, type CapFlag } from '../core/budget/cap-flag.ts';
+
+/** Per-run cost cap when no cap flag is passed (a `default` cap: unpriced models warn and run). */
+const DEFAULT_SKILLOPT_MAX_COST_USD = 5.0;
interface ParsedFlags {
skillName: string;
@@ -54,7 +58,12 @@ interface ParsedFlags {
/** F11: optional held-out test set path. REQUIRED (non-empty) to mutate a bundled skill. */
heldOutPath?: string;
json: boolean;
+ /** 0 = uncapped (`--max-usd off`, `--no-max-cost`, legacy `--max-cost-usd 0`). */
maxCostUsd: number;
+ /** `user` when a cap flag was passed, `default` for the $5 default (#5563). */
+ maxCostSource: 'user' | 'default';
+ /** The cap flag spelling the user typed, when any. */
+ maxCostFlag?: string;
maxRuntimeMin: number;
force: boolean;
resumeRunId?: string;
@@ -88,6 +97,11 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strin
process.exit(0);
}
+ if (parsed.maxCostFlag === '--max-cost-usd' && parsed.maxCostUsd === 0) {
+ process.stderr.write('gbrain skillopt: --max-cost-usd 0 is deprecated; it still means uncapped, but write --max-usd off.\n');
+ }
+ process.stderr.write(`[skillopt] ${capNotice({ usd: parsed.maxCostUsd > 0 ? parsed.maxCostUsd : null, source: parsed.maxCostSource, flag: parsed.maxCostFlag })}\n`);
+
if (!engine) {
process.stderr.write('gbrain skillopt: requires a configured brain (engine connection failed)\n');
process.exit(2);
@@ -125,6 +139,7 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strin
dryRun: parsed.dryRun,
modelsStrict: parsed.modelsStrict,
maxCostUsd: parsed.maxCostUsd,
+ maxCostSource: parsed.maxCostSource,
});
if (run.dry_run) exitDryRun(run.models_plan, run.strict, parsed.json, {});
if (parsed.json) {
@@ -146,6 +161,7 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strin
engine,
skillsDir,
perSkillMaxCostUsd: parsed.maxCostUsd,
+ maxCostSource: parsed.maxCostSource === 'user' || parsed.brainWideMaxCostUsd !== undefined ? 'user' : 'default',
brainWideMaxCostUsd: parsed.brainWideMaxCostUsd ?? 10.0,
optimizerModel,
targetModel,
@@ -209,6 +225,7 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strin
bootstrapReviewed: parsed.bootstrapReviewed,
...(parsed.heldOutPath ? { heldOutPath: parsed.heldOutPath } : {}),
maxCostUsd: parsed.maxCostUsd,
+ maxCostSource: parsed.maxCostSource,
maxRuntimeMin: parsed.maxRuntimeMin,
force: parsed.force,
});
@@ -265,6 +282,7 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strin
...(parsed.heldOutPath ? { heldOutPath: parsed.heldOutPath } : {}),
bootstrapReviewed: parsed.bootstrapReviewed,
maxCostUsd: parsed.maxCostUsd,
+ maxCostSource: parsed.maxCostSource,
maxRuntimeMin: parsed.maxRuntimeMin,
force: parsed.force,
});
@@ -310,6 +328,7 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strin
bootstrapReviewed: parsed.bootstrapReviewed,
json: parsed.json,
maxCostUsd: parsed.maxCostUsd,
+ maxCostSource: parsed.maxCostSource,
maxRuntimeMin: parsed.maxRuntimeMin,
force: parsed.force,
...(parsed.resumeRunId ? { resumeRunId: parsed.resumeRunId } : {}),
@@ -433,7 +452,7 @@ export function parseFlags(args: string[]): ParsedFlags {
let allowMutateBundled = false;
let heldOutPath: string | undefined;
let json = false;
- let maxCostUsd = 5.0;
+ let cap: CapFlag | undefined;
let maxRuntimeMin = 30;
let force = false;
let resumeRunId: string | undefined;
@@ -486,11 +505,12 @@ export function parseFlags(args: string[]): ParsedFlags {
if (a === '--allow-mutate-bundled') { allowMutateBundled = true; i += 1; continue; }
if (a === '--held-out') { heldOutPath = args[++i]; i += 1; continue; }
if (a === '--json') { json = true; i += 1; continue; }
- // #3516: 0 is accepted and means UNCAPPED — pricing misses for unpriced
- // model ids (openrouter:*, litellm:*) then warn-once instead of aborting
- // the run with BudgetExhausted(no_pricing).
- if (a === '--max-cost-usd') { maxCostUsd = mustNonNegFloat(args[++i], '--max-cost-usd'); i += 1; continue; }
- if (a === '--no-max-cost') { maxCostUsd = 0; i += 1; continue; }
+ // D19: one shared parser. `--max-usd N|off` is canonical; the legacy
+ // `--max-cost-usd` keeps #3516's meaning for 0 (uncapped) and
+ // `--no-max-cost` is `--max-usd off`. Disagreeing cap flags are refused.
+ if (a === '--max-usd') { cap = mergeCapFlag(cap, parseCapFlag(a, args[++i])); i += 1; continue; }
+ if (a === '--max-cost-usd') { cap = mergeCapFlag(cap, parseCapFlag(a, args[++i], { zero: 'off' })); i += 1; continue; }
+ if (a === '--no-max-cost') { cap = mergeCapFlag(cap, { flag: a, usd: null }); i += 1; continue; }
if (a === '--max-runtime-min') { maxRuntimeMin = mustInt(args[++i], '--max-runtime-min'); i += 1; continue; }
if (a === '--force') { force = true; i += 1; continue; }
if (a === '--resume') { resumeRunId = args[++i]; i += 1; continue; }
@@ -569,7 +589,9 @@ export function parseFlags(args: string[]): ParsedFlags {
allowMutateBundled,
...(heldOutPath !== undefined ? { heldOutPath } : {}),
json,
- maxCostUsd,
+ maxCostUsd: cap === undefined ? DEFAULT_SKILLOPT_MAX_COST_USD : cap.usd ?? 0,
+ maxCostSource: cap === undefined ? 'default' : 'user',
+ ...(cap ? { maxCostFlag: cap.flag } : {}),
maxRuntimeMin,
force,
...(resumeRunId !== undefined ? { resumeRunId } : {}),
@@ -597,14 +619,6 @@ function mustFloat(v: string | undefined, flag: string): number {
return n;
}
-/** #3516: like mustFloat but 0 is allowed (0 = uncapped for --max-cost-usd). */
-function mustNonNegFloat(v: string | undefined, flag: string): number {
- const n = Number(v);
- if (!Number.isFinite(n) || n < 0) {
- throw new Error(`${flag} requires a non-negative number (got '${v}'; 0 disables the cap)`);
- }
- return n;
-}
function handleErrorAndExit(err: unknown, json: boolean, exitCode: number): never {
if (json) {
diff --git a/src/core/ops/skillopt.ts b/src/core/ops/skillopt.ts
index da2eb278eb..bd82ffc218 100644
--- a/src/core/ops/skillopt.ts
+++ b/src/core/ops/skillopt.ts
@@ -138,7 +138,7 @@ const run_skillopt: Operation = {
epochs: { type: 'number', description: 'Default 4' },
batch_size: { type: 'number', description: 'Default 8' },
lr: { type: 'number', description: 'Default 4' },
- max_cost_usd: { type: 'number', description: 'Default 5.00' },
+ max_cost_usd: { type: 'number', description: 'Default 5.00 (an unpriced model then warns and runs). When set, an unpriced model is refused with no_pricing.' },
reflect_max_tokens: { type: 'number', description: 'Optimizer output cap (positive integer, clamped to 256..32000). Default: skillopt.reflect_max_tokens config, else 32000 for thinking optimizers and 4096 otherwise.' },
no_mutate: { type: 'boolean', description: 'Write proposed.md without replacing SKILL.md' },
allow_mutate_bundled: { type: 'boolean', description: 'Required to mutate bundled skills' },
@@ -270,6 +270,7 @@ const run_skillopt: Operation = {
...(heldOutPath ? { heldOutPath } : {}),
json: true,
maxCostUsd: (p.max_cost_usd as number) ?? 5.0,
+ maxCostSource: p.max_cost_usd === undefined ? 'default' : 'user',
maxRuntimeMin: 30,
force: false,
});
diff --git a/src/core/skillopt/batch.ts b/src/core/skillopt/batch.ts
index a62478660d..58ede129fd 100644
--- a/src/core/skillopt/batch.ts
+++ b/src/core/skillopt/batch.ts
@@ -26,6 +26,8 @@ export interface BatchAllOpts {
skillsDir: string;
/** Per-skill budget (each skill gets its own tracker). */
perSkillMaxCostUsd: number;
+ /** `user` when either cap came from a flag (refuses unpriced models), `default` otherwise (#5563). Default `user`. */
+ maxCostSource?: 'user' | 'default';
/** Brain-wide cumulative ceiling. */
brainWideMaxCostUsd: number;
/** Common knobs threaded to each skill. */
@@ -119,6 +121,7 @@ export async function runBatchAll(opts: BatchAllOpts): Promise<BatchAllResult> {
bootstrapReviewed: false,
json: true,
maxCostUsd: cap,
+ maxCostSource: opts.maxCostSource ?? 'user',
maxRuntimeMin: 30,
force: opts.force,
};
@@ -174,6 +177,8 @@ export interface FleetOpts {
/** F11: optional held-out test set (one skill, so a single path is valid here). */
heldOutPath?: string;
maxCostUsd: number;
+ /** See SkillOptOpts.maxCostSource. Default `user`. */
+ maxCostSource?: 'user' | 'default';
maxRuntimeMin: number;
force: boolean;
}
@@ -259,6 +264,7 @@ export async function runFleet(opts: FleetOpts): Promise<FleetResult> {
...(opts.heldOutPath ? { heldOutPath: opts.heldOutPath } : {}),
json: true,
maxCostUsd: opts.maxCostUsd,
+ maxCostSource: opts.maxCostSource ?? 'user',
maxRuntimeMin: opts.maxRuntimeMin,
force: opts.force,
};
diff --git a/src/core/skillopt/bootstrap-run.ts b/src/core/skillopt/bootstrap-run.ts
index a186c6b8c8..1ef0d8493d 100644
--- a/src/core/skillopt/bootstrap-run.ts
+++ b/src/core/skillopt/bootstrap-run.ts
@@ -36,6 +36,8 @@ export interface GuardedBootstrapOpts {
modelsStrict?: boolean;
/** USD cap for the bootstrap calls; 0 = uncapped. */
maxCostUsd: number;
+ /** `user` (default) refuses an unpriced optimizer; `default` warns and runs it (#5563). */
+ maxCostSource?: 'user' | 'default';
/** Test seam — substitute gateway.chat. */
chatFn?: typeof gatewayChat;
}
@@ -53,7 +55,7 @@ export async function runGuardedBootstrap(opts: GuardedBootstrapOpts): Promise<G
const pricingOverrides = await loadPricingOverrides(opts.engine);
const tracker = new BudgetTracker({
- ...(opts.maxCostUsd > 0 ? { maxCostUsd: opts.maxCostUsd } : {}),
+ ...(opts.maxCostUsd > 0 ? { maxCostUsd: opts.maxCostUsd, capSource: opts.maxCostSource ?? 'user' } : {}),
...(pricingOverrides ? { pricingOverrides } : {}),
label: `skillopt-bootstrap:${opts.skillName}`,
});
diff --git a/src/core/skillopt/help.ts b/src/core/skillopt/help.ts
index b7895b95a4..af50a7b3a2 100644
--- a/src/core/skillopt/help.ts
+++ b/src/core/skillopt/help.ts
@@ -61,18 +61,22 @@ Modes:
--json Machine-readable stdout
Safety:
- --max-cost-usd N Hard cap. Default 5.00. Preflight refuses
- if estimate exceeds. 0 disables the cap
- (unpriced model ids then warn-once instead
- of aborting with no_pricing).
- --no-max-cost Shorthand for --max-cost-usd 0.
+ --max-usd N|off Hard cap. Default 5.00. Preflight refuses
+ if estimate exceeds. A model with no price
+ runs under the default with a warning; an
+ explicit cap refuses it before any spend
+ until you register its rate (gbrain pricing
+ set). off runs uncapped (spend still ledgered).
+ --max-cost-usd N Legacy spelling of --max-usd; 0 still means
+ uncapped (deprecated: write --max-usd off).
+ --no-max-cost Shorthand for --max-usd off.
--max-runtime-min N Wall-clock cap. Default 30
--force Bypass dirty-working-tree refusal (rare)
--resume <run-id> Resume a prior interrupted run
Batch + fleet + background:
--all Optimize every skill with a benchmark
- (per-skill cap = --max-cost-usd; brain-wide
+ (per-skill cap = --max-usd; brain-wide
cap = --brain-wide-max-cost-usd, default $10)
--brain-wide-max-cost-usd N Cumulative ceiling for --all (default 10.00)
--target-models a,b,c Fleet mode: optimize ONCE per model. Always
diff --git a/src/core/skillopt/job.ts b/src/core/skillopt/job.ts
index 78b1513e11..1db22dc3ba 100644
--- a/src/core/skillopt/job.ts
+++ b/src/core/skillopt/job.ts
@@ -27,7 +27,7 @@ import type { SkillOptOpts } from './types.ts';
export type SkillOptJobInput = Pick<SkillOptOpts,
| 'skillsDir' | 'skillName' | 'benchmarkPath' | 'epochs' | 'batchSize' | 'lr' | 'lrSchedule' | 'split'
| 'reflectMaxTokens' | 'mode' | 'dryRun' | 'noMutate' | 'allowMutateBundled' | 'heldOutPath'
- | 'bootstrapReviewed' | 'maxCostUsd' | 'maxRuntimeMin' | 'force'
+ | 'bootstrapReviewed' | 'maxCostUsd' | 'maxCostSource' | 'maxRuntimeMin' | 'force'
> & { models: SkillOptModels; modelFlags: SkillOptModelFlags; modelsStrict: boolean };
export function buildSkillOptJobData(input: SkillOptJobInput): Record<string, unknown> {
@@ -63,6 +63,7 @@ export function buildSkillOptJobData(input: SkillOptJobInput): Record<string, un
...(input.heldOutPath ? { held_out_path: input.heldOutPath } : {}),
bootstrap_reviewed: input.bootstrapReviewed,
max_cost_usd: input.maxCostUsd,
+ ...(input.maxCostSource ? { max_cost_source: input.maxCostSource } : {}),
max_runtime_min: input.maxRuntimeMin,
force: input.force,
};
@@ -118,6 +119,7 @@ export async function runSkillOptJob(engine: BrainEngine, rawData: unknown): Pro
...(data.held_out_path ? { heldOutPath: String(data.held_out_path) } : {}),
json: true,
maxCostUsd: Number(data.max_cost_usd ?? 5.0),
+ maxCostSource: data.max_cost_source === 'default' ? 'default' : 'user',
maxRuntimeMin: Number(data.max_runtime_min ?? 30),
force: Boolean(data.force),
});
diff --git a/src/core/skillopt/orchestrator.ts b/src/core/skillopt/orchestrator.ts
index 75f4b36dd9..66ecab8d4d 100644
--- a/src/core/skillopt/orchestrator.ts
+++ b/src/core/skillopt/orchestrator.ts
@@ -272,6 +272,7 @@ export async function runSkillOpt(opts: SkillOptOpts): Promise<RunSkillOptResult
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
maxCostUsd: opts.maxCostUsd,
+ maxCostSource: opts.maxCostSource ?? 'user',
heldOutSize: heldOutTasks.length,
interactive: process.stderr.isTTY === true,
reflectMaxTokens: reflectCap.maxTokens,
@@ -284,8 +285,17 @@ export async function runSkillOpt(opts: SkillOptOpts): Promise<RunSkillOptResult
trainSize: split.train.length, selSize: split.sel.length, testSize: split.test.length,
optimizerModel: opts.optimizerModel, targetModel: opts.targetModel, judgeModel: opts.judgeModel,
maxCostUsd: opts.maxCostUsd,
+ maxCostSource: opts.maxCostSource ?? 'user',
}) + '\n');
}
+ if (preflightResult.abort_code === 'no_pricing') {
+ throw errorFor({
+ class: 'BudgetExhausted',
+ code: 'no_pricing',
+ message: preflightResult.abort_reason ?? 'no pricing for a model under the cost cap',
+ hint: 'No model call was made. Register the rate with the command above and retry, or pass --max-usd off to run uncapped.',
+ });
+ }
if (!preflightResult.proceed) {
throw errorFor({
class: 'CostCapExceeded',
@@ -525,7 +535,7 @@ async function runOptimizationLoop(
// hard BudgetExhausted(no_pricing) abort to the legacy warn-once path, so
// unpriced model ids (openrouter:*, litellm:*) can run at the user's own risk.
const tracker = new BudgetTracker({
- ...(opts.maxCostUsd > 0 ? { maxCostUsd: opts.maxCostUsd } : {}),
+ ...(opts.maxCostUsd > 0 ? { maxCostUsd: opts.maxCostUsd, capSource: opts.maxCostSource ?? 'user' } : {}),
...(resolved.pricingOverrides ? { pricingOverrides: resolved.pricingOverrides } : {}),
label: `skillopt:${skillName}`,
});
diff --git a/src/core/skillopt/preflight.ts b/src/core/skillopt/preflight.ts
index cedbc7f222..c746fb12ee 100644
--- a/src/core/skillopt/preflight.ts
+++ b/src/core/skillopt/preflight.ts
@@ -29,15 +29,18 @@
* that call, so preflight refuses before any spend and names the role and
* the control that fixes it (`reservation_exceeds_cap`).
*
- * Prices come from the canonical pricing table (model-pricing.ts) via
- * canonicalLookup. For unknown providers `lookupPrice` returns a warn-only
- * Sonnet-tier fallback (preflight estimates, never gates) — the actual
- * fail-loud gate is BudgetTracker's TX2 contract at run time.
+ * Prices come from the shared resolver (`priceFor`: operator
+ * `pricing.overrides`, the claude-cli → Anthropic sibling, canonical rows),
+ * the same chain the run's BudgetTracker uses. A model nothing prices is
+ * reported as unpriced (`est_cost_usd: null`, `unpriced_models`), never at an
+ * invented rate (#5563 / A-N4). Under a cap the user set, an unpriced model
+ * refuses before any spend (`no_pricing`, the shared guidance); under the
+ * default cap it runs with a warning, as the tracker does.
*/
import { defaultMaxOutputTokens } from '../ai/gateway.ts';
-import { reservationCostUsd, type PricingOverrides } from '../budget/reservation-cost.ts';
-import { canonicalLookup } from '../model-pricing.ts';
+import { priceFor, reservationCostUsd, type PricingOverrides } from '../budget/reservation-cost.ts';
+import { noPricingGuidance, noPricingMessage, type NoPricingGuidance } from '../budget/no-pricing.ts';
import { skilloptOutputCap } from './output-cap.ts';
import { JUDGE_SITE_MAX_TOKENS } from './score.ts';
import { VALIDATION_RUNS_PER_TASK } from './types.ts';
@@ -60,6 +63,8 @@ export interface PreflightOpts {
targetModel: string;
judgeModel: string;
maxCostUsd: number;
+ /** Where a positive `maxCostUsd` came from: `user` (a flag; the default when unset) refuses an unpriced model, `default` warns. */
+ maxCostSource?: 'user' | 'default';
/**
* Held-out task count (F11). When > 0, the held-out gate scores baseline +
* candidate on the held-out set at every accepted step. Conservatively
@@ -124,9 +129,12 @@ export interface PreflightEstimate {
judge_calls: number;
est_input_tokens: number;
est_output_tokens: number;
- est_cost_usd: number;
- /** Per-model breakdown for the audit. */
- per_model_cost_usd: Record<string, number>;
+ /** null when a model the run calls has no price (see `unpriced_models`). */
+ est_cost_usd: number | null;
+ /** Per-model breakdown for the audit; null for an unpriced model. */
+ per_model_cost_usd: Record<string, number | null>;
+ /** Models the run can call that nothing prices. */
+ unpriced_models: string[];
/** True when est_cost_usd > maxCostUsd (caller should refuse or prompt). */
exceeds_cap: boolean;
/** The priciest single call any role will reserve (separate from expected cost). */
@@ -139,8 +147,10 @@ export interface PreflightResult {
proceed: boolean;
/** Reason for abort, if proceed=false. */
abort_reason?: string;
- /** Machine code for the abort: one call can never fit the cap, or the expected total exceeds it. */
- abort_code?: 'reservation_exceeds_cap' | 'cost_cap_exceeded';
+ /** Machine code for the abort: one call can never fit the cap, the expected total exceeds it, or a user cap meets an unpriced model. */
+ abort_code?: 'reservation_exceeds_cap' | 'cost_cap_exceeded' | 'no_pricing';
+ /** Set with abort_code 'no_pricing': the lookup-and-register guidance. */
+ no_pricing?: NoPricingGuidance;
}
export function estimateCost(opts: PreflightOpts): PreflightEstimate {
@@ -175,12 +185,17 @@ export function estimateCost(opts: PreflightOpts): PreflightEstimate {
const judge_calls = judgeModels.length > 0 ? judgeCallsRaw : 0;
// Cost per call type. Judge calls price at the priciest judge the run can reach.
- const targetPrice = lookupPrice(opts.targetModel);
- const optimizerPrice = lookupPrice(opts.optimizerModel);
- const judgePrice = judgeModels.map(lookupPrice).reduce(
+ const lookup = (model: string) => priceFor(model, 'chat', opts.pricingOverrides)?.pricing ?? null;
+ const unpriced = [...new Set([opts.targetModel, opts.optimizerModel, ...(judge_calls > 0 ? judgeModels : [])])]
+ .filter((m) => lookup(m) === null);
+ const zero = { input: 0, output: 0 };
+ const targetPrice = lookup(opts.targetModel) ?? zero;
+ const optimizerPrice = lookup(opts.optimizerModel) ?? zero;
+ const judgePrice = judgeModels.map((m) => lookup(m) ?? zero).reduce(
(a, b) => (b.input + b.output > a.input + a.output ? b : a),
- { input: 0, output: 0 },
+ zero,
);
+ const unpricedJudge = judge_calls > 0 && judgeModels.some((m) => unpriced.includes(m));
const rolloutCost = rollout_calls * (
(ROLLOUT_INPUT_TOKENS * targetPrice.input) / 1_000_000
@@ -200,7 +215,7 @@ export function estimateCost(opts: PreflightOpts): PreflightEstimate {
const cachedReflectCost = reflectCost * 0.6;
const cachedJudgeCost = judgeCost * 0.6;
- const total = rolloutCost + cachedReflectCost + cachedJudgeCost;
+ const total = unpriced.length > 0 ? null : rolloutCost + cachedReflectCost + cachedJudgeCost;
void sel_runs_per_step;
const largest = largestReservation(opts);
@@ -214,12 +229,13 @@ export function estimateCost(opts: PreflightOpts): PreflightEstimate {
est_output_tokens: rollout_calls * ROLLOUT_OUTPUT_TOKENS + reflect_calls * REFLECT_OUTPUT_TOKENS + judge_calls * JUDGE_OUTPUT_TOKENS,
est_cost_usd: total,
per_model_cost_usd: {
- [opts.targetModel]: rolloutCost,
- [opts.optimizerModel]: cachedReflectCost,
- [opts.judgeModel]: cachedJudgeCost,
+ [opts.targetModel]: unpriced.includes(opts.targetModel) ? null : rolloutCost,
+ [opts.optimizerModel]: unpriced.includes(opts.optimizerModel) ? null : cachedReflectCost,
+ [opts.judgeModel]: unpricedJudge ? null : cachedJudgeCost,
},
+ unpriced_models: unpriced,
// #3516: maxCostUsd === 0 means uncapped (--no-max-cost) — never refuse.
- exceeds_cap: opts.maxCostUsd > 0 && total > opts.maxCostUsd,
+ exceeds_cap: opts.maxCostUsd > 0 && total !== null && total > opts.maxCostUsd,
...(largest ? { largest_reservation: largest } : {}),
};
}
@@ -235,7 +251,7 @@ export function formatPreflightReport(est: PreflightEstimate, opts: PreflightOpt
` Reflects: ${est.reflect_calls.toLocaleString()} calls`,
` Judges: ${est.judge_calls.toLocaleString()} calls`,
` Tokens: ~${(est.est_input_tokens / 1000).toFixed(0)}K in / ~${(est.est_output_tokens / 1000).toFixed(0)}K out`,
- ` Est. cost: $${est.est_cost_usd.toFixed(2)} (cap: ${opts.maxCostUsd > 0 ? `$${opts.maxCostUsd.toFixed(2)}` : 'uncapped'})`,
+ ` Est. cost: ${est.est_cost_usd === null ? `unpriced (no price for ${est.unpriced_models.join(', ')}; register a rate with gbrain pricing set)` : `$${est.est_cost_usd.toFixed(2)}`} (cap: ${opts.maxCostUsd > 0 ? `$${opts.maxCostUsd.toFixed(2)}${opts.maxCostSource === 'default' ? ' default' : ''}` : 'uncapped'})`,
est.largest_reservation
? ` Per call: largest single call reserves $${est.largest_reservation.reservation_usd!.toFixed(2)} (${est.largest_reservation.role} ${est.largest_reservation.model}, ${est.largest_reservation.max_output_tokens} output tokens)`
: '',
@@ -251,6 +267,17 @@ export function formatPreflightReport(est: PreflightEstimate, opts: PreflightOpt
*/
export function preflight(opts: PreflightOpts): PreflightResult {
const estimate = estimateCost(opts);
+ const unpriced = estimate.unpriced_models[0];
+ if (opts.maxCostUsd > 0 && (opts.maxCostSource ?? 'user') === 'user' && unpriced) {
+ const guidance = noPricingGuidance(unpriced, 'chat');
+ return {
+ estimate,
+ proceed: false,
+ abort_code: 'no_pricing',
+ abort_reason: noPricingMessage(guidance, { label: 'skillopt', capUsd: opts.maxCostUsd }),
+ no_pricing: guidance,
+ };
+ }
const big = estimate.largest_reservation;
if (opts.maxCostUsd > 0 && big && big.reservation_usd! > opts.maxCostUsd) {
return {
@@ -265,20 +292,8 @@ export function preflight(opts: PreflightOpts): PreflightResult {
estimate,
proceed: false,
abort_code: 'cost_cap_exceeded',
- abort_reason: `estimated cost $${estimate.est_cost_usd.toFixed(2)} exceeds --max-cost-usd $${opts.maxCostUsd.toFixed(2)}. Raise the cap with --max-cost-usd ${Math.ceil(estimate.est_cost_usd)} or reduce --epochs/--batch-size.`,
+ abort_reason: `estimated cost $${estimate.est_cost_usd!.toFixed(2)} exceeds --max-cost-usd $${opts.maxCostUsd.toFixed(2)}. Raise the cap with --max-usd ${Math.ceil(estimate.est_cost_usd!)} or reduce --epochs/--batch-size.`,
};
}
return { estimate, proceed: true };
}
-
-function lookupPrice(model: string): { input: number; output: number } {
- // Canonical lookup handles bare/colon/slash forms (fixes this site's prior
- // bare-only limitation, which mispriced `anthropic/...` slash ids).
- const p = canonicalLookup(model);
- if (p) return p;
- // Conservative fallback: assume Sonnet-tier pricing for unknown providers.
- // Don't throw — preflight is for warning, not gating. The actual budget
- // tracker (BudgetTracker TX2) will fail-loud at run time if pricing is
- // truly unknown.
- return { input: 3.0, output: 15.0 };
-}
diff --git a/src/core/skillopt/types.ts b/src/core/skillopt/types.ts
index 0b37bf70c7..4de3f72f30 100644
--- a/src/core/skillopt/types.ts
+++ b/src/core/skillopt/types.ts
@@ -205,6 +205,11 @@ export interface SkillOptOpts {
* misses then warn-once instead of hard-failing, so unpriced model ids
* (openrouter:*, litellm:*) can run. */
maxCostUsd: number;
+ /** Where a positive `maxCostUsd` came from (#5563). `user` (a cap flag; the
+ * value when unset, so legacy callers and queued jobs keep failing closed)
+ * refuses an unpriced model with the no_pricing guidance; `default` (no
+ * flag, the $5 default) warns and runs it while metering priced calls. */
+ maxCostSource?: 'user' | 'default';
maxRuntimeMin: number;
force: boolean;
resumeRunId?: string;
diff --git a/test/skillopt/models-four-paths.serial.test.ts b/test/skillopt/models-four-paths.serial.test.ts
index ea93c1bb11..18720155bc 100644
--- a/test/skillopt/models-four-paths.serial.test.ts
+++ b/test/skillopt/models-four-paths.serial.test.ts
@@ -202,3 +202,35 @@ describe('CLI strict + dry-run contract', () => {
});
});
});
+
+describe('#5563 the cap source reaches runSkillOpt on every path', () => {
+ test('no cap flag is a default cap (unpriced models warn and run); a cap flag is a user cap', async () => {
+ await withEnv(ENV, async () => {
+ const none = await viaCli();
+ expect(none.maxCostUsd).toBe(5);
+ expect(none.maxCostSource).toBe('default');
+ const set = await viaCli(['--max-usd', '2']);
+ expect(set.maxCostUsd).toBe(2);
+ expect(set.maxCostSource).toBe('user');
+ const off = await viaCli(['--max-usd', 'off']);
+ expect(off.maxCostUsd).toBe(0);
+ expect((await viaMcp()).maxCostSource).toBe('default');
+ });
+ });
+
+ test('the background job carries the source; legacy job data without it stays a user cap', async () => {
+ await withEnv(ENV, async () => {
+ expect((await viaJob()).maxCostSource).toBe('user');
+ captured = [];
+ const data = buildSkillOptJobData({
+ skillsDir, skillName: SKILL, benchmarkPath: path.join(skillsDir, SKILL, 'skillopt-benchmark.jsonl'),
+ epochs: 1, batchSize: 2, lr: 4, lrSchedule: 'constant', split: [4, 1, 5], mode: 'patch', dryRun: false,
+ noMutate: false, allowMutateBundled: false, bootstrapReviewed: false, maxCostUsd: 5, maxCostSource: 'default', maxRuntimeMin: 30, force: false,
+ models: await resolveSkillOptModels(engine, {}), modelFlags: {}, modelsStrict: false,
+ });
+ expect(data.max_cost_source).toBe('default');
+ await runSkillOptJob(engine, JSON.parse(JSON.stringify(data)));
+ expect(captured[0]!.maxCostSource).toBe('default');
+ });
+ });
+});
diff --git a/test/skillopt/preflight-pricing-5563.test.ts b/test/skillopt/preflight-pricing-5563.test.ts
new file mode 100644
index 0000000000..994b1ec2a4
--- /dev/null
+++ b/test/skillopt/preflight-pricing-5563.test.ts
@@ -0,0 +1,122 @@
+/**
+ * #5563 + A-N4: skillopt must not block a valid model only for missing
+ * pricing under the default cap, and its preflight must not invent prices.
+ *
+ * Pre-fix, the preflight priced every unknown model at Sonnet rates and
+ * ignored `pricing.overrides` (`est_cost_usd 0.326` next to a 0.032
+ * per-model figure), and the $5 default was a user cap, so the tracker threw
+ * no_pricing at the first reserve with no flag passed.
+ *
+ * Covers the real parser (D19 spellings), the preflight's resolver, its
+ * unpriced reporting and the user-cap refusal.
+ */
+import { describe, expect, test } from 'bun:test';
+import { parseFlags } from '../../src/commands/skillopt.ts';
+import { estimateCost, formatPreflightReport, preflight, type PreflightOpts } from '../../src/core/skillopt/preflight.ts';
+
+const SKILL = 'widget-example';
+const UNPRICED = 'openai:gpt-unreleased-x';
+
+const base: PreflightOpts = {
+ epochs: 2,
+ batchSize: 4,
+ trainSize: 8,
+ selSize: 2,
+ testSize: 2,
+ optimizerModel: UNPRICED,
+ targetModel: UNPRICED,
+ judgeModel: UNPRICED,
+ maxCostUsd: 5,
+ heldOutSize: 0,
+ interactive: false,
+};
+
+describe('A-N4 preflight prices through the shared resolver', () => {
+ test('pricing.overrides price the estimate instead of invented Sonnet rates', () => {
+ const cheap = { [UNPRICED]: { input: 0.01, output: 0.01 } };
+ const est = estimateCost({ ...base, pricingOverrides: cheap });
+ expect(est.unpriced_models).toEqual([]);
+ const tokensCost = (est.est_input_tokens + est.est_output_tokens) * 0.01 / 1_000_000;
+ expect(est.est_cost_usd).not.toBeNull();
+ expect(est.est_cost_usd!).toBeGreaterThan(0);
+ expect(est.est_cost_usd!).toBeLessThanOrEqual(tokensCost);
+ });
+
+ test('an unpriced model is reported as unpriced, never priced at a guessed rate', () => {
+ const est = estimateCost({ ...base, maxCostSource: 'default' });
+ expect(est.est_cost_usd).toBeNull();
+ expect(est.unpriced_models).toEqual([UNPRICED]);
+ expect(est.per_model_cost_usd[UNPRICED]).toBeNull();
+ expect(est.exceeds_cap).toBe(false);
+ const report = formatPreflightReport(est, { ...base, maxCostSource: 'default' });
+ expect(report).toContain(`Est. cost: unpriced (no price for ${UNPRICED}; register a rate with gbrain pricing set)`);
+ expect(report).toContain('cap: $5.00 default');
+ });
+
+ test('a priced target with an unpriced judge names only the judge', () => {
+ const est = estimateCost({ ...base, optimizerModel: 'anthropic:claude-sonnet-4-6', targetModel: 'anthropic:claude-sonnet-4-6' });
+ expect(est.unpriced_models).toEqual([UNPRICED]);
+ expect(est.per_model_cost_usd['anthropic:claude-sonnet-4-6']).toBeGreaterThan(0);
+ });
+});
+
+describe('#5563 preflight policy for unpriced models', () => {
+ test('default cap: proceeds (the tracker warns and runs the model)', () => {
+ const r = preflight({ ...base, maxCostSource: 'default' });
+ expect(r.proceed).toBe(true);
+ });
+
+ test('user cap: refuses before any spend with the shared no_pricing guidance', () => {
+ const r = preflight({ ...base, maxCostSource: 'user', maxCostUsd: 3 });
+ expect(r.proceed).toBe(false);
+ expect(r.abort_code).toBe('no_pricing');
+ expect(r.no_pricing?.model).toBe(UNPRICED);
+ expect(r.abort_reason).toContain(`skillopt: gbrain has no pricing for chat model "${UNPRICED}"`);
+ expect(r.abort_reason).toContain(`gbrain pricing set ${UNPRICED} --input`);
+ });
+
+ test('user cap with a registered rate: proceeds', () => {
+ const r = preflight({ ...base, maxCostSource: 'user', pricingOverrides: { [UNPRICED]: { input: 0.01, output: 0.01 } } });
+ expect(r.proceed).toBe(true);
+ });
+
+ test('uncapped (0): proceeds even when unpriced', () => {
+ expect(preflight({ ...base, maxCostUsd: 0, maxCostSource: 'user' }).proceed).toBe(true);
+ });
+});
+
+describe('D19 skillopt cap flags (real parser)', () => {
+ test('no flag: $5 default cap', () => {
+ const p = parseFlags([SKILL]);
+ expect([p.maxCostUsd, p.maxCostSource]).toEqual([5, 'default']);
+ });
+ test('--max-usd N: user cap', () => {
+ const p = parseFlags([SKILL, '--max-usd', '2.5']);
+ expect([p.maxCostUsd, p.maxCostSource, p.maxCostFlag]).toEqual([2.5, 'user', '--max-usd']);
+ });
+ for (const word of ['off', 'unlimited', 'none', 'OFF']) {
+ test(`--max-usd ${word}: uncapped`, () => {
+ const p = parseFlags([SKILL, '--max-usd', word]);
+ expect([p.maxCostUsd, p.maxCostSource]).toEqual([0, 'user']);
+ });
+ }
+ test('--no-max-cost and legacy --max-cost-usd 0 stay uncapped', () => {
+ expect(parseFlags([SKILL, '--no-max-cost']).maxCostUsd).toBe(0);
+ expect(parseFlags([SKILL, '--max-cost-usd', '0']).maxCostUsd).toBe(0);
+ expect(parseFlags([SKILL, '--max-cost-usd', '4']).maxCostUsd).toBe(4);
+ });
+ test('--max-usd 0 is refused as ambiguous', () => {
+ expect(() => parseFlags([SKILL, '--max-usd', '0'])).toThrow(/--max-usd 0 is ambiguous: pass --max-usd off/);
+ });
+ test('missing and invalid values are refused', () => {
+ expect(() => parseFlags([SKILL, '--max-usd'])).toThrow(/--max-usd needs a positive USD amount or "off"/);
+ expect(() => parseFlags([SKILL, '--max-usd', '--json'])).toThrow(/--max-usd needs/);
+ expect(() => parseFlags([SKILL, '--max-usd', 'lots'])).toThrow(/--max-usd must be a positive USD amount or "off" \(got "lots"\)/);
+ expect(() => parseFlags([SKILL, '--max-usd', '-2'])).toThrow(/must be a positive USD amount/);
+ });
+ test('disagreeing cap flags are refused; repeating the same cap is fine', () => {
+ expect(() => parseFlags([SKILL, '--max-usd', '3', '--no-max-cost'])).toThrow(/--max-usd 3 conflicts with --no-max-cost off; pass one cost cap/);
+ expect(() => parseFlags([SKILL, '--max-cost-usd', '2', '--max-usd', '3'])).toThrow(/conflicts/);
+ expect(parseFlags([SKILL, '--max-cost-usd', '3', '--max-usd', '3']).maxCostUsd).toBe(3);
+ });
+});