OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(cost): report context-aware estimate ranges (#926)
zcrab-oai7b77956c3067
diff --git a/plugins/codex-security/tests/test_workbench_scan_history.py b/plugins/codex-security/tests/test_workbench_scan_history.pyindex d69d57c3d..2ffcd7659 100644--- a/plugins/codex-security/tests/test_workbench_scan_history.py+++ b/plugins/codex-security/tests/test_workbench_scan_history.py@@ -11,6 +11,7 @@ import uuidfrom pathlib import Pathfrom typing import Any+import pytestfrom test_workbench_db import HEAD_CHANGED_WARNINGfrom test_workbench_deep_scan import begin_target_scanfrom test_workbench_prompt_only_scan import start_headless_standard_scan, start_prompt_only_scan@@ -442,7 +443,8 @@ def test_cli_scan_preserves_original_revision_when_head_moves(tmp_path: Path) ->assert history["scans"][0]["warnings"] == completed["scan"]["warnings"]-def test_cli_scan_history_persists_per_scan_cost(tmp_path: Path) -> None:[email protected]("context_reporting", ["bounded", "unknown_upper", "legacy"])+def test_cli_scan_history_persists_per_scan_cost(tmp_path: Path, context_reporting: str) -> None:state_dir = tmp_path / "state"repository = tmp_path / "repository"repository.mkdir()@@ -456,12 +458,25 @@ def test_cli_scan_history_persists_per_scan_cost(tmp_path: Path) -> None:"cacheWriteInputTokensReported": False,"pricing": {"source": "https://developers.openai.com/api/docs/pricing",- "asOf": "2026-09-09",+ "asOf": "2026-09-09" if context_reporting == "legacy" else "2026-09-14","serviceTier": "standard","context": "short","usdPerMillionTokens": {"input": 4, "cacheRead": 0.4, "cacheWrite": 5, "output": 20},},}+ if context_reporting != "legacy":+ cost["estimatedUsdRange"] = {+ "min": 0.00488,+ "max": 0.01156 if context_reporting == "bounded" else None,+ "context": "unknown",+ }+ if context_reporting == "bounded":+ cost["pricing"]["longContextUsdPerMillionTokens"] = {+ "input": 8,+ "cacheRead": 0.8,+ "cacheWrite": 10,+ "output": 30,+ }scan = create_cli_scan(state_dir, tmp_path / "results", repository, cost=cost)listed = run_workbench(state_dir, "list-scans", "--repository", str(repository))diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 4c2a32a76..af8b260ce 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -934,20 +934,32 @@ The final summary preserves missing-data information from a matching session logIf the Codex runtime converts an omitted count to zero before recording it, theCLI cannot distinguish that zero from reported usage.-JSON results, scan history, and bulk-scan receipts record the model, tokens,-estimated cost, and `cost.pricing`: the price source, verification date, processing-tier, context category, and rates in USD per million tokens. Estimates use-[standard, short-context API prices](https://developers.openai.com/api/docs/pricing),-including cache reads and writes. They exclude long-context and other processing-tier adjustments, fees, and surcharges. GPT-5.5 and GPT-6 Astra are supported;-models without known prices show an unavailable estimate.+Cost displays show a range using+[standard API prices](https://developers.openai.com/api/docs/pricing), because+runtime usage does not identify which requests received long-context pricing.+The minimum assumes short-context pricing; the maximum assumes long-context+pricing. These are token-cost estimates for the observed usage, excluding other+processing tiers, fees, surcharges, and account-specific pricing.++JSON results, scan history, and bulk-scan receipts preserve+`cost.estimatedUsdRange`: `min`, `max`, and `context: "unknown"`. A `null` maximum+means an upper estimate is unavailable, including models without verified+long-context rates. `cost.pricing` records the price source, verification date,+processing tier, short-context rates, and verified long-context rates when known.+Models without known short-context prices still have no cost estimate.For compatibility, `cacheWriteInputTokens` remains the reported token subtotal.`cacheWriteInputTokensReported: false` means at least one included usage recorddid not report cache writes. Raw usage uses `cache_write_input_tokens_reported`.-In that case, the estimate prices unclassified input at the ordinary input rate;-it may undercount cache-write charges. Older saved records lack this distinction-and the saved pricing basis.+In that case, the range minimum prices unclassified input as ordinary input,+and the maximum allows it to be cache writes. Token counts remain unchanged.+Older saved records remain readable and display a labeled legacy estimate;+they are not repriced using current rates.++For compatibility, `cost.estimatedUsd` retains the short-context baseline used+by existing spending limits. `cost.pricing.context: "short"` describes that+baseline, not observed request contexts. Use `estimatedUsdRange` for cost+reporting. This change does not change when spending limits stop scans.`--max-cost USD` stops the scan and its workers when estimated cost exceedsthe limit, though in-flight requests can finish above it. If deep-scandiff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 425e486c4..f9d7b4033 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -4132,14 +4132,32 @@ function addScanCosts(current: Readonly<ScanCost>,): ScanCost {if (previous === null) return { ...current };+ const { estimatedUsdRange: currentRange, ...currentCost } = current;+ const previousRange = previous.estimatedUsdRange;return {- model: current.model,+ ...currentCost,inputTokens: previous.inputTokens + current.inputTokens,cachedInputTokens: previous.cachedInputTokens + current.cachedInputTokens,cacheWriteInputTokens:previous.cacheWriteInputTokens + current.cacheWriteInputTokens,outputTokens: previous.outputTokens + current.outputTokens,estimatedUsd: previous.estimatedUsd + current.estimatedUsd,+ ...(previous.cacheWriteInputTokensReported === false ||+ current.cacheWriteInputTokensReported === false+ ? { cacheWriteInputTokensReported: false }+ : {}),+ ...(previousRange === undefined || currentRange === undefined+ ? {}+ : {+ estimatedUsdRange: {+ context: "unknown" as const,+ min: previousRange.min + currentRange.min,+ max:+ previousRange.max === null || currentRange.max === null+ ? null+ : previousRange.max + currentRange.max,+ },+ }),};}diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 81e90a503..e5bccc3bf 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -115,7 +115,11 @@ import {type JsonValue,} from "./config.js";import { formatUsd, type ScanCost } from "./cost.js";-import { formatScanCostTokens, formatTokenUsage } from "./cost-model.js";+import {+ formatScanCost,+ formatScanCostTokens,+ formatTokenUsage,+} from "./cost-model.js";import {isOutsidePath,readRegularInputFile,@@ -8112,8 +8116,7 @@ async function executeScan(}if (runningCost !== null) {details.push(`Tokens: ${formatScanCostTokens(runningCost)}`);- if (showCost)- details.push(`Cost: ${formatUsd(runningCost.estimatedUsd)}`);+ if (showCost) details.push(`Cost: ${formatScanCost(runningCost)}`);}return details.length === 0 ? stage : `${stage} | ${details.join(" | ")}`;};@@ -8159,6 +8162,7 @@ async function executeScan(diagnostic("cost.updated", {model: cost.model,estimated_usd: showCost ? cost.estimatedUsd : undefined,+ cost_estimate: showCost ? formatScanCost(cost) : undefined,input_tokens: cost.inputTokens,cached_input_tokens: cost.cachedInputTokens,cache_write_input_tokens: cost.cacheWriteInputTokens,@@ -8173,11 +8177,11 @@ async function executeScan(progress?.stopTimer();if (maxCostUsd === undefined) {progress?.stage(- `Tokens: ${formatScanCostTokens(cost)}.${showCost ? ` Estimated cost: ${formatUsd(cost.estimatedUsd)} USD.` : ""}`,+ `Tokens: ${formatScanCostTokens(cost)}.${showCost ? ` Estimated cost: ${formatScanCost(cost)}.` : ""}`,);} else {progress?.stage(- `Estimated cost: ${formatUsd(cost.estimatedUsd)} of ${formatUsd(maxCostUsd)} limit`,+ `Estimated cost: ${formatScanCost(cost)}; short-context budget baseline: ${formatUsd(cost.estimatedUsd)} of ${formatUsd(maxCostUsd)} limit`,);}if (maxCostUsd === undefined || cost.estimatedUsd <= maxCostUsd) {@@ -8441,6 +8445,10 @@ async function executeScan(partial_output: scanDir !== null,max_cost_usd: costLimitFailure?.maxCostUsd,estimated_usd: costLimitFailure?.cost.estimatedUsd,+ cost_estimate:+ costLimitFailure === undefined+ ? undefined+ : formatScanCost(costLimitFailure.cost),});errorOutput.write(`${message}\n`);if (failure instanceof ScanInterruptedError) {@@ -8538,6 +8546,10 @@ async function executeScan(findings: findings.length,scan_id: result.manifest.scan.id,estimated_usd: showCost ? result.cost?.estimatedUsd : undefined,+ cost_estimate:+ showCost && result.cost !== null+ ? formatScanCost(result.cost)+ : undefined,exit_code: exitCode,});progress?.stopTimer();@@ -8972,7 +8984,7 @@ function printScanSummary(const costSummary =result.cost === null? "unavailable (model pricing or usage missing)"- : `${formatUsd(result.cost.estimatedUsd)} (standard, short context)`;+ : formatScanCost(result.cost);errorOutput.write(` ${paint("COST", 1)} ${costSummary}\n`);}errorOutput.write(@@ -8994,7 +9006,7 @@ function componentScanEventLine(}if (event.type !== "cost") return null;const cost = event.value;- return `codex-security: ${componentName} | Tokens: ${formatScanCostTokens(cost)}${showCost ? ` | Cost: ${formatUsd(cost.estimatedUsd)}` : ""}\n`;+ return `codex-security: ${componentName} | Tokens: ${formatScanCostTokens(cost)}${showCost ? ` | Cost: ${formatScanCost(cost)}` : ""}\n`;}function protectedRootErrorMessage(diff --git a/sdk/typescript/src/cost-model.ts b/sdk/typescript/src/cost-model.tsindex f24dcd4a2..3d1f22eab 100644--- a/sdk/typescript/src/cost-model.ts+++ b/sdk/typescript/src/cost-model.ts@@ -5,21 +5,33 @@ export interface ScanCost {cacheWriteInputTokens: number;cacheWriteInputTokensReported?: boolean;outputTokens: number;+ /** Short-context baseline retained for compatibility and spending limits. */estimatedUsd: number;+ /** Standard token-cost bounds for the observed usage, not a billing total. */+ estimatedUsdRange?: {+ min: number;+ /** null when a verified upper estimate is unavailable. */+ max: number | null;+ context: "unknown";+ };pricing?: {source: string;asOf: string;serviceTier: "standard";context: "short";- usdPerMillionTokens: {- input: number;- cacheRead: number;- cacheWrite: number;- output: number;- };+ /** Short-context rates used by estimatedUsd and the range minimum. */+ usdPerMillionTokens: TokenPrices;+ longContextUsdPerMillionTokens?: TokenPrices;};}+interface TokenPrices {+ input: number;+ cacheRead: number;+ cacheWrite: number;+ output: number;+}+type ModelPricing = readonly [input: number,cachedInput: number,@@ -51,6 +63,33 @@ const MODEL_PRICING_NANODOLLARS: Readonly<Record<string, ModelPricing>> = {"gpt-daybreak-red-latest": [12_500, 1_250, 15_625, 75_000],};+// Verified Standard rates: https://developers.openai.com/api/docs/pricing+// GPT-5.5: https://developers.openai.com/api/docs/models/gpt-5.5+// Do not infer tiers from aggregate scan tokens: the runtime does not report+// which usage received long-context pricing. Cyber/Daybreak Red has no verified+// long-context rate in the pricing table, so its upper estimate stays unavailable.+const LONG_CONTEXT_PRICING_NANODOLLARS: Readonly<Record<string, ModelPricing>> =+ {+ "gpt-5.5": [10_000, 1_000, 10_000, 45_000],+ "gpt-5.5-2026-04-23": [10_000, 1_000, 10_000, 45_000],+ "gpt-6-astra": [20_000, 2_000, 25_000, 75_000],+ "gpt-5.6": [8_000, 800, 10_000, 30_000],+ "gpt-5.6-sol": [8_000, 800, 10_000, 30_000],+ "gpt-5.6-terra": [4_000, 400, 5_000, 18_000],+ "gpt-5.6-luna": [400, 40, 500, 1_800],+ "gpt-daybreak-blue-latest": [8_000, 800, 10_000, 30_000],+ };++function usdPerMillionTokens(pricing: ModelPricing): TokenPrices {+ const [input, cacheRead, cacheWrite, output] = pricing;+ return {+ input: input / 1_000,+ cacheRead: cacheRead / 1_000,+ cacheWrite: cacheWrite / 1_000,+ output: output / 1_000,+ };+}+export function tokenUsage(value: unknown): ScanTokenUsage | null {if (!isRecord(value)) return null;const input = value["input_tokens"];@@ -119,6 +158,24 @@ export function estimateScanCost(outputTokens * outputRate;if (!Number.isSafeInteger(nanodollars)) return null;+ const longPricing = LONG_CONTEXT_PRICING_NANODOLLARS[pricingModel];+ let maximumNanodollars: number | null = null;+ if (longPricing !== undefined) {+ const [longInput, longRead, longWrite, longOutput] = longPricing;+ // Unclassified input may include additional cache writes. Preserve the+ // reported subtotal, but include that uncertainty in the upper estimate.+ const uncachedRate =+ normalized.cache_write_input_tokens_reported === false+ ? Math.max(longInput, longWrite)+ : longInput;+ const maximum =+ (inputTokens - cachedInputTokens - cacheWriteInputTokens) * uncachedRate ++ cachedInputTokens * longRead ++ cacheWriteInputTokens * longWrite ++ outputTokens * longOutput;+ if (Number.isSafeInteger(maximum)) maximumNanodollars = maximum;+ }+return {model,inputTokens,@@ -129,19 +186,23 @@ export function estimateScanCost(: {}),outputTokens,estimatedUsd: nanodollars / 1_000_000_000,+ estimatedUsdRange: {+ min: nanodollars / 1_000_000_000,+ max:+ maximumNanodollars === null ? null : maximumNanodollars / 1_000_000_000,+ context: "unknown",+ },pricing: {source: pricingModel.startsWith("gpt-5.5")? "https://developers.openai.com/api/docs/models/gpt-5.5": "https://developers.openai.com/api/docs/pricing",- asOf: "2026-09-09",+ asOf: "2026-09-14",serviceTier: "standard",context: "short",- usdPerMillionTokens: {- input: inputRate / 1_000,- cacheRead: cachedInputRate / 1_000,- cacheWrite: cacheWriteInputRate / 1_000,- output: outputRate / 1_000,- },+ usdPerMillionTokens: usdPerMillionTokens(pricing),+ ...(longPricing === undefined+ ? {}+ : { longContextUsdPerMillionTokens: usdPerMillionTokens(longPricing) }),},};}@@ -183,6 +244,36 @@ export function formatScanCostTokens(cost: Readonly<ScanCost>): string {})!;}+export function formatScanCost(cost: Readonly<ScanCost>): string {+ return formatScanCosts([cost]);+}++export function formatScanCosts(costs: readonly Readonly<ScanCost>[]): string {+ if (costs.some((cost) => cost.estimatedUsdRange === undefined)) {+ return `${formatUsd(costs.reduce((sum, cost) => sum + cost.estimatedUsd, 0))} (legacy estimate, context unknown)`;+ }+ const minimum = costs.reduce(+ (sum, cost) => sum + cost.estimatedUsdRange!.min,+ 0,+ );+ const maximum = costs.some((cost) => cost.estimatedUsdRange!.max === null)+ ? null+ : costs.reduce((sum, cost) => sum + cost.estimatedUsdRange!.max!, 0);+ const cacheWrites = costs.some(+ (cost) => cost.cacheWriteInputTokensReported === false,+ )+ ? ", cache writes unknown"+ : "";+ if (maximum === null) {+ return `at least ${formatUsd(minimum)} (standard, upper estimate unavailable${cacheWrites})`;+ }+ const amount =+ minimum === maximum+ ? formatUsd(minimum)+ : `${formatUsd(minimum)}–${formatUsd(maximum)}`;+ return `${amount} (standard, context unknown${cacheWrites})`;+}+export function formatUsd(value: number): string {return new Intl.NumberFormat("en-US", {style: "currency",diff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.tsindex 6c5fd88ee..7125bed35 100644--- a/sdk/typescript/src/errors.ts+++ b/sdk/typescript/src/errors.ts@@ -1,4 +1,4 @@-import { formatUsd, type ScanCost } from "./cost-model.js";+import { formatScanCost, formatUsd, type ScanCost } from "./cost-model.js";/** Returns the original error message without altering its contents. */export function errorMessage(error: unknown): string {@@ -106,7 +106,7 @@ export class ScanCostLimitExceededError extends ScanInterruptedError {scanDir: string,) {super(- `Scan stopped: estimated cost ${formatUsd(cost.estimatedUsd)} exceeded the ${formatUsd(maxCostUsd)} limit; partial output remains at ${scanDir}.`,+ `Scan stopped: short-context budget baseline ${formatUsd(cost.estimatedUsd)} exceeded the ${formatUsd(maxCostUsd)} limit; estimated cost ${formatScanCost(cost)}; partial output remains at ${scanDir}.`,scanDir,);this.maxCostUsd = maxCostUsd;diff --git a/sdk/typescript/src/scan-dashboard.ts b/sdk/typescript/src/scan-dashboard.tsindex 2ae8679ac..0f2c8a344 100644--- a/sdk/typescript/src/scan-dashboard.ts+++ b/sdk/typescript/src/scan-dashboard.ts@@ -9,7 +9,12 @@ import type {ComponentScanResult,} from "./component-scan.js";import { formatUsd, type ScanCost, type ScanSessionEvent } from "./cost.js";-import { estimateScanCost, formatScanCostTokens } from "./cost-model.js";+import {+ estimateScanCost,+ formatScanCost,+ formatScanCosts,+ formatScanCostTokens,+} from "./cost-model.js";import type { ScanActivity } from "./scan-activity.js";import type { ScanMode } from "./targets.js";import { scanPhaseLabel, type ScanProgress } from "./worker-progress.js";@@ -564,18 +569,6 @@ export class ScanDashboard {this.#files === null? "waiting for inventory": `${formatCount(this.#files.filesCompleted)} / ${formatCount(this.#files.filesTotal)} reviewed`;- const cost =- this.#cost === null- ? this.#options.maxCostUsd === undefined- ? estimateScanCost(this.#options.model?.model, {- input_tokens: 0,- output_tokens: 0,- }) === null- ? "unavailable (model pricing missing)"- : "waiting for usage"- : `— / ${formatUsd(this.#options.maxCostUsd)}`- : `${formatUsd(this.#cost.estimatedUsd)}${this.#options.maxCostUsd === undefined ? "" : ` / ${formatUsd(this.#options.maxCostUsd)} · ${budgetBar(this.#cost.estimatedUsd, this.#options.maxCostUsd)}`}`;-const history = this.#activityLines(width);const maximumOffset = Math.max(0, history.length - activityRows);this.#scrollOffset = Math.min(this.#scrollOffset, maximumOffset);@@ -622,7 +615,7 @@ export class ScanDashboard {? []: [` STAGE ${this.#stage}`, ` FILES ${files}`]),...this.#tokenLines(),- ...(this.#showCost ? [` COST ${cost}`] : []),+ ...this.#costLines(),...(this.#budget === null? []: [@@ -719,7 +712,10 @@ export class ScanDashboard {}#componentRows(): number {- return Math.max(1, (this.#stream.rows ?? 24) - (this.#showCost ? 11 : 10));+ return Math.max(+ 1,+ (this.#stream.rows ?? 24) - 10 - this.#componentCostLines().length,+ );}#componentFrame(): string {@@ -732,7 +728,16 @@ export class ScanDashboard {this.#components.length - rows,),);- const nameWidth = Math.max(10, width - (this.#showCost ? 61 : 52));+ const costWidth = Math.max(+ 8,+ ...this.#components.map(({ dashboard }) =>+ dashboard.#cost === null ? 1 : formatScanCost(dashboard.#cost).length,+ ),+ );+ const nameWidth = Math.max(+ 10,+ width - 52 - (this.#showCost ? costWidth + 1 : 0),+ );const row = (marker: string,name: string,@@ -758,9 +763,7 @@ export class ScanDashboard {receipt.findingCount === undefined? "—": formatCount(receipt.findingCount),- dashboard.#cost === null- ? "—"- : formatUsd(dashboard.#cost.estimatedUsd),+ dashboard.#cost === null ? "—" : formatScanCost(dashboard.#cost),);});if (table.length === 0) table.push(` ${this.#stage}…`);@@ -769,9 +772,6 @@ export class ScanDashboard {this.#components.filter(({ receipt }) => receipt.status === status).length;const selected = this.#components[this.#selectedComponent]?.receipt;- const costs = this.#components.flatMap(({ dashboard }) =>- dashboard.#cost === null ? [] : [dashboard.#cost.estimatedUsd],- );const rawFindings = this.#components.reduce((sum, { receipt }) => sum + (receipt.findingCount ?? 0),0,@@ -791,11 +791,7 @@ export class ScanDashboard {divider,` SCOPE ${selected?.paths.join(", ") ?? "waiting for component plan"}`,` STATUS ${selected?.error ?? findings}`,- ...(this.#showCost- ? [- ` COST ${costs.length === 0 ? "waiting for usage" : formatUsd(costs.reduce((sum, value) => sum + value, 0))} · component scans only`,- ]- : []),+ ...this.#componentCostLines(),` STAGE ${this.#stage}`,` TIME ${formatElapsed(Math.max(0, Math.floor((this.#options.clock.now() - this.#startedAt) / 1_000)))} · ↑↓ select · Enter activity · Ctrl+C cancel`,]);@@ -807,6 +803,18 @@ export class ScanDashboard {);}+ #componentCostLines(): string[] {+ if (!this.#showCost) return [];+ const costs = this.#components.flatMap(({ dashboard }) =>+ dashboard.#cost === null ? [] : [dashboard.#cost],+ );+ return wrapActivity(+ " COST ",+ `${costs.length === 0 ? "waiting for usage" : formatScanCosts(costs)} · component scans only`,+ this.#width(),+ );+ }+#width(): number {return Math.max(1, Math.min(this.#stream.columns ?? 88, 160));}@@ -820,7 +828,7 @@ export class ScanDashboard {(this.#options.presentation === "publication" ||this.#options.presentation === "verification"? 0- : this.#tokenLines().length - 1 - (this.#showCost ? 0 : 1)) ++ : this.#tokenLines().length - 1 + this.#costLines().length - 1) +(this.#options.presentation === "publication"? 2: this.#options.mode === "deep"@@ -837,6 +845,22 @@ export class ScanDashboard {return wrapActivity(" TOKENS ", tokens, this.#width());}+ #costLines(): string[] {+ if (!this.#showCost) return [];+ const cost =+ this.#cost === null+ ? this.#options.maxCostUsd === undefined+ ? estimateScanCost(this.#options.model?.model, {+ input_tokens: 0,+ output_tokens: 0,+ }) === null+ ? "unavailable (model pricing missing)"+ : "waiting for usage"+ : `— / ${formatUsd(this.#options.maxCostUsd)}`+ : `${formatScanCost(this.#cost)}${this.#options.maxCostUsd === undefined ? "" : `; short-context budget baseline: ${formatUsd(this.#cost.estimatedUsd)} / ${formatUsd(this.#options.maxCostUsd)} · ${budgetBar(this.#cost.estimatedUsd, this.#options.maxCostUsd)}`}`;+ return wrapActivity(" COST ", cost, this.#width());+ }+#activityLines(width: number): DashboardActivityLine[] {if (this.#view === "details") {let cache = this.#detailsCache;diff --git a/sdk/typescript/src/security-policy-cli.ts b/sdk/typescript/src/security-policy-cli.tsindex b60f40f6a..19a740267 100644--- a/sdk/typescript/src/security-policy-cli.ts+++ b/sdk/typescript/src/security-policy-cli.ts@@ -1,7 +1,7 @@import type { CodexSecurity, ScanAuthMode } from "./api.js";import type { BulkScanPrompt } from "./bulk-scan-discovery.js";import type { CodexSecurityConfig } from "./config.js";-import { formatUsd } from "./cost.js";+import { formatScanCost } from "./cost-model.js";import { safeErrorMessage } from "./errors.js";import {formatSecurityPolicyText as display,@@ -199,7 +199,7 @@ export async function runPolicyCommand(}const seconds = Math.max(0, (dependencies.now() - started) / 1000);write(- `Policy generation finished in ${seconds.toFixed(1)}s${cost === null ? "" : ` (${formatUsd(cost.estimatedUsd)} estimated)`}.`,+ `Policy generation finished in ${seconds.toFixed(1)}s${cost === null ? "" : ` (estimated cost: ${formatScanCost(cost)})`}.`,);return {exitCode: 0,diff --git a/sdk/typescript/tests-ts/api-policy.test.ts b/sdk/typescript/tests-ts/api-policy.test.tsindex 08d057f01..f69bc8fdf 100644--- a/sdk/typescript/tests-ts/api-policy.test.ts+++ b/sdk/typescript/tests-ts/api-policy.test.ts@@ -1245,6 +1245,12 @@ describe("CodexSecurity policy API", () => {expect(f.configuration()?.env?.["CODEX_SECURITY_SCAN_ID"]).toBeUndefined();expect(result.cost?.inputTokens).toBe(300);expect(result.cost?.outputTokens).toBe(30);+ expect(result.cost?.estimatedUsdRange).toEqual({+ min: 0.0018,+ max: 0.0033,+ context: "unknown",+ });+ expect(result.cost?.pricing?.longContextUsdPerMillionTokens?.input).toBe(8);expect(costs).toHaveLength(3);expect(costs.at(-1)).toBe(result.cost?.estimatedUsd);expect(await readFile(result.draftPath, "utf8")).toBe(POLICY);diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 29c995175..f69ba7977 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -4892,7 +4892,7 @@ describe("CodexSecurity orchestration", () => {"--scan-id","scan_example_001","--message",- `Scan stopped: estimated cost $0.00488 exceeded the $0.004 limit; partial output remains at ${scanDir}.`,+ `Scan stopped: short-context budget baseline $0.00488 exceeded the $0.004 limit; estimated cost $0.00488–$0.01156 (standard, context unknown, cache writes unknown); partial output remains at ${scanDir}.`,"--cost-json",JSON.stringify(cost),]);@@ -5025,7 +5025,7 @@ describe("CodexSecurity orchestration", () => {expect(recovered.threadId).toBe("scan-thread");expect(recovered.cost?.estimatedUsd).toBe(0.00488);expect(warnings).toEqual([- `Scan stopped: estimated cost $0.00488 exceeded the $0.004 limit; partial output remains at ${scanDir}.`,+ `Scan stopped: short-context budget baseline $0.00488 exceeded the $0.004 limit; estimated cost $0.00488–$0.01156 (standard, context unknown, cache writes unknown); partial output remains at ${scanDir}.`,]);expect(commands.some((args) => args[0] === "fail-scan")).toBe(false);}diff --git a/sdk/typescript/tests-ts/cli-policy.test.ts b/sdk/typescript/tests-ts/cli-policy.test.tsindex 67e5c1894..9a87f8551 100644--- a/sdk/typescript/tests-ts/cli-policy.test.ts+++ b/sdk/typescript/tests-ts/cli-policy.test.ts@@ -143,6 +143,16 @@ describe("policy CLI", () => {test("generates a headless draft with machine-readable paths and no source edits", async () => {const f = await fixture();+ const draft = await f.generate();+ draft.cost = {+ model: "synthetic-model",+ inputTokens: 1,+ cachedInputTokens: 0,+ cacheWriteInputTokens: 0,+ outputTokens: 1,+ estimatedUsd: 1,+ estimatedUsdRange: { min: 1, max: 2, context: "unknown" },+ };const stdout = capture();const stderr = capture();let closed = false;@@ -162,6 +172,7 @@ describe("policy CLI", () => {stdout.stream,stderr.stream,policyDependencies(f, {+ draft,onClose: () => {closed = true;},@@ -175,6 +186,8 @@ describe("policy CLI", () => {expect(result.status).toBe("draft");expect(result.targetPath).toBe(join(f.repository, "SECURITY.md"));expect(result.threatModelPath).toBe(join(f.outputDir, "THREAT_MODEL.md"));+ expect(result.cost).toEqual(draft.cost);+ expect(stderr.text()).toContain("$1.00–$2.00 (standard, context unknown)");expect(stderr.text()).toContain("[1/3]");expect(stderr.text()).not.toContain("+Requests must be authorized");expect(config).toMatchObject({diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex 178d92ce4..d853d1a94 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -4727,12 +4727,12 @@ describe("CLI", () => {).toBe(0);expect(JSON.parse(stdout.text())).toEqual(result.toJSON());expect(stderr.text()).toContain(- "Tokens: unavailable uncached input, 200 cache reads, unavailable cache writes, 30 output, 1,280 total. Estimated cost: $0.00488 USD.",+ "Tokens: unavailable uncached input, 200 cache reads, unavailable cache writes, 30 output, 1,280 total. Estimated cost: $0.00488–$0.01156 (standard, context unknown, cache writes unknown).",);expect(stderr.text()).toContain("Scan phase: reviewing files (0/8 files).");expect(stderr.text()).toContain("Scan phase: reviewing files (3/8 files).");expect(stderr.text()).toContain(- "Running scan: reviewing files | Workers: 4/6 | Files: 3/8 | Tokens: unavailable uncached input, 200 cache reads, unavailable cache writes, 30 output, 1,280 total | Cost: $0.00488",+ "Running scan: reviewing files | Workers: 4/6 | Files: 3/8 | Tokens: unavailable uncached input, 200 cache reads, unavailable cache writes, 30 output, 1,280 total | Cost: $0.00488–$0.01156",);});@@ -4805,7 +4805,9 @@ describe("CLI", () => {expect(stderr.text()).toContain("TOKENS unavailable uncached input, 200 cache reads, unavailable cache writes, 30 output, 1,280 total",);- expect(stderr.text()).toContain("COST $0.00488");+ expect(stderr.text()).toContain(+ "COST $0.00488–$0.01156 (standard, context unknown, cache writes unknown)",+ );expect(stderr.text()).toContain(`REPORT ${result.reportPath}`);expect(stderr.text()).toContain("RESULTS /tmp/scan");expect(stderr.text()).not.toContain("Next:");@@ -4848,7 +4850,7 @@ describe("CLI", () => {},);- test("reports the running cost against the scan budget", async () => {+ test("reports a cost range while preserving the short-context scan budget", async () => {const stdout = capture();const stderr = capture();const result = fakeResult([], "complete", {@@ -4859,14 +4861,20 @@ describe("CLI", () => {expect(await main(- ["scan", ".", "--json", "--max-cost", "0.01"],+ ["scan", ".", "--verbose", "--json", "--max-cost", "0.01"],stdout.stream,stderr.stream,dependencies({ result, costUpdates: [result.cost!] }),),).toBe(0);expect(JSON.parse(stdout.text())).toEqual(result.toJSON());- expect(stderr.text()).toContain("Estimated cost: $0.00488 of $0.01 limit");+ expect(stderr.text()).toContain("Estimated cost: $0.00488–$0.01156");+ expect(stderr.text()).toContain(+ "short-context budget baseline: $0.00488 of $0.01 limit",+ );+ expect(stderr.text()).toContain(+ 'estimated_usd=0.00488 cost_estimate="$0.00488–$0.01156 (standard, context unknown, cache writes unknown)"',+ );});test("includes cache-write tokens in verbose cost diagnostics", async () => {@@ -4892,6 +4900,7 @@ describe("CLI", () => {expect(stderr.text()).toContain("codex-security: debug: cost.updated");expect(stderr.text()).toContain("cache_write_input_tokens=200");expect(stderr.text()).not.toContain("estimated_usd=");+ expect(stderr.text()).not.toContain("cost_estimate=");});test("reports and classifies a scan stopped when its live cost exceeds the limit", async () => {@@ -4918,7 +4927,7 @@ describe("CLI", () => {).toBe(2);expect(stdout.text()).toBe("");expect(stderr.text()).toContain(- "Scan stopped: estimated cost $0.00488 exceeded the $0.004 limit; partial output remains at /tmp/scan.",+ "Scan stopped: short-context budget baseline $0.00488 exceeded the $0.004 limit; estimated cost $0.00488–$0.01156 (standard, context unknown, cache writes unknown); partial output remains at /tmp/scan.",);expect(stderr.text()).toMatch(/scan\.configuration[^\n]*max_cost_usd=0\.004/u,diff --git a/sdk/typescript/tests-ts/cost-context.test.ts b/sdk/typescript/tests-ts/cost-context.test.tsnew file mode 100644index 000000000..dfdd69277--- /dev/null+++ b/sdk/typescript/tests-ts/cost-context.test.ts@@ -0,0 +1,131 @@+import { expect, test } from "bun:test";+import {+ estimateScanCost,+ formatScanCost,+ formatScanCosts,+} from "../src/cost-model.js";++// Standard prices per million: input, cache reads, cache writes, output.+test.each([+ ["gpt-5.5", [5, 0.5, 5, 30], [10, 1, 10, 45]],+ ["gpt-5.5-2026-04-23", [5, 0.5, 5, 30], [10, 1, 10, 45]],+ ["gpt-6-astra", [10, 1, 12.5, 50], [20, 2, 25, 75]],+ ["gpt-5.6", [4, 0.4, 5, 20], [8, 0.8, 10, 30]],+ ["gpt-5.6-sol", [4, 0.4, 5, 20], [8, 0.8, 10, 30]],+ ["gpt-5.6-terra", [2, 0.2, 2.5, 12], [4, 0.4, 5, 18]],+ ["gpt-5.6-luna", [0.2, 0.02, 0.25, 1.2], [0.4, 0.04, 0.5, 1.8]],+ ["gpt-daybreak-blue-latest", [4, 0.4, 5, 20], [8, 0.8, 10, 30]],+] as const)(+ "%s bounds each token category with verified rates",+ (model, short, long) => {+ for (const category of [0, 1, 2, 3] as const) {+ for (const selected of [model, `openai.${model}`]) {+ const cost = estimateScanCost(selected, {+ input_tokens: category === 3 ? 0 : 1_000_000,+ cached_input_tokens: category === 1 ? 1_000_000 : 0,+ cache_write_input_tokens: category === 2 ? 1_000_000 : 0,+ output_tokens: category === 3 ? 1_000_000 : 0,+ })!;+ expect(cost.estimatedUsd).toBe(short[category]);+ expect(cost.estimatedUsdRange).toEqual({+ min: short[category],+ max: long[category],+ context: "unknown",+ });+ }+ }+ },+);++test("reports a range for cache-heavy scans without changing the budget baseline", () => {+ const cost = estimateScanCost("gpt-5.6-sol", {+ input_tokens: 150_000_000,+ cached_input_tokens: 138_000_000,+ cache_write_input_tokens: 11_700_000,+ output_tokens: 900_000,+ })!;+ expect(cost.estimatedUsd).toBe(132.9);+ expect(cost.estimatedUsdRange).toEqual({+ min: 132.9,+ max: 256.8,+ context: "unknown",+ });+ expect(formatScanCost(cost)).toBe(+ "$132.90–$256.80 (standard, context unknown)",+ );+});++test("widens the maximum for unreported cache writes without changing token counts", () => {+ const usage = {+ input_tokens: 1_000_000,+ cached_input_tokens: 200_000,+ output_tokens: 0,+ };+ const missing = estimateScanCost("gpt-5.6-sol", usage)!;+ const zero = estimateScanCost("gpt-5.6-sol", {+ ...usage,+ cache_write_input_tokens: 0,+ })!;+ const partial = estimateScanCost("gpt-5.6-sol", {+ ...usage,+ cache_write_input_tokens: 300_000,+ cache_write_input_tokens_reported: false,+ })!;+ expect(missing.cacheWriteInputTokens).toBe(0);+ expect(missing.estimatedUsdRange).toMatchObject({ min: 3.28, max: 8.16 });+ expect(zero.estimatedUsdRange).toMatchObject({ min: 3.28, max: 6.56 });+ expect(partial.cacheWriteInputTokens).toBe(300_000);+ expect(partial.estimatedUsdRange).toMatchObject({ min: 3.58, max: 8.16 });+ expect(formatScanCost(missing)).toContain("cache writes unknown");+});++test("keeps unverified long-context prices unavailable", () => {+ const cost = estimateScanCost("gpt-daybreak-red-latest", {+ input_tokens: 1_000_000,+ cache_write_input_tokens: 0,+ output_tokens: 0,+ })!;+ expect(cost.estimatedUsdRange).toEqual({+ min: 12.5,+ max: null,+ context: "unknown",+ });+ expect(formatScanCost(cost)).toBe(+ "at least $12.50 (standard, upper estimate unavailable)",+ );+});++test("unavailable upper arithmetic does not disable an existing budget estimate", () => {+ const cost = estimateScanCost("gpt-6-astra", {+ input_tokens: 600_000_000_000,+ cache_write_input_tokens: 0,+ output_tokens: 0,+ })!;+ expect(cost.estimatedUsd).toBe(6_000_000);+ expect(cost.estimatedUsdRange?.max).toBeNull();+});++test("component totals preserve uncertainty and label legacy records without repricing", () => {+ const cost = estimateScanCost("gpt-5.6-sol", {+ input_tokens: 1_000_000,+ cache_write_input_tokens: 0,+ output_tokens: 0,+ })!;+ expect(formatScanCosts([cost, cost])).toBe(+ "$8.00–$16.00 (standard, context unknown)",+ );+ const { estimatedUsdRange: _range, pricing: _pricing, ...legacy } = cost;+ legacy.estimatedUsd = 3;+ expect(formatScanCost(legacy)).toBe(+ "$3.00 (legacy estimate, context unknown)",+ );+ expect(formatScanCosts([legacy, cost])).toBe(+ "$7.00 (legacy estimate, context unknown)",+ );+ expect(+ formatScanCosts([+ cost,+ { ...cost, estimatedUsdRange: { min: 4, max: null, context: "unknown" } },+ ]),+ ).toContain("at least $8.00");+});diff --git a/sdk/typescript/tests-ts/cost.test.ts b/sdk/typescript/tests-ts/cost.test.tsindex 077eb4983..aaa2f09e2 100644--- a/sdk/typescript/tests-ts/cost.test.ts+++ b/sdk/typescript/tests-ts/cost.test.ts@@ -228,9 +228,10 @@ describe("scan cost", () => {cacheWriteInputTokens: 300_000,outputTokens: 100_000,estimatedUsd: 13.95,+ estimatedUsdRange: { min: 13.95, max: 25.4, context: "unknown" },pricing: {source: "https://developers.openai.com/api/docs/pricing",- asOf: "2026-09-09",+ asOf: "2026-09-14",serviceTier: "standard",context: "short",usdPerMillionTokens: {@@ -239,6 +240,12 @@ describe("scan cost", () => {cacheWrite: 12.5,output: 50,},+ longContextUsdPerMillionTokens: {+ input: 20,+ cacheRead: 2,+ cacheWrite: 25,+ output: 75,+ },},});});diff --git a/sdk/typescript/tests-ts/errors.test.ts b/sdk/typescript/tests-ts/errors.test.tsindex c710d5223..23db1958c 100644--- a/sdk/typescript/tests-ts/errors.test.ts+++ b/sdk/typescript/tests-ts/errors.test.ts@@ -55,6 +55,8 @@ describe("error messages", () => {});expect(limit.message).toContain("$2.00");expect(limit.message).toContain("$1.00");+ expect(limit.message).toContain("short-context budget baseline $2.00");+ expect(limit.message).toContain("legacy estimate, context unknown");expect(limit.message).toContain("/scan");});diff --git a/sdk/typescript/tests-ts/result.test.ts b/sdk/typescript/tests-ts/result.test.tsindex 9c9e7622f..9b0bdf990 100644--- a/sdk/typescript/tests-ts/result.test.ts+++ b/sdk/typescript/tests-ts/result.test.ts@@ -128,7 +128,19 @@ describe("ScanResult", () => {});expect(result.cost?.estimatedUsd).toBe(0.00488);- expect(result.toJSON()["cost"]).toEqual(result.cost);+ const serialized = JSON.parse(JSON.stringify(result));+ expect(serialized.cost).toEqual(result.cost);+ expect(serialized.cost).toMatchObject({+ estimatedUsdRange: { min: 0.00488, max: 0.01156, context: "unknown" },+ pricing: {+ longContextUsdPerMillionTokens: {+ input: 8,+ cacheRead: 0.8,+ cacheWrite: 10,+ output: 30,+ },+ },+ });});test("discovers SARIF at its canonical scan path", async () => {diff --git a/sdk/typescript/tests-ts/scan-dashboard.test.ts b/sdk/typescript/tests-ts/scan-dashboard.test.tsindex 531cefc64..a5c093983 100644--- a/sdk/typescript/tests-ts/scan-dashboard.test.ts+++ b/sdk/typescript/tests-ts/scan-dashboard.test.ts@@ -41,6 +41,38 @@ class DashboardTestInput extends EventEmitter {}describe("live scan dashboard", () => {+ test("keeps cost bounds and assumptions readable on a narrow terminal", () => {+ const stderr = capture(true);+ const dashboard = new ScanDashboard(+ { ...stderr.stream, columns: 60, rows: 24 },+ {+ repository: "/synthetic/repository",+ showCost: true,+ clock: fakeClock(),+ },+ );+ dashboard.start();+ dashboard.setCost({+ model: "synthetic-model",+ inputTokens: 1,+ cachedInputTokens: 0,+ cacheWriteInputTokens: 0,+ cacheWriteInputTokensReported: false,+ outputTokens: 1,+ estimatedUsd: 1,+ estimatedUsdRange: { min: 1, max: 2, context: "unknown" },+ });+ const frame = stripVTControlCharacters(+ stderr.text().split("\u001B[H").at(-1)!,+ );+ expect(frame.replace(/\s+/gu, " ")).toContain(+ "$1.00–$2.00 (standard, context unknown, cache writes unknown)",+ );+ expect(frame.split("\n")).toHaveLength(24);+ expect(frame.split("\n").every((line) => line.length <= 60)).toBe(true);+ dashboard.stop();+ });+test("edits a higher total budget while continuing to show live cost", async () => {const stderr = capture(true);const input = new DashboardTestInput();@@ -55,6 +87,7 @@ describe("live scan dashboard", () => {...fakeResult([], "complete", { input_tokens: 100, output_tokens: 1 }).cost!,estimatedUsd: 16,+ estimatedUsdRange: { min: 16, max: 32, context: "unknown" as const },};dashboard.start();dashboard.setCost(cost);@@ -68,14 +101,24 @@ describe("live scan dashboard", () => {input.emit("data", "\u00150\r");input.emit("data", "\u0015Infinity\r");input.emit("data", "\u001520\r");- dashboard.setCost({ ...cost, estimatedUsd: 21 });+ const updatedCost = {+ ...cost,+ estimatedUsd: 21,+ estimatedUsdRange: { min: 21, max: 42, context: "unknown" as const },+ };+ dashboard.setCost(updatedCost);input.emit("data", "\u001520.5\r");expect(stderr.text()).toContain("above $21.00");- expect(stderr.text()).toContain("$21.00 / $20.00");+ expect(+ stripVTControlCharacters(stderr.text()).replace(/\s+/gu, " "),+ ).toContain("short-context budget baseline: $21.00 / $20.00");+ expect(stderr.text()).toContain("$21.00–$42.00");input.emit("data", "\u0015300\u007F\r");await expect(answer).resolves.toBe(30);- dashboard.setCost({ ...cost, estimatedUsd: 21 }, 30);- expect(stderr.text()).toContain("$21.00 / $30.00");+ dashboard.setCost(updatedCost, 30);+ expect(+ stripVTControlCharacters(stderr.text()).replace(/\s+/gu, " "),+ ).toContain("short-context budget baseline: $21.00 / $30.00");dashboard.stop();expect(input.isRaw).toBe(false);expect(input.listenerCount("data")).toBe(0);@@ -180,7 +223,15 @@ describe("live scan dashboard", () => {dashboard.recordComponentEvent({componentId: receipt.id,type: "cost",- value: { ...cost, estimatedUsd: index + 1 },+ value: {+ ...cost,+ estimatedUsd: index + 1,+ estimatedUsdRange: {+ min: index + 1,+ max: (index + 1) * 2,+ context: "unknown",+ },+ },});dashboard.recordComponentEvent({componentId: receipt.id,@@ -213,7 +264,8 @@ describe("live scan dashboard", () => {expect(frame()).toContain("validating findings");expect(frame()).toContain("1/10");expect(frame()).toContain("2/10");- expect(frame()).toContain("$3.00 · component scans only");+ expect(frame()).toContain("$3.00–$6.00 (standard, context unknown");+ expect(frame()).toContain("component scans only");expect(frame()).toContain("before deduplication");expect(frame().split("\n")).toHaveLength(20);input.emit("data", "\r");