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
chore(codex-security): sync public projection
ianw-oai808e9bb58c6c
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 7ab146af1..13e6d2167 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -104,6 +104,7 @@ npx codex-security scan /path/to/repository --output-dir /path/outside/repositornpx codex-security scan /path/to/repository --output-dir /path/outside/repository/results --archive-existingnpx codex-security scan /path/to/repository --dry-runnpx codex-security scan /path/to/repository --fail-on-severity high+npx codex-security scan /path/to/repository --max-cost 5npx codex-security bulk-scannpx codex-security bulk-scan repositories.csv --output-dir /path/outside/repositories/security-scans --workers 4npx codex-security scans list /path/to/repository@@ -159,9 +160,19 @@ options for other Codex settings, such asScan progress identifies the requested paths and reports actual ranking,file-review, validation, and attack-path phases as they become available.Completion summarizes findings, severity, coverage, elapsed time, available-token and worker counts, the results directory, and the next useful command.+token and worker counts, estimated cost, the results directory, and the next+useful command.Progress and summaries use stderr; structured scan results remain on stdout.+Each scan records its model, tokens, and estimated cost in its JSON result,+scan history, and bulk-scan receipt. Estimates use+[standard API token prices](https://developers.openai.com/api/docs/models/compare),+including cached input and cache writes; fees and surcharges are not included.++Use `--max-cost USD` to stop a scan, including its delegated workers, when its+running cost exceeds the limit. Partial results are preserved. Requests+already in progress can finish above the limit.+Run `npx codex-security scan --help` or `npx codex-security bulk-scan --help`for the complete CLI references.diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.pyindex 23e07aff0..c117c0ad6 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py@@ -208,6 +208,7 @@ def parse_args(description: str) -> argparse.Namespace:complete_scan = subparsers.add_parser("complete-scan")complete_scan.add_argument("--scan-id", required=True)complete_scan.add_argument("--claim-token")+ complete_scan.add_argument("--cost-json")cancel_scan = subparsers.add_parser("cancel-scan")cancel_scan.add_argument("--scan-id", required=True)@@ -217,6 +218,7 @@ def parse_args(description: str) -> argparse.Namespace:fail_scan.add_argument("--scan-id", required=True)fail_scan.add_argument("--message", required=True)fail_scan.add_argument("--claim-token")+ fail_scan.add_argument("--cost-json")mark_handoff_delivered = subparsers.add_parser("mark-handoff-delivered")mark_handoff_delivered.add_argument("--scan-id", required=True)diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.pyindex d66cb81a5..a44eed527 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py@@ -106,6 +106,7 @@ from workbench_validation import (capability_preflight_input,capability_preflight_json,optional_text,+ parse_scan_cost,require_occurrence,require_uuid,)@@ -1453,12 +1454,16 @@ def pin_legacy_manifest_digest(def complete_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:scan_id = require_uuid(args.scan_id, "scan-id")+ cost_json = parse_scan_cost(args.cost_json)with scan_completion_lock(scan_id):- return complete_scan_locked(connection, scan_id, args.claim_token)+ return complete_scan_locked(connection, scan_id, args.claim_token, cost_json)def complete_scan_locked(- connection: sqlite3.Connection, scan_id: str, claim_token: str | None+ connection: sqlite3.Connection,+ scan_id: str,+ claim_token: str | None,+ cost_json: str | None,) -> dict[str, Any]:scan = require_scan(connection, scan_id)if scan["status"] == "complete":@@ -1551,10 +1556,10 @@ def complete_scan_locked("""UPDATE scansSET status = 'complete', phase = 'reporting', completed_at = ?, updated_at = ?,- seal_manifest_digest = ?+ seal_manifest_digest = ?, cost_json = ?WHERE id = ? AND status = 'running'""",- (timestamp, timestamp, manifest_digest, scan["id"]),+ (timestamp, timestamp, manifest_digest, cost_json, scan["id"]),)if updated.rowcount != 1:raise SystemExit("Only a running scan can be completed.")@@ -1750,6 +1755,7 @@ def coverage_for_comparison(scan: sqlite3.Row) -> dict[str, Any]:def fail_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:scan_id = require_uuid(args.scan_id, "scan-id")+ cost_json = parse_scan_cost(args.cost_json)connection.execute("BEGIN IMMEDIATE")try:timestamp = now()@@ -1767,10 +1773,17 @@ def fail_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[updated = connection.execute("""UPDATE scans- SET status = 'failed', failure_message = ?, completed_at = ?, updated_at = ?+ SET status = 'failed', failure_message = ?, completed_at = ?, updated_at = ?,+ cost_json = ?WHERE id = ? AND status = 'running'""",- (optional_text(args.message, maximum=2400), timestamp, timestamp, scan["id"]),+ (+ optional_text(args.message, maximum=2400),+ timestamp,+ timestamp,+ cost_json,+ scan["id"],+ ),)if updated.rowcount != 1:raise SystemExit("Only a running scan can be marked failed.")@@ -3025,6 +3038,11 @@ def scan_result(return {"artifacts": artifacts,"canceledAt": scan["canceled_at"],+ **(+ {"cost": json.loads(scan["cost_json"], parse_constant=reject_non_finite_json)}+ if scan["cost_json"] is not None+ else {}+ ),"contract": scan_contract(scan),"continuationThreadId": scan["continuation_thread_id"],"failureMessage": scan["failure_message"],diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.pyindex e73d5ee41..835dc56dc 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py@@ -216,6 +216,7 @@ def list_scans({"completedAt": row["completed_at"],"continuationThreadId": row["continuation_thread_id"],+ **({"cost": json.loads(row["cost_json"])} if row["cost_json"] else {}),"findingCount": row["finding_count"],"handoffStatus": row["handoff_status"],"mode": row["mode"],diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py b/sdk/typescript/_bundled_plugin/scripts/workbench_schema.pyindex 01d928769..0b7244eae 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_schema.py@@ -595,6 +595,13 @@ MIGRATIONS = (ON scan_comparison_matches(after_occurrence_id);""",),+ (+ 24,+ "persist scan cost estimates",+ """+ ALTER TABLE scans ADD COLUMN cost_json TEXT;+ """,+ ),)diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_validation.py b/sdk/typescript/_bundled_plugin/scripts/workbench_validation.pyindex 47432cfc0..9d5e2bbf8 100644--- a/sdk/typescript/_bundled_plugin/scripts/workbench_validation.py+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_validation.py@@ -36,6 +36,32 @@ def reject_nonstandard_json_number(value: str) -> None:raise ValueError(f"invalid JSON number {value}")+def parse_scan_cost(value: str | None) -> str | None:+ if value is None:+ return None+ if len(value.encode("utf-8")) > 8192:+ raise SystemExit("Scan cost must be no larger than 8 KiB.")+ try:+ cost = json.loads(value, parse_constant=reject_nonstandard_json_number)+ except (TypeError, UnicodeError, ValueError) as exc:+ raise SystemExit("Scan cost must be a valid JSON object.") from exc+ token_keys = ("inputTokens", "cachedInputTokens", "cacheWriteInputTokens", "outputTokens")+ if (+ not isinstance(cost, dict)+ or not isinstance(cost.get("model"), str)+ or not cost["model"]+ or any(type(cost.get(key)) is not int or cost[key] < 0 for key in token_keys)+ or cost["cachedInputTokens"] + cost["cacheWriteInputTokens"] > cost["inputTokens"]+ or type(cost.get("estimatedUsd")) not in (int, float)+ or not math.isfinite(cost["estimatedUsd"])+ or cost["estimatedUsd"] < 0+ ):+ raise SystemExit(+ "Scan cost must include a model, nonnegative token counts, and an estimated USD amount."+ )+ return json.dumps(cost, separators=(",", ":"), allow_nan=False)++def capability_preflight_json(value: str | None,*,diff --git a/sdk/typescript/package.json b/sdk/typescript/package.jsonindex 4cfacc883..d54a90caf 100644--- a/sdk/typescript/package.json+++ b/sdk/typescript/package.json@@ -46,7 +46,7 @@"generate:models": "node scripts/generate-models.cjs","generate:models:check": "node scripts/generate-models.cjs --check","lint": "tsc --noEmit",- "test": "bun test --timeout 30000 tests-ts/api.test.ts tests-ts/auth.test.ts tests-ts/bulk-scan-discovery.test.ts tests-ts/cli-export.test.ts tests-ts/cli.test.ts tests-ts/config.test.ts tests-ts/contract.test.ts tests-ts/knowledge-base.test.ts tests-ts/multiscan.test.ts tests-ts/result.test.ts tests-ts/runtime.test.ts tests-ts/scan-comparison.test.ts tests-ts/scan-history-renderer.test.ts tests-ts/skeleton.test.ts tests-ts/targets.test.ts tests-ts/trusted-executable.test.ts tests-ts/worker-progress.test.ts",+ "test": "bun test --timeout 30000 tests-ts/api.test.ts tests-ts/auth.test.ts tests-ts/bulk-scan-discovery.test.ts tests-ts/cli-export.test.ts tests-ts/cli.test.ts tests-ts/config.test.ts tests-ts/contract.test.ts tests-ts/cost.test.ts tests-ts/knowledge-base.test.ts tests-ts/multiscan.test.ts tests-ts/result.test.ts tests-ts/runtime.test.ts tests-ts/scan-comparison.test.ts tests-ts/scan-history-renderer.test.ts tests-ts/skeleton.test.ts tests-ts/targets.test.ts tests-ts/trusted-executable.test.ts tests-ts/worker-progress.test.ts","types": "pnpm run generate:models:check && tsc --noEmit"},"dependencies": {diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjsindex e731c0143..f6fec8a21 100644--- a/sdk/typescript/scripts/check-package.mjs+++ b/sdk/typescript/scripts/check-package.mjs@@ -140,6 +140,7 @@ const distFiles = new Set("cli","config","contract",+ "cost","errors","index","knowledge-base",diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex 79135fed3..a4029ab65 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -19,6 +19,7 @@ import {type JsonObject,writeCodexConfig,} from "./config.js";+import { estimateScanCost, ScanCostTracker, type ScanCost } from "./cost.js";import {loadContract,requireScanFile,@@ -31,6 +32,7 @@ import {OutputDirectoryError,OutputInsideProtectedRootError,type ProtectedScanPathKind,+ ScanCostLimitExceededError,ScanInterruptedError,} from "./errors.js";import {@@ -118,6 +120,8 @@ export interface ScanOptions {parentScanId?: string;expectedPluginVersion?: string;failureSeverity?: SeverityLevel;+ maxCostUsd?: number;+ onCost?: (cost: Readonly<ScanCost>) => void;onOutputArchived?: (archiveDir: string) => void;onOutputDirReady?: (scanDir: string) => void;onAuthentication?: (authentication: ScanAuthentication) => void;@@ -150,6 +154,7 @@ export interface ScanReconnectDetails {type ScanObserverName =| "onAuthentication"+ | "onCost"| "onOutputArchived"| "onOutputDirReady"| "onScanStarted"@@ -166,6 +171,7 @@ export interface ScanPreflight {authentication: ScanAuthentication;model: string;reasoningEffort: string;+ maxCostUsd?: number;}interface LocalScanInputs@@ -251,6 +257,8 @@ export class CodexSecurity {"temporary",);const configuration = await mergedCodexConfig(this.config);+ const model = scanModelConfiguration(configuration);+ validateScanCostLimit(options.maxCostUsd, model.model);const archiveDir =options.archiveExisting === true? await planOutputArchive(inputs.outputDir)@@ -266,19 +274,25 @@ export class CodexSecurity {outputDir: inputs.outputDir,...(archiveDir === null ? {} : { archiveDir }),authentication: scanAuthentication(this.#dependencies.environment),- ...scanModelConfiguration(configuration),+ ...model,+ ...(options.maxCostUsd === undefined+ ? {}+ : { maxCostUsd: options.maxCostUsd }),};}async #run(repository: string, options: ScanOptions): Promise<ScanResult> {this.#requireOpen();- const signal =- options.signal === undefined- ? this.#abortController.signal- : AbortSignal.any([this.#abortController.signal, options.signal]);+ const costAbortController = new AbortController();+ const signal = AbortSignal.any([+ this.#abortController.signal,+ costAbortController.signal,+ ...(options.signal === undefined ? [] : [options.signal]),+ ]);let scanDir = "";let targetPathsFile: string | null = null;let knowledgeBase: PreparedKnowledgeBase | null = null;+ let costTracker: ScanCostTracker | null = null;let activeScan: {id: string;options: WorkbenchCommandOptions;@@ -446,6 +460,31 @@ export class CodexSecurity {};const effectiveConfig =runtime.effectiveConfig ?? (await mergedCodexConfig(this.config));+ const { model } = scanModelConfiguration(effectiveConfig);+ validateScanCostLimit(options.maxCostUsd, model);+ const tracker = new ScanCostTracker({+ codexHome: runtime.codexHome,+ model,+ maxCostUsd: options.maxCostUsd,+ onCost: (cost) => {+ notifyObserver(+ "onCost",+ options.onCost,+ options.onObserverError,+ cost,+ );+ if (+ options.maxCostUsd !== undefined &&+ cost.estimatedUsd > options.maxCostUsd+ ) {+ costAbortController.abort(+ new ScanCostLimitExceededError(options.maxCostUsd, cost, scanDir),+ );+ }+ },+ onError: (error) => costAbortController.abort(error),+ });+ costTracker = tracker;const recipe = scanRecipe(repo,normalized,@@ -455,6 +494,7 @@ export class CodexSecurity {effectiveConfig,options.failureSeverity,knowledgeBase?.sources,+ options.maxCostUsd,);const workbenchOptions: WorkbenchCommandOptions = {python,@@ -567,13 +607,25 @@ export class CodexSecurity {scanDir,pluginRoot: runtime.plugin.installedRoot,expectation,- onFinalize: async () => {+ model,+ onThreadStarted: (threadId) => tracker.start(threadId),+ onFinalize: async (usage) => {+ const snapshot = await tracker.stop(usage);+ throwIfAborted(signal, scanDir);+ if (options.maxCostUsd !== undefined && snapshot.cost === null) {+ throw new CodexSecurityError(+ "Cannot evaluate the cost limit: model pricing or token usage is unavailable.",+ );+ }+ const cost = snapshot.cost;await workbench(workbenchOptions, ["complete-scan","--scan-id",scanId,+ ...(cost === null ? [] : ["--cost-json", JSON.stringify(cost)]),]);activeScan = null;+ return snapshot.usage;},onScanStarted: options.onScanStarted,onReconnect: options.onReconnect,@@ -583,6 +635,11 @@ export class CodexSecurity {checkOpen();return result;} catch (error) {+ const snapshot = await costTracker?.stop().catch(() => null);+ const failure =+ signal.reason instanceof ScanCostLimitExceededError+ ? signal.reason+ : error;if (activeScan !== null) {try {await workbench({ ...activeScan.options, signal: undefined }, [@@ -590,18 +647,21 @@ export class CodexSecurity {"--scan-id",activeScan.id,"--message",- (error instanceof Error ? error.message : String(error)).slice(- 0,- 2400,- ),+ (failure instanceof Error+ ? failure.message+ : String(failure)+ ).slice(0, 2400),+ ...(snapshot?.cost+ ? ["--cost-json", JSON.stringify(snapshot.cost)]+ : []),]);} catch {}}if (this.#closed) this.#requireOpen();- if (signal.aborted && !(error instanceof ScanInterruptedError)) {+ if (signal.aborted && !(failure instanceof ScanInterruptedError)) {throwIfAborted(signal, scanDir);}- throw error;+ throw failure;} finally {await Promise.all([knowledgeBase?.cleanup(),@@ -815,6 +875,14 @@ export class CodexSecurity {options: ScanOptions,signal?: AbortSignal,): Promise<LocalScanInputs> {+ if (+ options.maxCostUsd !== undefined &&+ (!Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0)+ ) {+ throw new CodexSecurityError(+ "The scan cost limit must be a positive USD amount.",+ );+ }const repositoryPath = resolveRepositoryPath(repository);const repo = await normalizeRepository(repositoryPath, signal);throwIfAborted(signal);@@ -955,7 +1023,9 @@ interface ScanEventRunOptions {scanDir: string;pluginRoot: string;expectation: ScanExpectation;- onFinalize?: () => Promise<void>;+ model?: string;+ onFinalize?: (usage: unknown) => Promise<unknown>;+ onThreadStarted?: (threadId: string) => void;onScanStarted?: () => void;onReconnect?: (attempt: number,@@ -988,7 +1058,10 @@ export async function runScanEvents(}if (event.type === "thread.started") {const startedThreadId = event["thread_id"];- if (typeof startedThreadId === "string") threadId = startedThreadId;+ if (typeof startedThreadId === "string") {+ threadId = startedThreadId;+ options.onThreadStarted?.(startedThreadId);+ }if (!scanStarted) {scanStarted = true;notifyObserver(@@ -1047,9 +1120,16 @@ export async function runScanEvents("Codex Security did not report a thread ID.",);}- await options.onFinalize?.();+ if (options.onFinalize !== undefined) {+ usage = (await options.onFinalize(usage)) ?? usage;+ }const result = await collectResult(- { status, finalResponse, usage },+ {+ status,+ finalResponse,+ usage,+ ...(options.model === undefined ? {} : { model: options.model }),+ },threadId,options.scanDir,options.pluginRoot,@@ -1064,6 +1144,9 @@ export async function runScanEvents(}return result;} catch (error) {+ if (options.signal.reason instanceof ScanCostLimitExceededError) {+ throw options.signal.reason;+ }if (options.signal.aborted && !(error instanceof ScanInterruptedError)) {throw new ScanInterruptedError(`Codex Security scan was interrupted; partial output remains at ${options.scanDir}.`,@@ -1154,6 +1237,7 @@ function scanRecipe(effectiveConfig: JsonObject,failOnSeverity?: SeverityLevel,knowledgeBasePaths?: string[],+ maxCostUsd?: number,): JsonObject {return {repository,@@ -1171,9 +1255,22 @@ function scanRecipe(config: scanPreflightCodexConfig(effectiveConfig),...(failOnSeverity === undefined ? {} : { failOnSeverity }),...(knowledgeBasePaths === undefined ? {} : { knowledgeBasePaths }),+ ...(maxCostUsd === undefined ? {} : { maxCostUsd }),};}+function validateScanCostLimit(+ maxCostUsd: number | undefined,+ model: string,+): void {+ if (maxCostUsd === undefined) return;+ if (estimateScanCost(model, { input_tokens: 0, output_tokens: 0 }) === null) {+ throw new CodexSecurityError(+ `A scan cost limit is not available for the configured model: ${model}.`,+ );+ }+}+async function collectResult(turnResult: TurnResultMetadata,threadId: string,@@ -1507,6 +1604,7 @@ function requireOutputOutsideRepository(function throwIfAborted(signal?: AbortSignal, scanDir = ""): void {if (!signal?.aborted) return;+ if (signal.reason instanceof ScanCostLimitExceededError) throw signal.reason;const message = scanDir? `Codex Security scan was interrupted; partial output remains at ${scanDir}.`: "Codex Security scan was interrupted during preparation.";diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex dc9bd9405..cbc11fa84 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -47,6 +47,7 @@ import {type JsonObject,type JsonValue,} from "./config.js";+import { formatUsd } from "./cost.js";import {CodexSecurityError,OutputInsideProtectedRootError,@@ -131,6 +132,7 @@ const VALUE_OPTIONS = new Set(["--python","--codex","--fail-on-severity",+ "--max-cost","--workers","--max-attempts","--export-format",@@ -164,6 +166,7 @@ interface ScanArguments {codex: string[];codexOverrides?: JsonObject;failOnSeverity?: FailureSeverity;+ maxCostUsd?: number;dryRun: boolean;parentScanId?: string;expectedPluginVersion?: string;@@ -824,6 +827,11 @@ export async function main(.enum(REPORTABLE_SEVERITIES).optional().describe("Exit 1 for findings at or above LEVEL."),+ maxCost: z+ .number()+ .positive()+ .optional()+ .describe("Stop the scan if estimated USD cost exceeds AMOUNT."),dryRun: z.boolean().default(false)@@ -887,6 +895,7 @@ export async function main(pythonPath: options.python,codex: options.codex,failOnSeverity: options.failOnSeverity,+ maxCostUsd: options.maxCost,dryRun: options.dryRun,},errorOutput,@@ -1387,6 +1396,17 @@ function scanArgumentsFromRecipe("The saved scan recipe contains an invalid severity policy.",);}+ const maxCostUsd = recipe["maxCostUsd"];+ if (+ maxCostUsd !== undefined &&+ (typeof maxCostUsd !== "number" ||+ !Number.isFinite(maxCostUsd) ||+ maxCostUsd <= 0)+ ) {+ throw new CodexSecurityError(+ "The saved scan recipe contains an invalid cost limit.",+ );+ }return {repository,paths,@@ -1400,6 +1420,7 @@ function scanArgumentsFromRecipe(codex: [],codexOverrides: config,failOnSeverity: threshold as FailureSeverity | undefined,+ maxCostUsd,dryRun: false,parentScanId,expectedPluginVersion:@@ -2062,6 +2083,17 @@ async function runScan(parentScanId: arguments_.parentScanId,expectedPluginVersion: arguments_.expectedPluginVersion,failureSeverity: arguments_.failOnSeverity,+ maxCostUsd: arguments_.maxCostUsd,+ onCost: (cost) => {+ if (arguments_.maxCostUsd === undefined) return;+ progress?.stopTimer();+ progress?.stage(+ `Estimated cost: ${formatUsd(cost.estimatedUsd)} of ${formatUsd(arguments_.maxCostUsd)} limit`,+ );+ if (cost.estimatedUsd <= arguments_.maxCostUsd) {+ progress?.startTimer(runningMessage());+ }+ },onOutputArchived: (archiveDir) => {progress?.stopTimer();errorOutput.write(@@ -2304,6 +2336,11 @@ function printScanSummary(if (tokenSummary !== null) {errorOutput.write(`codex-security: Tokens: ${tokenSummary}.\n`);}+ if (result.cost !== null) {+ errorOutput.write(+ `codex-security: Estimated cost: ${formatUsd(result.cost.estimatedUsd)} USD.\n`,+ );+ }const scanDir = cliErrorMessage(result.scanDir);errorOutput.write(`codex-security: Results: ${scanDir}\n`);errorOutput.write(diff --git a/sdk/typescript/src/cost.ts b/sdk/typescript/src/cost.tsnew file mode 100644index 000000000..912ccd275--- /dev/null+++ b/sdk/typescript/src/cost.ts@@ -0,0 +1,362 @@+import { open, readdir } from "node:fs/promises";+import { join } from "node:path";++export interface ScanCost {+ model: string;+ inputTokens: number;+ cachedInputTokens: number;+ cacheWriteInputTokens: number;+ outputTokens: number;+ estimatedUsd: number;+}++type ModelPricing = readonly [+ input: number,+ cachedInput: number,+ cacheWriteInput: number,+ output: number,+];++interface ScanTokenUsage {+ input_tokens: number;+ cached_input_tokens: number;+ cache_write_input_tokens: number;+ output_tokens: number;+ reasoning_output_tokens: number;+ total_tokens: number;+}++interface SessionUsage {+ offset: number;+ remainder: Buffer;+ threadId: string | null;+ parentThreadId: string | null;+ usage: ScanTokenUsage | null;+}++interface ScanCostTrackerOptions {+ codexHome: string;+ model: string;+ maxCostUsd?: number;+ onCost?: (cost: Readonly<ScanCost>) => void;+ onError?: (error: unknown) => void;+}++interface ScanCostSnapshot {+ usage: unknown;+ cost: ScanCost | null;+}++const MODEL_PRICING_NANODOLLARS: Readonly<Record<string, ModelPricing>> = {+ "gpt-5.6": [5_000, 500, 6_250, 30_000],+ "gpt-5.6-sol": [5_000, 500, 6_250, 30_000],+ "gpt-5.6-terra": [2_500, 250, 3_125, 15_000],+ "gpt-5.6-luna": [1_000, 100, 1_250, 6_000],+};++const COST_POLL_INTERVAL_MS = 100;+const SESSION_READ_SIZE = 64 * 1_024;++export class ScanCostTracker {+ readonly #options: ScanCostTrackerOptions;+ readonly #sessions = new Map<string, SessionUsage>();+ #threadId: string | null = null;+ #timer: NodeJS.Timeout | null = null;+ #pending: Promise<void> = Promise.resolve();+ #snapshot: ScanCostSnapshot = { usage: null, cost: null };+ #lastCost: number | null = null;++ public constructor(options: ScanCostTrackerOptions) {+ this.#options = options;+ }++ public start(threadId: string): void {+ if (this.#threadId !== null) return;+ this.#threadId = threadId;+ if (this.#options.maxCostUsd === undefined) return;+ const poll = () => {+ void this.refresh().catch((error: unknown) => {+ this.#options.onError?.(error);+ });+ };+ this.#timer = setInterval(poll, COST_POLL_INTERVAL_MS);+ this.#timer.unref();+ poll();+ }++ public async refresh(): Promise<ScanCostSnapshot> {+ const update = this.#pending.then(async () => {+ await this.#readSessions();+ });+ this.#pending = update.catch(() => {});+ await update;+ return this.#snapshot;+ }++ public async stop(fallbackUsage?: unknown): Promise<ScanCostSnapshot> {+ if (this.#timer !== null) {+ clearInterval(this.#timer);+ this.#timer = null;+ }+ await this.refresh();+ if (this.#snapshot.usage !== null) return this.#snapshot;+ const cost = estimateScanCost(this.#options.model, fallbackUsage);+ this.#snapshot = { usage: fallbackUsage ?? null, cost };+ this.#reportCost(cost);+ return this.#snapshot;+ }++ async #readSessions(): Promise<void> {+ if (this.#threadId === null) return;+ for await (const path of sessionFiles(+ join(this.#options.codexHome, "sessions"),+ )) {+ let session = this.#sessions.get(path);+ if (session === undefined) {+ session = {+ offset: 0,+ remainder: Buffer.alloc(0),+ threadId: null,+ parentThreadId: null,+ usage: null,+ };+ this.#sessions.set(path, session);+ }+ await readSessionUsage(path, session);+ }++ const included = new Set([this.#threadId]);+ let changed = true;+ while (changed) {+ changed = false;+ for (const session of this.#sessions.values()) {+ if (+ session.threadId !== null &&+ session.parentThreadId !== null &&+ included.has(session.parentThreadId) &&+ !included.has(session.threadId)+ ) {+ included.add(session.threadId);+ changed = true;+ }+ }+ }++ let usage: ScanTokenUsage | null = null;+ for (const session of this.#sessions.values()) {+ if (+ session.threadId !== null &&+ included.has(session.threadId) &&+ session.usage !== null+ ) {+ usage = addTokenUsage(usage, session.usage);+ }+ }+ if (usage === null) return;+ const cost = estimateScanCost(this.#options.model, usage);+ this.#snapshot = { usage, cost };+ this.#reportCost(cost);+ }++ #reportCost(cost: ScanCost | null): void {+ if (cost === null || cost.estimatedUsd === this.#lastCost) return;+ this.#lastCost = cost.estimatedUsd;+ this.#options.onCost?.(cost);+ }+}++async function* sessionFiles(directory: string): AsyncGenerator<string> {+ let entries;+ try {+ entries = await readdir(directory, { withFileTypes: true });+ } catch (error) {+ if (isMissingFile(error)) return;+ throw error;+ }+ for (const entry of entries) {+ const path = join(directory, entry.name);+ if (entry.isDirectory()) {+ yield* sessionFiles(path);+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {+ yield path;+ }+ }+}++async function readSessionUsage(+ path: string,+ session: SessionUsage,+): Promise<void> {+ let file;+ try {+ file = await open(path, "r");+ } catch (error) {+ if (isMissingFile(error)) return;+ throw error;+ }+ try {+ const buffer = Buffer.alloc(SESSION_READ_SIZE);+ while (true) {+ const { bytesRead } = await file.read(+ buffer,+ 0,+ buffer.length,+ session.offset,+ );+ if (bytesRead === 0) return;+ session.offset += bytesRead;+ const contents = Buffer.concat([+ session.remainder,+ buffer.subarray(0, bytesRead),+ ]);+ let lineStart = 0;+ while (true) {+ const lineEnd = contents.indexOf(0x0a, lineStart);+ if (lineEnd === -1) break;+ readSessionEvent(+ contents.subarray(lineStart, lineEnd).toString("utf8"),+ session,+ );+ lineStart = lineEnd + 1;+ }+ session.remainder = Buffer.from(contents.subarray(lineStart));+ }+ } finally {+ await file.close();+ }+}++function readSessionEvent(line: string, session: SessionUsage): void {+ if (line.length === 0) return;+ let event: unknown;+ try {+ event = JSON.parse(line) as unknown;+ } catch {+ return;+ }+ if (!isRecord(event) || !isRecord(event["payload"])) return;+ const payload = event["payload"];+ if (event["type"] === "session_meta") {+ if (typeof payload["id"] === "string") {+ session.threadId = payload["id"];+ }+ const source = payload["source"];+ const subagent = isRecord(source) ? source["subagent"] : undefined;+ const spawn = isRecord(subagent) ? subagent["thread_spawn"] : undefined;+ const parent =+ payload["parent_thread_id"] ??+ (isRecord(spawn) ? spawn["parent_thread_id"] : undefined);+ if (typeof parent === "string") session.parentThreadId = parent;+ return;+ }+ if (+ event["type"] !== "event_msg" ||+ payload["type"] !== "token_count" ||+ !isRecord(payload["info"])+ ) {+ return;+ }+ const usage = tokenUsage(payload["info"]["total_token_usage"]);+ if (usage !== null) session.usage = usage;+}++function tokenUsage(value: unknown): ScanTokenUsage | null {+ if (!isRecord(value)) return null;+ const input = value["input_tokens"];+ const cached = value["cached_input_tokens"] ?? 0;+ const cacheWrite =+ value["cache_write_input_tokens"] ?? value["cache_write_tokens"] ?? 0;+ const output = value["output_tokens"];+ const reasoning = value["reasoning_output_tokens"] ?? 0;+ if (+ !isTokenCount(input) ||+ !isTokenCount(cached) ||+ !isTokenCount(cacheWrite) ||+ !isTokenCount(output) ||+ !isTokenCount(reasoning) ||+ cached + cacheWrite > input ||+ reasoning > output+ ) {+ return null;+ }+ return {+ input_tokens: input,+ cached_input_tokens: cached,+ cache_write_input_tokens: cacheWrite,+ output_tokens: output,+ reasoning_output_tokens: reasoning,+ total_tokens: input + output,+ };+}++function addTokenUsage(+ previous: ScanTokenUsage | null,+ next: ScanTokenUsage,+): ScanTokenUsage {+ if (previous === null) return next;+ return {+ input_tokens: previous.input_tokens + next.input_tokens,+ cached_input_tokens:+ previous.cached_input_tokens + next.cached_input_tokens,+ cache_write_input_tokens:+ previous.cache_write_input_tokens + next.cache_write_input_tokens,+ output_tokens: previous.output_tokens + next.output_tokens,+ reasoning_output_tokens:+ previous.reasoning_output_tokens + next.reasoning_output_tokens,+ total_tokens: previous.total_tokens + next.total_tokens,+ };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function isMissingFile(error: unknown): boolean {+ return isRecord(error) && error["code"] === "ENOENT";+}++export function estimateScanCost(+ model: string | undefined,+ usage: unknown,+): ScanCost | null {+ if (model === undefined) return null;+ const pricing = MODEL_PRICING_NANODOLLARS[model];+ const normalized = tokenUsage(usage);+ if (pricing === undefined || normalized === null) return null;+ const [inputRate, cachedInputRate, cacheWriteInputRate, outputRate] = pricing;+ const {+ input_tokens: inputTokens,+ cached_input_tokens: cachedInputTokens,+ cache_write_input_tokens: cacheWriteInputTokens,+ output_tokens: outputTokens,+ } = normalized;++ const nanodollars =+ (inputTokens - cachedInputTokens - cacheWriteInputTokens) * inputRate ++ cachedInputTokens * cachedInputRate ++ cacheWriteInputTokens * cacheWriteInputRate ++ outputTokens * outputRate;+ if (!Number.isSafeInteger(nanodollars)) return null;++ return {+ model,+ inputTokens,+ cachedInputTokens,+ cacheWriteInputTokens,+ outputTokens,+ estimatedUsd: nanodollars / 1_000_000_000,+ };+}++export function formatUsd(value: number): string {+ return new Intl.NumberFormat("en-US", {+ style: "currency",+ currency: "USD",+ minimumFractionDigits: 2,+ maximumFractionDigits: 9,+ }).format(value);+}++function isTokenCount(value: unknown): value is number {+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;+}diff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.tsindex 02c138d16..10be04ca8 100644--- a/sdk/typescript/src/errors.ts+++ b/sdk/typescript/src/errors.ts@@ -1,3 +1,5 @@+import { formatUsd, type ScanCost } from "./cost.js";+/** Base error for Codex Security SDK failures. */export class CodexSecurityError extends Error {public constructor(message: string, options?: ErrorOptions) {@@ -35,3 +37,21 @@ export class ScanInterruptedError extends CodexSecurityError {this.scanDir = scanDir;}}++export class ScanCostLimitExceededError extends ScanInterruptedError {+ public readonly maxCostUsd: number;+ public readonly cost: Readonly<ScanCost>;++ public constructor(+ maxCostUsd: number,+ cost: Readonly<ScanCost>,+ scanDir: string,+ ) {+ super(+ `Scan stopped: estimated cost ${formatUsd(cost.estimatedUsd)} exceeded the ${formatUsd(maxCostUsd)} limit; partial output remains at ${scanDir}.`,+ scanDir,+ );+ this.maxCostUsd = maxCostUsd;+ this.cost = cost;+ }+}diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex e0c5af00b..00fb3bb3a 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -1,4 +1,6 @@export { CodexSecurity } from "./api.js";+export { estimateScanCost } from "./cost.js";+export type { ScanCost } from "./cost.js";export type {CodexSecurityMetadata,ScanAuthentication,@@ -21,6 +23,7 @@ export {OutputInsideProtectedRootError,PluginBootstrapError,PluginPythonUnavailableError,+ ScanCostLimitExceededError,ScanInterruptedError,} from "./errors.js";export type { ProtectedScanPathKind } from "./errors.js";diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.tsindex 05c19a776..8f68095e0 100644--- a/sdk/typescript/src/multiscan.ts+++ b/sdk/typescript/src/multiscan.ts@@ -16,6 +16,7 @@ import { promisify } from "node:util";import Papa from "papaparse";import type { CodexSecurity } from "./api.js";import type { CodexSecurityConfig } from "./config.js";+import type { ScanCost } from "./cost.js";import type { ScanMode } from "./targets.js";import { resolveTrustedExecutable } from "./trusted-executable.js";@@ -39,6 +40,7 @@ interface MultiscanReceipt extends MultiscanTask {status: "completed" | "failed";attempt: number;outputDir: string;+ cost?: ScanCost;error?: string;}@@ -154,6 +156,7 @@ async function runCampaign(const progress = { repository: task.id, attempt };options.onProgress?.({ ...progress, status: "started" });let failure: string | undefined;+ let cost: Readonly<ScanCost> | null = null;try {await mkdir(dirname(scanDir), { recursive: true, mode: 0o700 });await rm(checkout, { recursive: true, force: true });@@ -181,6 +184,7 @@ async function runCampaign(outputDir: scanDir,...(options.signal === undefined ? {} : { signal: options.signal }),});+ cost = result.cost;if (result.coverage.completeness !== "complete") {throw new Error("Multiscan repository coverage is incomplete.");}@@ -198,6 +202,7 @@ async function runCampaign(status,attempt,outputDir: scanDir,+ ...(cost === null ? {} : { cost }),...(failure === undefined ? {} : { error: failure }),})}\n`,);diff --git a/sdk/typescript/src/result.ts b/sdk/typescript/src/result.tsindex 635088fac..467c520d1 100644--- a/sdk/typescript/src/result.ts+++ b/sdk/typescript/src/result.ts@@ -5,10 +5,12 @@ import type {FindingsDocument,ScanManifest,} from "./models.js";+import { estimateScanCost, type ScanCost } from "./cost.js";export interface TurnResultMetadata {id?: string;status?: string;+ model?: string;durationMs?: number;finalResponse?: string;usage?: unknown;@@ -32,6 +34,7 @@ export class ScanResult {public readonly scanDir: string;public readonly threadId: string;public readonly turnResult: Readonly<TurnResultMetadata>;+ public readonly cost: Readonly<ScanCost> | null;public readonly sarifPath: string | null;public constructor(options: ScanResultOptions) {@@ -41,6 +44,10 @@ export class ScanResult {this.scanDir = options.scanDir;this.threadId = options.threadId;this.turnResult = options.turnResult;+ this.cost = estimateScanCost(+ options.turnResult.model,+ options.turnResult.usage,+ );if (options.sarifPath !== undefined) {this.sarifPath = options.sarifPath;} else {@@ -95,6 +102,7 @@ export class ScanResult {reportPath: this.reportPath,artifactsDir: this.artifactsDir,sarifPath: this.sarifPath,+ cost: this.cost,turn: this.turnResult,};}diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex fdab47adc..3bafc14d6 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -29,6 +29,7 @@ import {OutputDirectoryError,OutputInsideProtectedRootError,type ScanAuthentication,+ ScanCostLimitExceededError,type ScanOptions,ScanInterruptedError,type ScanReconnectDetails,@@ -100,6 +101,38 @@ async function copyCompletedScan(root: string): Promise<string> {return scanDir;}+async function writeUsageSession(+ codexHome: string,+ threadId: string,+ usage: Record<string, number>,+ parentThreadId?: string,+): Promise<void> {+ const directory = join(codexHome, "sessions", "2026", "07", "26");+ await mkdir(directory, { recursive: true });+ await writeFile(+ join(directory, `rollout-${threadId}.jsonl`),+ [+ JSON.stringify({+ type: "session_meta",+ payload: {+ id: threadId,+ ...(parentThreadId === undefined+ ? {}+ : { parent_thread_id: parentThreadId }),+ },+ }),+ JSON.stringify({+ type: "event_msg",+ payload: {+ type: "token_count",+ info: { total_token_usage: usage },+ },+ }),+ "",+ ].join("\n"),+ );+}+async function* completedEvents(): AsyncGenerator<ThreadEvent> {yield { type: "thread.started", thread_id: "thread-1" };yield { type: "turn.started" };@@ -142,6 +175,7 @@ function runEvents(signal: abortController.signal,scanDir,pluginRoot: PLUGIN_ROOT,+ model: "gpt-5.6-sol",onScanStarted,onReconnect,onWorkerStatus,@@ -180,8 +214,17 @@ describe("one-shot scan events", () => {expect(result.threadId).toBe("thread-1");expect(result.turnResult).toMatchObject({status: "completed",+ model: "gpt-5.6-sol",finalResponse: "scan complete",});+ expect(result.cost).toEqual({+ model: "gpt-5.6-sol",+ inputTokens: 10,+ cachedInputTokens: 2,+ cacheWriteInputTokens: 0,+ outputTokens: 3,+ estimatedUsd: 0.000131,+ });});test("lets the workbench seal artifacts before validating completed scans", async () => {@@ -208,7 +251,12 @@ describe("one-shot scan events", () => {mode: "standard",pluginVersion: "0.1.0",},- onFinalize: async () => {+ onFinalize: async (usage) => {+ expect(usage).toMatchObject({+ input_tokens: 10,+ cached_input_tokens: 2,+ output_tokens: 3,+ });expect(existsSync(join(scanDir, "scan-manifest.json"))).toBe(false);await copyCompletedScan(root);finalized = true;@@ -1022,6 +1070,43 @@ describe("CodexSecurity orchestration", () => {await client.close();});+ test("validates cost limits and pricing before starting a scan", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ await mkdir(repository);+ let runtimeStarted = false;+ const client = new TestClient(+ {},+ {+ environment: {},+ prepareRuntime: async () => {+ runtimeStarted = true;+ throw new Error("runtime should not initialize");+ },+ },+ );++ await expect(+ client.preflight(repository, { maxCostUsd: 5 }),+ ).resolves.toMatchObject({ model: "gpt-5.6-sol", maxCostUsd: 5 });+ for (const maxCostUsd of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {+ await expect(+ client.preflight(repository, { maxCostUsd }),+ ).rejects.toThrow("cost limit must be a positive USD amount");+ }++ const unpriced = new TestClient(+ { codexOverrides: { model: "unknown-model" } },+ { environment: {} },+ );+ await expect(+ unpriced.preflight(repository, { maxCostUsd: 5 }),+ ).rejects.toThrow("cost limit is not available for the configured model");+ expect(runtimeStarted).toBe(false);+ await unpriced.close();+ await client.close();+ });+test("validates knowledge-base documents before initializing the runtime", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");@@ -1673,6 +1758,150 @@ describe("CodexSecurity orchestration", () => {await client.close();});+ test("stops and records a scan as soon as its live cost exceeds the limit", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "codex-home");+ const scanDir = join(root, "scan");+ await mkdir(repository);+ await mkdir(codexHome);+ await mkdir(scanDir, { mode: 0o700 });+ const commands: Array<readonly string[]> = [];+ const costs: number[] = [];+ const cost = {+ model: "gpt-5.6-sol",+ inputTokens: 1_250,+ cachedInputTokens: 200,+ cacheWriteInputTokens: 0,+ outputTokens: 30,+ estimatedUsd: 0.00625,+ };+ const client = new TestClient(+ {},+ {+ environment: {},+ prepareRuntime: async () => preparedRuntime(codexHome),+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ runWorkbench: async (_options: unknown, args: readonly string[]) => {+ commands.push(args);+ return args[0] === "register-cli-scan"+ ? {+ scanId: "scan_example_001",+ targetId: "target_sha256_example",+ scanDir,+ }+ : {};+ },+ createCodex: () => ({+ startThread: () => ({+ id: null,+ async runStreamed(+ _input: string,+ options: { signal: AbortSignal },+ ) {+ async function* events(): AsyncGenerator<ThreadEvent> {+ yield { type: "thread.started", thread_id: "scan-thread" };+ await Promise.all([+ writeUsageSession(codexHome, "scan-thread", {+ input_tokens: 500,+ cached_input_tokens: 100,+ output_tokens: 10,+ }),+ writeUsageSession(+ codexHome,+ "worker-thread",+ {+ input_tokens: 750,+ cached_input_tokens: 100,+ output_tokens: 20,+ },+ "scan-thread",+ ),+ ]);+ await new Promise<void>((resolve) => {+ if (options.signal.aborted) {+ resolve();+ } else {+ options.signal.addEventListener("abort", () => resolve(), {+ once: true,+ });+ }+ });+ throw new DOMException("aborted", "AbortError");+ }+ return { events: events() };+ },+ }),+ }),+ },+ );++ await expect(+ client.run(repository, {+ maxCostUsd: 0.005,+ onCost: (cost) => costs.push(cost.estimatedUsd),+ signal: AbortSignal.timeout(5_000),+ }),+ ).rejects.toMatchObject({+ name: ScanCostLimitExceededError.name,+ maxCostUsd: 0.005,+ scanDir,+ cost,+ });+ expect(costs.at(-1)).toBe(0.00625);+ expect(commands[1]).toEqual([+ "fail-scan",+ "--scan-id",+ "scan_example_001",+ "--message",+ `Scan stopped: estimated cost $0.00625 exceeded the $0.005 limit; partial output remains at ${scanDir}.`,+ "--cost-json",+ JSON.stringify(cost),+ ]);+ expect(commands.some((args) => args[0] === "complete-scan")).toBe(false);+ await expect(stat(scanDir)).resolves.toBeDefined();+ await client.close();+ });++ test("fails a budgeted scan when token usage is unavailable", async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "codex-home");+ const scanDir = join(root, "scan");+ await mkdir(repository);+ await mkdir(codexHome);+ await mkdir(scanDir, { mode: 0o700 });+ const client = new TestClient(+ {},+ {+ environment: {},+ prepareRuntime: async () => preparedRuntime(codexHome),+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ createCodex: () => ({+ startThread: () => ({+ id: null,+ async runStreamed() {+ async function* events() {+ yield { type: "thread.started", thread_id: "scan-thread" };+ yield { type: "turn.completed", usage: null };+ }+ return { events: events() };+ },+ }),+ }),+ },+ );++ await expect(client.run(repository, { maxCostUsd: 1 })).rejects.toThrow(+ "Cannot evaluate the cost limit",+ );+ await client.close();+ });+test("provides authoritative knowledge-base context without retaining its documents", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");diff --git a/sdk/typescript/tests-ts/cli-fixtures.ts b/sdk/typescript/tests-ts/cli-fixtures.tsindex bca849984..0b675fbe7 100644--- a/sdk/typescript/tests-ts/cli-fixtures.ts+++ b/sdk/typescript/tests-ts/cli-fixtures.ts@@ -7,6 +7,7 @@ import type {CoverageDocument,FindingsDocument,JsonObject,+ ScanCost,ScanManifest,ScanPreflight,SeverityLevel,@@ -206,6 +207,7 @@ export function fakeResult(threadId: "thread-1",turnResult: {status: "completed",+ model: "gpt-5.6-sol",finalResponse: "done",usage,},@@ -246,6 +248,7 @@ export function dependencies(environment?: NodeJS.ProcessEnv;signals?: FakeSignals;result?: ScanResult;+ costUpdates?: ScanCost[];workerStatuses?: import("../src/index.js").ScanWorkerStatus[];} = {},): MainDependencies {@@ -261,6 +264,11 @@ export function dependencies(options.onRun?.();if (!signal?.aborted) {(runOptions as { onScanStarted?: () => void }).onScanStarted?.();+ for (const cost of options.costUpdates ?? []) {+ (+ runOptions as { onCost?: (cost: Readonly<ScanCost>) => void }+ ).onCost?.(cost);+ }for (const status of options.workerStatuses ?? []) {(runOptions as {diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex a01ccd40a..0f1abbb57 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -25,6 +25,7 @@ import {CodexSecurityError,DiffTarget,OutputInsideProtectedRootError,+ ScanCostLimitExceededError,ScanInterruptedError,VERSION,} from "../src/index.js";@@ -2254,6 +2255,7 @@ describe("CLI", () => {).toBe(0);expect(help.text()).toContain("Usage: codex-security scan [repository]");expect(help.text()).toContain("--path <array>");+ expect(help.text()).toContain("--max-cost <number>");expect(help.text()).toContain("--model <string>");expect(help.text()).toContain("codex-security scan . --model gpt-5.6-terra",@@ -2422,6 +2424,7 @@ describe("CLI", () => {[["scan", ".", "--head", "HEAD"], "--head requires --diff"],[["scan", ".", "--base", "HEAD"], "--base requires --working-tree"],[["scan", ".", "--archive-existing"], "requires --output-dir"],+ [["scan", ".", "--max-cost=0"], "expected number to be >0"],[["scan", ".", "--path="], "--path must not be empty"],[["scan", ".", "--model="], "--model must not be empty"],[["scan", ".", "--mode", "bogus"], "Invalid option"],@@ -2429,6 +2432,7 @@ describe("CLI", () => {[["scan", ".", "--path", "--dry-run"], "Missing value for flag"],[["scan", ".", "--model", "--dry-run"], "Missing value for flag"],[["scan", ".", "--output-dir", "--dry-run"], "Missing value for flag"],+ [["scan", ".", "--max-cost", "--dry-run"], "Missing value for flag"],[["scan", "repo-a", "repo-b", "--dry-run"], "Unexpected positional"],[["scan", ".", "--format", "md"], "Markdown output is not supported"],[["scan", ".", "--format=md"], "Markdown output is not supported"],@@ -2893,12 +2897,80 @@ describe("CLI", () => {expect(stderr.text()).toContain("Tokens: 1,250 input, 200 cached, 30 output.",);+ expect(stderr.text()).toContain("Estimated cost: $0.00625 USD.");expect(stderr.text()).toContain("Results: /tmp/scan");expect(stderr.text()).toContain("Next: codex-security export /tmp/scan --export-format sarif",);});+ test("reports the running cost against the scan budget", async () => {+ const stdout = capture();+ const stderr = capture();+ const result = fakeResult([], "complete", {+ input_tokens: 1_250,+ cached_input_tokens: 200,+ output_tokens: 30,+ });++ expect(+ await main(+ ["scan", ".", "--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.00625 of $0.01 limit");+ });++ test("reports a scan stopped when its live cost exceeds the limit", async () => {+ const stdout = capture();+ const stderr = capture();+ const cost = fakeResult([], "complete", {+ input_tokens: 1_250,+ cached_input_tokens: 200,+ output_tokens: 30,+ }).cost!;++ expect(+ await main(+ ["scan", ".", "--json", "--max-cost", "0.005"],+ stdout.stream,+ stderr.stream,+ dependencies({+ onTurn: () => {+ throw new ScanCostLimitExceededError(0.005, cost, "/tmp/scan");+ },+ }),+ ),+ ).toBe(2);+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toContain(+ "Scan stopped: estimated cost $0.00625 exceeded the $0.005 limit; partial output remains at /tmp/scan.",+ );+ });++ test("accepts a scan at its estimated cost limit", async () => {+ const stdout = capture();+ const result = fakeResult([], "complete", {+ input_tokens: 1_250,+ cached_input_tokens: 200,+ output_tokens: 30,+ });++ expect(+ await main(+ ["scan", ".", "--json", "--max-cost", "0.00625"],+ stdout.stream,+ capture().stream,+ dependencies({ result }),+ ),+ ).toBe(0);+ expect(JSON.parse(stdout.text())).toEqual(result.toJSON());+ });+test("keeps scan progress scope and completion paths redacted", async () => {const stdout = capture();const stderr = capture();diff --git a/sdk/typescript/tests-ts/cost.test.ts b/sdk/typescript/tests-ts/cost.test.tsnew file mode 100644index 000000000..5e7d588b0--- /dev/null+++ b/sdk/typescript/tests-ts/cost.test.ts@@ -0,0 +1,270 @@+import {+ appendFile,+ mkdir,+ mkdtemp,+ realpath,+ rm,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, test } from "bun:test";+import { estimateScanCost, ScanCostTracker } from "../src/cost.js";++const temporaryDirectories: string[] = [];++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((directory) => rm(directory, { recursive: true, force: true })),+ );+});++async function codexHome(): Promise<string> {+ const directory = await realpath(+ await mkdtemp(join(tmpdir(), "codex-security-cost-")),+ );+ temporaryDirectories.push(directory);+ return directory;+}++async function writeSession(+ home: string,+ threadId: string,+ usage: Record<string, number>,+ parentThreadId?: string,+): Promise<string> {+ const directory = join(home, "sessions", "2026", "07", "26");+ await mkdir(directory, { recursive: true });+ const path = join(directory, `rollout-${threadId}.jsonl`);+ await writeFile(+ path,+ [+ JSON.stringify({+ type: "session_meta",+ payload: {+ id: threadId,+ ...(parentThreadId === undefined+ ? {}+ : {+ source: {+ subagent: {+ thread_spawn: { parent_thread_id: parentThreadId },+ },+ },+ }),+ },+ }),+ JSON.stringify({+ type: "event_msg",+ payload: {+ type: "token_count",+ info: { total_token_usage: usage },+ },+ }),+ "",+ ].join("\n"),+ );+ return path;+}++describe("scan cost", () => {+ test("uses published GPT-5.6 model rates", () => {+ const usage = { input_tokens: 1_000_000, output_tokens: 1_000_000 };++ expect(estimateScanCost("gpt-5.6", usage)?.estimatedUsd).toBe(35);+ expect(estimateScanCost("gpt-5.6-sol", usage)?.estimatedUsd).toBe(35);+ expect(estimateScanCost("gpt-5.6-terra", usage)?.estimatedUsd).toBe(17.5);+ expect(estimateScanCost("gpt-5.6-luna", usage)?.estimatedUsd).toBe(7);+ });++ test("charges cached input at its discounted rate", () => {+ expect(+ estimateScanCost("gpt-5.6-sol", {+ input_tokens: 1_250,+ cached_input_tokens: 200,+ output_tokens: 30,+ }),+ ).toEqual({+ model: "gpt-5.6-sol",+ inputTokens: 1_250,+ cachedInputTokens: 200,+ cacheWriteInputTokens: 0,+ outputTokens: 30,+ estimatedUsd: 0.00625,+ });+ });++ test("charges GPT-5.6 cache writes at their published rate", () => {+ expect(+ estimateScanCost("gpt-5.6-sol", {+ input_tokens: 1_000,+ cached_input_tokens: 100,+ cache_write_input_tokens: 200,+ output_tokens: 10,+ })?.estimatedUsd,+ ).toBe(0.0051);+ });++ test("does not double-charge reasoning tokens included in output", () => {+ expect(+ estimateScanCost("gpt-5.6-sol", {+ input_tokens: 1_000,+ output_tokens: 10,+ reasoning_output_tokens: 9,+ })?.estimatedUsd,+ ).toBe(0.0053);+ });++ test("does not invent prices for unknown models or incomplete usage", () => {+ for (const [model, usage] of [+ ["unknown-model", { input_tokens: 1, output_tokens: 1 }],+ ["gpt-5.6-sol", null],+ ["gpt-5.6-sol", {}],+ ["gpt-5.6-sol", { input_tokens: -1, output_tokens: 1 }],+ ["gpt-5.6-sol", { input_tokens: 1.5, output_tokens: 1 }],+ [+ "gpt-5.6-sol",+ { input_tokens: 1, cached_input_tokens: 2, output_tokens: 1 },+ ],+ [+ "gpt-5.6-sol",+ {+ input_tokens: Number.MAX_SAFE_INTEGER,+ output_tokens: Number.MAX_SAFE_INTEGER,+ },+ ],+ ] as const) {+ expect(estimateScanCost(model, usage)).toBeNull();+ }+ });+});++describe("live scan cost tracking", () => {+ test("counts the scan and delegated workers without including other scans", async () => {+ const home = await codexHome();+ await writeSession(home, "scan-thread", {+ input_tokens: 1_000,+ cached_input_tokens: 100,+ cache_write_input_tokens: 200,+ output_tokens: 10,+ reasoning_output_tokens: 2,+ });+ await writeSession(+ home,+ "worker-thread",+ {+ input_tokens: 250,+ cached_input_tokens: 50,+ output_tokens: 5,+ reasoning_output_tokens: 1,+ },+ "scan-thread",+ );+ await writeSession(home, "unrelated-thread", {+ input_tokens: 1_000_000,+ output_tokens: 1_000_000,+ });+ const tracker = new ScanCostTracker({+ codexHome: home,+ model: "gpt-5.6-sol",+ });+ tracker.start("scan-thread");++ expect(await tracker.stop()).toEqual({+ usage: {+ input_tokens: 1_250,+ cached_input_tokens: 150,+ cache_write_input_tokens: 200,+ output_tokens: 15,+ reasoning_output_tokens: 3,+ total_tokens: 1_265,+ },+ cost: {+ model: "gpt-5.6-sol",+ inputTokens: 1_250,+ cachedInputTokens: 150,+ cacheWriteInputTokens: 200,+ outputTokens: 15,+ estimatedUsd: 0.006275,+ },+ });+ });++ test("uses each session's final cumulative usage without double counting", async () => {+ const home = await codexHome();+ const path = await writeSession(home, "scan-thread", {+ input_tokens: 100,+ output_tokens: 10,+ });+ const tracker = new ScanCostTracker({+ codexHome: home,+ model: "gpt-5.6-terra",+ });+ tracker.start("scan-thread");+ expect((await tracker.refresh()).cost?.estimatedUsd).toBe(0.0004);++ const latest = JSON.stringify({+ type: "event_msg",+ payload: {+ type: "token_count",+ info: {+ total_token_usage: { input_tokens: 250, output_tokens: 20 },+ },+ },+ });+ await appendFile(path, `${latest}\n${latest}\n`);++ expect((await tracker.stop()).cost).toEqual({+ model: "gpt-5.6-terra",+ inputTokens: 250,+ cachedInputTokens: 0,+ cacheWriteInputTokens: 0,+ outputTokens: 20,+ estimatedUsd: 0.000925,+ });+ });++ test("reports a changed running cost only once", async () => {+ const home = await codexHome();+ await writeSession(home, "scan-thread", {+ input_tokens: 1_250,+ cached_input_tokens: 200,+ output_tokens: 30,+ });+ const updates: number[] = [];+ const tracker = new ScanCostTracker({+ codexHome: home,+ model: "gpt-5.6-sol",+ maxCostUsd: 0.005,+ onCost: (cost) => updates.push(cost.estimatedUsd),+ });+ tracker.start("scan-thread");++ await tracker.stop();++ expect(updates).toEqual([0.00625]);+ });++ test("falls back to the completed turn when session logs are unavailable", async () => {+ const tracker = new ScanCostTracker({+ codexHome: await codexHome(),+ model: "gpt-5.6-luna",+ });+ const usage = { input_tokens: 1_000, output_tokens: 20 };+ tracker.start("scan-thread");++ expect(await tracker.stop(usage)).toEqual({+ usage,+ cost: {+ model: "gpt-5.6-luna",+ inputTokens: 1_000,+ cachedInputTokens: 0,+ cacheWriteInputTokens: 0,+ outputTokens: 20,+ estimatedUsd: 0.00112,+ },+ });+ });+});diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.tsindex d57449cee..e739ed74f 100644--- a/sdk/typescript/tests-ts/multiscan.test.ts+++ b/sdk/typescript/tests-ts/multiscan.test.ts@@ -15,6 +15,7 @@ import { join } from "node:path";import { afterEach, describe, expect, test } from "bun:test";import type { ScanResult } from "../src/result.js";import { buildGitHubCredentialArgs, runMultiscan } from "../src/multiscan.js";+import { resolveTrustedExecutable } from "../src/trusted-executable.js";type MultiscanOptions = Parameters<typeof runMultiscan>[0];type SecurityClient = ReturnType<MultiscanOptions["createSecurity"]>;@@ -204,6 +205,36 @@ describe("multiscan", () => {]);});+ test("records each completed scan's cost in the resumable ledger", async () => {+ const paths = await fixture();+ const source = await repository(paths.root, "priced");+ await writeFile(+ paths.input,+ `id,repository,revision\npriced,${source.path},${source.revision}\n`,+ );+ const cost = {+ model: "gpt-5.6-sol",+ inputTokens: 1_250,+ cachedInputTokens: 200,+ cacheWriteInputTokens: 0,+ outputTokens: 30,+ estimatedUsd: 0.00625,+ };++ const summary = await runMultiscan(+ options(+ paths,+ client(async (_repository, scanOptions = {}) =>+ Object.assign(await completedScan(scanOptions.outputDir!), { cost }),+ ),+ ),+ );++ expect(await results(summary.resultsPath)).toMatchObject([+ { id: "priced", status: "completed", cost },+ ]);+ });+test("rejects malformed CSV and duplicate headers before starting scans", async () => {const paths = await fixture();const source = await repository(paths.root, "csv");@@ -509,12 +540,20 @@ describe("multiscan", () => {options(paths,client(async (checkout, scanOptions = {}) => {- const credential = execFileSync(+ const trustedGit = await resolveTrustedExecutable("git",+ { ...process.env, PATH: environment.get("PATH") ?? "" },+ paths.root,+ );+ if (trustedGit === null) {+ throw new Error("Git is not available on a trusted PATH.");+ }+ const credential = execFileSync(+ trustedGit.executable,["-C", checkout, "config", "--get", "multiscan.credential"],{encoding: "utf8",- env: { ...process.env, PATH: environment.get("PATH") ?? "" },+ env: trustedGit.environment,stdio: ["ignore", "pipe", "pipe"],},).trim();diff --git a/sdk/typescript/tests-ts/result.test.ts b/sdk/typescript/tests-ts/result.test.tsindex cebf4a72c..6566e5228 100644--- a/sdk/typescript/tests-ts/result.test.ts+++ b/sdk/typescript/tests-ts/result.test.ts@@ -64,9 +64,31 @@ describe("ScanResult", () => {expect(result.toJSON()).toMatchObject({scanDir: "/scan",threadId: "thread",+ cost: null,});});+ test("includes the model and estimated cost in machine-readable results", () => {+ const result = new ScanResult({+ manifest,+ findings,+ coverage,+ scanDir: "/scan",+ threadId: "thread",+ turnResult: {+ model: "gpt-5.6-sol",+ usage: {+ input_tokens: 1_250,+ cached_input_tokens: 200,+ output_tokens: 30,+ },+ },+ });++ expect(result.cost?.estimatedUsd).toBe(0.00625);+ expect(result.toJSON()["cost"]).toEqual(result.cost);+ });+test("discovers SARIF at its canonical scan path", async () => {const scanDir = await mkdtemp(join(tmpdir(), "codex-security-result-"));try {