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
feat(cli): make cost display optional (#881)
ianw-oai788b0bb4358f
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex e0f904c0f..6b46987f0 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -381,6 +381,10 @@ const PROVIDER_OPTION = z.enum(["openai", "openrouter", "fireworks", "amazon-bedrock"]).default("openai").describe("Inference provider for scans.");+const SHOW_COST_OPTION = z+ .boolean()+ .default(false)+ .describe("Show estimated USD cost; always shown when a cost limit is set.");const CREATE_PR_OPTION = z.boolean().default(false)@@ -960,6 +964,7 @@ interface ScanArguments extends ResolvedScanSettings {patch?: boolean;patchSeverity?: FailureSeverity;createPr?: boolean;+ showCost?: boolean;headless?: boolean;dryRun: boolean;parentScanId?: string;@@ -2112,6 +2117,7 @@ export async function main(scanId: z.string().min(1).describe("Interrupted Deep Scan identifier."),}),options: z.object({+ showCost: SHOW_COST_OPTION,verbose: z.boolean().default(false)@@ -2154,6 +2160,7 @@ export async function main(// Resume uses the installed engine with the saved recipe and checkpoints.scanArguments.expectedPluginVersion = undefined;scanArguments.verbose = options.verbose;+ scanArguments.showCost = options.showCost;} catch (error) {const message = errorMessage(error);errorOutput.write(`codex-security: ${message}\n`);@@ -2188,6 +2195,7 @@ export async function main(.describe("Saved scan identifier (default: latest completed scan)."),}),options: z.object({+ showCost: SHOW_COST_OPTION,scanPromptFile: optionValue("--scan-prompt-file").optional().describe(@@ -2281,6 +2289,7 @@ export async function main(dependencies.currentDirectory(),);scanArguments.verbose = options.verbose;+ scanArguments.showCost = options.showCost;} catch (error) {const message = errorMessage(error);errorOutput.write(`codex-security: ${message}\n`);@@ -3440,6 +3449,7 @@ export async function main(maxCost: ScanSettingsSchema.shape.maxCostUsd.describe("Stop above AMOUNT in estimated USD; the dashboard offers increases near the limit.",),+ showCost: SHOW_COST_OPTION,headless: z.boolean().default(false)@@ -3573,6 +3583,7 @@ export async function main(patch: options.patch,patchSeverity: options.patchSeverity,createPr: options.createPr,+ showCost: options.showCost,headless: options.headless,dryRun: options.dryRun,mock: options.mock,@@ -3956,6 +3967,7 @@ export async function main(.describe("Stop each component scan if estimated USD cost exceeds AMOUNT.",),+ showCost: SHOW_COST_OPTION,pluginPath: optionValue("--plugin-path").optional().describe(PLUGIN_PATH_DESCRIPTION),@@ -4058,6 +4070,7 @@ export async function main(model: scanModelConfiguration(await mergedCodexConfig(config)),mode: settings.mode,maxCostUsd: settings.maxCostUsd,+ showCost: options.showCost,clock: dependencies,color: dependencies.environment["NO_COLOR"] === undefined,sanitize: safeErrorMessage,@@ -4101,7 +4114,11 @@ export async function main(const componentName =componentNames.get(event.componentId) ??event.componentId;- const line = componentScanEventLine(componentName, event);+ const line = componentScanEventLine(+ componentName,+ event,+ options.showCost || settings.maxCostUsd !== undefined,+ );if (line !== null) errorOutput.write(line);}: (event) => dashboard?.recordComponentEvent(event),@@ -7643,6 +7660,7 @@ async function executeScan(let fileProgress: ScanProgress | null = null;let runningCost: Readonly<ScanCost> | null = null;let maxCostUsd = arguments_.maxCostUsd;+ const showCost = arguments_.showCost === true || maxCostUsd !== undefined;let phase: string | null = null;const targetWarnings: string[] = [];const configuredLogLevel =@@ -7837,6 +7855,7 @@ async function executeScan(dashboard = new ScanDashboard(errorOutput, {repository,mode: arguments_.mode,+ showCost,model: scanModelConfiguration(await mergedCodexConfig(config)),...(arguments_.maxCostUsd === undefined? {}@@ -7869,7 +7888,8 @@ async function executeScan(}if (runningCost !== null) {details.push(`Tokens: ${formatScanCostTokens(runningCost)}`);- details.push(`Cost: ${formatUsd(runningCost.estimatedUsd)}`);+ if (showCost)+ details.push(`Cost: ${formatUsd(runningCost.estimatedUsd)}`);}return details.length === 0 ? stage : `${stage} | ${details.join(" | ")}`;};@@ -7914,7 +7934,7 @@ async function executeScan(maxCostUsd = limit;diagnostic("cost.updated", {model: cost.model,- estimated_usd: cost.estimatedUsd,+ estimated_usd: showCost ? cost.estimatedUsd : undefined,input_tokens: cost.inputTokens,cached_input_tokens: cost.cachedInputTokens,cache_write_input_tokens: cost.cacheWriteInputTokens,@@ -7929,7 +7949,7 @@ async function executeScan(progress?.stopTimer();if (maxCostUsd === undefined) {progress?.stage(- `Tokens: ${formatScanCostTokens(cost)}. Estimated cost: ${formatUsd(cost.estimatedUsd)} USD.`,+ `Tokens: ${formatScanCostTokens(cost)}.${showCost ? ` Estimated cost: ${formatUsd(cost.estimatedUsd)} USD.` : ""}`,);} else {progress?.stage(@@ -8285,6 +8305,7 @@ async function executeScan(progress?.interactive === true &&dependencies.environment["NO_COLOR"] === undefined &&dependencies.environment["TERM"] !== "dumb",+ showCost,deepScanStop,);const completedScan = (exitCode: number): ScanOutcome => {@@ -8292,7 +8313,7 @@ async function executeScan(coverage: result.coverage.completeness,findings: findings.length,scan_id: result.manifest.scan.id,- estimated_usd: result.cost?.estimatedUsd,+ estimated_usd: showCost ? result.cost?.estimatedUsd : undefined,exit_code: exitCode,});progress?.stopTimer();@@ -8661,6 +8682,7 @@ function printScanSummary(progress: Progress | null,errorOutput: Writable,color: boolean,+ showCost: boolean,deepScanStop?: DeepScanStop,): void {const paint = (value: string, code: number | string): string =>@@ -8722,11 +8744,13 @@ function printScanSummary(if (tokenSummary !== null) {errorOutput.write(` ${paint("TOKENS", 1)} ${tokenSummary}\n`);}- const costSummary =- result.cost === null- ? "unavailable (model pricing or usage missing)"- : `${formatUsd(result.cost.estimatedUsd)} (standard, short context)`;- errorOutput.write(` ${paint("COST", 1)} ${costSummary}\n`);+ if (showCost) {+ const costSummary =+ result.cost === null+ ? "unavailable (model pricing or usage missing)"+ : `${formatUsd(result.cost.estimatedUsd)} (standard, short context)`;+ errorOutput.write(` ${paint("COST", 1)} ${costSummary}\n`);+ }errorOutput.write(` ${paint("RESULTS", 1)} ${errorMessage(result.scanDir)}\n`,);@@ -8738,6 +8762,7 @@ function printScanSummary(function componentScanEventLine(componentName: string,event: ComponentScanEvent,+ showCost: boolean,): string | null {if (event.type === "progress") {const progress = event.value;@@ -8745,7 +8770,7 @@ function componentScanEventLine(}if (event.type !== "cost") return null;const cost = event.value;- return `codex-security: ${componentName} | Tokens: ${formatScanCostTokens(cost)} | Cost: ${formatUsd(cost.estimatedUsd)}\n`;+ return `codex-security: ${componentName} | Tokens: ${formatScanCostTokens(cost)}${showCost ? ` | Cost: ${formatUsd(cost.estimatedUsd)}` : ""}\n`;}function protectedRootErrorMessage(diff --git a/sdk/typescript/src/scan-dashboard.ts b/sdk/typescript/src/scan-dashboard.tsindex e08ae0d0d..f6685a108 100644--- a/sdk/typescript/src/scan-dashboard.ts+++ b/sdk/typescript/src/scan-dashboard.ts@@ -56,6 +56,7 @@ interface ScanDashboardOptions {mode?: ScanMode;model?: ScanModelConfiguration;maxCostUsd?: number;+ showCost?: boolean;clock: DashboardClock;color?: boolean;sanitize?: (value: string) => string;@@ -621,7 +622,7 @@ export class ScanDashboard {? []: [` STAGE ${this.#stage}`, ` FILES ${files}`]),...this.#tokenLines(),- ` COST ${cost}`,+ ...(this.#showCost ? [` COST ${cost}`] : []),...(this.#budget === null? []: [@@ -718,7 +719,7 @@ export class ScanDashboard {}#componentRows(): number {- return Math.max(1, (this.#stream.rows ?? 24) - 11);+ return Math.max(1, (this.#stream.rows ?? 24) - (this.#showCost ? 11 : 10));}#componentFrame(): string {@@ -731,7 +732,7 @@ export class ScanDashboard {this.#components.length - rows,),);- const nameWidth = Math.max(10, width - 61);+ const nameWidth = Math.max(10, width - (this.#showCost ? 61 : 52));const row = (marker: string,name: string,@@ -740,7 +741,7 @@ export class ScanDashboard {findings: string,cost: string,): string =>- ` ${marker} ${fitLine(this.#options.sanitize?.(name) ?? name, nameWidth).padEnd(nameWidth)} ${fitLine(status, 24).padEnd(24)} ${files.padStart(11)} ${findings.padStart(8)} ${cost.padStart(8)}`;+ ` ${marker} ${fitLine(this.#options.sanitize?.(name) ?? name, nameWidth).padEnd(nameWidth)} ${fitLine(status, 24).padEnd(24)} ${files.padStart(11)} ${findings.padStart(8)}${this.#showCost ? ` ${cost.padStart(8)}` : ""}`;const table = this.#components.slice(first, first + rows).map(({ receipt, dashboard }, index) => {@@ -790,12 +791,22 @@ export class ScanDashboard {divider,` SCOPE ${selected?.paths.join(", ") ?? "waiting for component plan"}`,` STATUS ${selected?.error ?? findings}`,- ` COST ${costs.length === 0 ? "waiting for usage" : formatUsd(costs.reduce((sum, value) => sum + value, 0))} · component scans only`,+ ...(this.#showCost+ ? [+ ` COST ${costs.length === 0 ? "waiting for usage" : formatUsd(costs.reduce((sum, value) => sum + value, 0))} · component scans only`,+ ]+ : []),` STAGE ${this.#stage}`,` TIME ${formatElapsed(Math.max(0, Math.floor((this.#options.clock.now() - this.#startedAt) / 1_000)))} · ↑↓ select · Enter activity · Ctrl+C cancel`,]);}+ get #showCost(): boolean {+ return (+ this.#options.showCost === true || this.#options.maxCostUsd !== undefined+ );+ }+#width(): number {return Math.max(1, Math.min(this.#stream.columns ?? 88, 160));}@@ -809,7 +820,7 @@ export class ScanDashboard {(this.#options.presentation === "publication" ||this.#options.presentation === "verification"? 0- : this.#tokenLines().length - 1) ++ : this.#tokenLines().length - 1 - (this.#showCost ? 0 : 1)) +(this.#options.presentation === "publication"? 2: this.#options.mode === "deep"diff --git a/sdk/typescript/tests-ts/cli-project-config.test.ts b/sdk/typescript/tests-ts/cli-project-config.test.tsindex a1d6a9cda..8b993b721 100644--- a/sdk/typescript/tests-ts/cli-project-config.test.ts+++ b/sdk/typescript/tests-ts/cli-project-config.test.ts@@ -472,6 +472,7 @@ test.each(["standard", "deep"] as const)(deep: { workers: 2, subagents_per_worker: 0 },},codex: { model: "gpt-5.6-terra" },+ limits: { max_cost_usd_per_scan: 7 },policy: { fail_on_severity: "high" },output: { directory: "../component-results" },});@@ -489,6 +490,12 @@ test.each(["standard", "deep"] as const)();let selected: ScanOptions | undefined;const stdout = capture();+ const stderr = capture();+ const result = fakeResult(["high"], "complete", {+ input_tokens: 1250,+ cached_input_tokens: 200,+ output_tokens: 30,+ });expect(await main([@@ -502,10 +509,11 @@ test.each(["standard", "deep"] as const)("--json",],stdout.stream,- capture().stream,+ stderr.stream,dependencies({currentDirectory: input.root,- result: fakeResult(["high"]),+ result,+ costUpdates: [result.cost!],onTurn: (_repository, options) => {selected = options as ScanOptions;},@@ -517,7 +525,9 @@ test.each(["standard", "deep"] as const)(target: ["lib"],scanPrompt: "Review synthetic boundaries.",failureSeverity: "high",+ maxCostUsd: 7,});+ expect(stderr.text()).toContain("Cost: $0.00488");if (mode === "deep")expect(selected).toMatchObject({ workers: 2, subagents: 0 });else@@ -588,6 +598,7 @@ test("actual CLI parsing preserves file values when flags are absent", async ()expect(JSON.parse(stdout.text())).toMatchObject({manifest: { scan: { status: "completed" } },});+ expect(stderr.text()).toContain("COST");});test("CLI values override matching file values, including native objects and lists", async () => {diff --git a/sdk/typescript/tests-ts/cli-show-cost.test.ts b/sdk/typescript/tests-ts/cli-show-cost.test.tsnew file mode 100644index 000000000..ca9cb0d0e--- /dev/null+++ b/sdk/typescript/tests-ts/cli-show-cost.test.ts@@ -0,0 +1,92 @@+import { expect, test } from "bun:test";+import { main } from "../src/cli.js";+import { capture, dependencies, fakeResult } from "./cli-fixtures.js";++const result = fakeResult([], "complete", {+ input_tokens: 1250,+ cached_input_tokens: 200,+ output_tokens: 30,+});++test.each([false, true])("scan cost visibility with TTY %p", async (tty) => {+ for (const costFlags of [+ [],+ ["--show-cost"],+ ["--show-cost=false", "--max-cost", "20"],+ ]) {+ const stdout = capture();+ const stderr = capture(tty);+ expect(+ await main(+ ["scan", ".", ...costFlags, ...(tty ? [] : ["--json"])],+ stdout.stream,+ stderr.stream,+ dependencies({+ result,+ costUpdates: [result.cost!],+ }),+ ),+ ).toBe(0);+ const text = stderr.text();+ const showCost = costFlags.length > 0;+ expect(text.includes("COST")).toBe(showCost);+ expect(text).toContain("1,280 total");+ const progress = text.split("REPORT")[0]!;+ expect(progress.includes("$0.00488")).toBe(showCost);+ if (!tty) expect(JSON.parse(stdout.text())).toEqual(result.toJSON());+ }+});++test.each(["resume", "rerun"])(+ "scans %s uses the display flag and saved cost limit",+ async (command) => {+ for (const [flags, maxCostUsd, showCost] of [+ [[], undefined, false],+ [["--show-cost"], undefined, true],+ [[], 20, true],+ ] as const) {+ const stderr = capture();+ expect(+ await main(+ ["scans", command, "scan-original", ...flags],+ capture().stream,+ stderr.stream,+ dependencies({+ result,+ costUpdates: [result.cost!],+ onWorkbench: () => ({+ scanId: "scan-original",+ scanDir: "/tmp/scan",+ recipe: {+ repository: "/synthetic/repository",+ target: { kind: "repository", paths: [] },+ mode: "deep",+ config: {},+ ...(maxCostUsd === undefined ? {} : { maxCostUsd }),+ },+ }),+ }),+ ),+ ).toBe(0);+ expect(stderr.text().includes("$0.00488")).toBe(showCost);+ }+ },+);++test.each([false, true])(+ "missing pricing follows cost visibility: %j",+ async (showCost) => {+ const stderr = capture();+ expect(+ await main(+ ["scan", ...(showCost ? ["--show-cost"] : [])],+ capture().stream,+ stderr.stream,+ dependencies(),+ ),+ ).toBe(0);+ expect(+ stderr.text().includes("unavailable (model pricing or usage missing)"),+ ).toBe(showCost);+ },+);diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex f4580b956..178d92ce4 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -149,6 +149,7 @@ describe("CLI", () => {maxTimeHours: { type: "number", maximum: 96 },model: { type: "string" },verbose: { type: "boolean" },+ showCost: { type: "boolean", default: false },effort: {enum: ["minimal", "low", "medium", "high", "xhigh", "max"],},@@ -1990,8 +1991,10 @@ describe("CLI", () => {"Scan phase: reviewing files (2 workers).",);expect(stderr.text()).toContain(- "Running scan: reviewing files | Workers: 2/2 | 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: 2/2 | Files: 3/8 | Tokens: unavailable uncached input, 200 cache reads, unavailable cache writes, 30 output, 1,280 total",);+ expect(stderr.text()).not.toContain("Cost:");+ expect(stderr.text()).not.toContain("COST");expect(stderr.text()).not.toContain("CODEX SECURITY");expect(stderr.text()).not.toContain("\u001B");expect(stderr.text()).not.toContain("\r");@@ -2249,7 +2252,7 @@ describe("CLI", () => {expect(text).not.toContain("0 / 1,258 reviewed");expect(text).toContain("worker 1 · read routes/login.ts");expect(text).toContain("TOKENS");- expect(text).toContain("COST");+ expect(text).not.toContain("COST");expect(text).toContain("TIME");});@@ -2357,6 +2360,7 @@ describe("CLI", () => {expect(help.text()).toContain("--verbose");expect(help.text()).toContain("--path <array>");expect(help.text()).toContain("--max-cost <number>");+ expect(help.text()).toContain("--show-cost");expect(help.text()).toContain("--workers <number>");expect(help.text()).toContain("--subagents <number>");expect(help.text()).toContain("--stop-after-no-new <number>");@@ -4270,7 +4274,6 @@ describe("CLI", () => {" COVERAGE complete"," ELAPSED 6m 37s"," TOKENS unavailable uncached input, 200 cache reads, unavailable cache writes, 30 output, 1,280 total",- " COST $0.00488 (standard, short context)"," RESULTS /tmp/scan",].join("\n"),);@@ -4695,7 +4698,7 @@ describe("CLI", () => {expect(stderr.text()).not.toContain("synthetic-parent");});- test("shows live stage, files, workers, tokens, and cost without a budget", async () => {+ test("shows live stage, files, workers, tokens, and opt-in cost without a budget", async () => {const stdout = capture();const stderr = capture();const result = fakeResult([], "complete", {@@ -4706,7 +4709,7 @@ describe("CLI", () => {expect(await main(- ["scan", ".", "--json"],+ ["scan", ".", "--show-cost", "--json"],stdout.stream,stderr.stream,dependencies({@@ -4782,7 +4785,7 @@ describe("CLI", () => {expect(await main(- ["scan", ".", "--json"],+ ["scan", ".", "--show-cost", "--json"],stdout.stream,stderr.stream,dependencies({@@ -4888,6 +4891,7 @@ describe("CLI", () => {expect(JSON.parse(stdout.text())).toEqual(result.toJSON());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=");});test("reports and classifies a scan stopped when its live cost exceeds the limit", async () => {diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.tsindex 6674f4e0d..06a1d0ac0 100644--- a/sdk/typescript/tests-ts/component-scan.test.ts+++ b/sdk/typescript/tests-ts/component-scan.test.ts@@ -461,9 +461,16 @@ test("forwards scan events with their component identity without letting observe}});-test.each(["dashboard", "headless", "ci"])(- "CLI component presentation: %s",- async (presentation) => {+test.each([+ ["dashboard", []],+ ["headless", []],+ ["ci", []],+ ["dashboard", ["--show-cost"]],+ ["headless", ["--show-cost"]],+ ["ci", ["--max-cost", "20"]],+] as const)(+ "CLI component presentation: %s, flags: %j",+ async (presentation, costFlags) => {const paths = await fixture();const stdout = capture();const stderr = capture(true);@@ -477,6 +484,7 @@ test.each(["dashboard", "headless", "ci"])("--output-dir",paths.outputDir,...(presentation === "headless" ? ["--headless"] : []),+ ...costFlags,"--json",],stdout.stream,@@ -516,6 +524,9 @@ test.each(["dashboard", "headless", "ci"])(presentation === "dashboard",);expect(stderr.text()).toContain("Report:");+ expect(stderr.text().includes("$0.00123")).toBe(costFlags.length > 0);+ if (costFlags.length === 0)+ expect(stderr.text()).not.toMatch(/\bCOST\b|\bCost:/u);if (presentation === "dashboard") {expect(stderr.text()).toContain("validating findings");expect(stderr.text().indexOf("\u001B[?1049l")).toBeLessThan(@@ -527,7 +538,7 @@ test.each(["dashboard", "headless", "ci"])("apps/api validating findings | Files: 2/2",);expect(stderr.text()).toContain(- "apps/api | Tokens: 90 uncached input, 10 cache reads, 0 cache writes, 20 output, 120 total | Cost: $0.00123",+ "apps/api | Tokens: 90 uncached input, 10 cache reads, 0 cache writes, 20 output, 120 total",);}expect(diff --git a/sdk/typescript/tests-ts/scan-dashboard.test.ts b/sdk/typescript/tests-ts/scan-dashboard.test.tsindex 80b330e27..531cefc64 100644--- a/sdk/typescript/tests-ts/scan-dashboard.test.ts+++ b/sdk/typescript/tests-ts/scan-dashboard.test.ts@@ -134,6 +134,7 @@ describe("live scan dashboard", () => {{repository: "/synthetic/project",presentation: "components",+ showCost: true,input,clock: {...fakeClock(),@@ -299,12 +300,15 @@ describe("live scan dashboard", () => {expect(frame()).toContain("Component 19");expect(frame()).not.toContain("Component 0 ");expect(frame()).toContain("[redacted] unavailable");+ expect(frame()).not.toContain("Cost");expect(frame().split("\n").every((line) => line.length <= 80),).toBe(true);- input.emit("data", "\r\u0003");+ input.emit("data", "\r");+ expect(frame()).not.toContain("COST");+ input.emit("data", "\u0003");expect(interrupted).toBe(true);dashboard.stop();});@@ -625,7 +629,7 @@ describe("live scan dashboard", () => {expect(frame).toContain("worker 1 · Reviewed source file 2");expect(frame).toContain("worker 1 · Reviewed source file 6");expect(frame).toContain("TOKENS");- expect(frame).toContain("COST");+ expect(frame).not.toContain("COST");expect(frame).toContain("TIME");});@@ -883,7 +887,7 @@ describe("live scan dashboard", () => {expect(frame).not.toContain("above live");input.emit("data", "\u001B[5~");- expect(lastFrame(stderr)).toContain("6 lines above live");+ expect(lastFrame(stderr)).toContain("7 lines above live");input.emit("data", "\u001B[6~");expect(lastFrame(stderr)).not.toContain("above live");dashboard.stop();