@openai/codex-security 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +127 -13
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/.mcp.json +8 -1
  4. package/_bundled_plugin/examples/completed-scan/findings.json +6 -0
  5. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +1 -1
  6. package/_bundled_plugin/mcp/mcp-app.html.br +0 -0
  7. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  8. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  9. package/_bundled_plugin/preflight/capability-profiles.toml +0 -57
  10. package/_bundled_plugin/references/config-preflight.md +1 -1
  11. package/_bundled_plugin/references/final-report.md +15 -7
  12. package/_bundled_plugin/references/finding-detail-fields.md +10 -2
  13. package/_bundled_plugin/references/scan-artifacts.md +11 -9
  14. package/_bundled_plugin/references/scan-contract.md +3 -1
  15. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +42 -0
  16. package/_bundled_plugin/schemas/definitions/discovery-candidate.schema.json +100 -0
  17. package/_bundled_plugin/schemas/tools/candidate-attack-paths.schema.json +181 -0
  18. package/_bundled_plugin/schemas/tools/candidate-validations.schema.json +166 -0
  19. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +120 -0
  20. package/_bundled_plugin/schemas/tools/discovery-candidates.schema.json +83 -0
  21. package/_bundled_plugin/schemas/tools/review-items.schema.json +80 -0
  22. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +572 -0
  23. package/_bundled_plugin/schemas/tools/worker-threat-model.schema.json +18 -0
  24. package/_bundled_plugin/scripts/deep_scan_config.py +11 -3
  25. package/_bundled_plugin/scripts/deep_scan_workbench.py +153 -133
  26. package/_bundled_plugin/scripts/finalize_scan_contract.py +39 -0
  27. package/_bundled_plugin/scripts/generate_in_scope_files.py +134 -0
  28. package/_bundled_plugin/scripts/workbench_cli.py +33 -1
  29. package/_bundled_plugin/scripts/workbench_db.py +181 -118
  30. package/_bundled_plugin/scripts/workbench_feedback.py +2 -0
  31. package/_bundled_plugin/scripts/workbench_native_indexes.py +5 -49
  32. package/_bundled_plugin/scripts/workbench_progress.py +86 -3
  33. package/_bundled_plugin/scripts/workbench_remediation.py +19 -1
  34. package/_bundled_plugin/scripts/workbench_scan_history.py +7 -1
  35. package/_bundled_plugin/scripts/workbench_scan_start.py +11 -5
  36. package/_bundled_plugin/scripts/workbench_scan_usage.py +557 -0
  37. package/_bundled_plugin/scripts/workbench_schema.py +501 -0
  38. package/_bundled_plugin/scripts/workbench_target.py +14 -1
  39. package/_bundled_plugin/scripts/workbench_validation.py +117 -13
  40. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +4 -4
  41. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +34 -28
  42. package/_bundled_plugin/skills/finding-discovery/SKILL.md +1 -1
  43. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +11 -8
  44. package/_bundled_plugin/skills/security-scan/SKILL.md +16 -9
  45. package/_bundled_plugin/skills/security-scan/references/repository-wide-scan.md +26 -14
  46. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +1 -1
  47. package/_bundled_plugin/skills/threat-model/SKILL.md +2 -2
  48. package/_bundled_plugin/skills/validation/SKILL.md +5 -5
  49. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +145 -227
  50. package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +53 -68
  51. package/dist/api.d.ts +30 -8
  52. package/dist/api.d.ts.map +1 -1
  53. package/dist/api.js +438 -66
  54. package/dist/api.js.map +1 -1
  55. package/dist/auth.d.ts.map +1 -1
  56. package/dist/auth.js +262 -44
  57. package/dist/auth.js.map +1 -1
  58. package/dist/cli.d.ts +4 -3
  59. package/dist/cli.d.ts.map +1 -1
  60. package/dist/cli.js +713 -148
  61. package/dist/cli.js.map +1 -1
  62. package/dist/config.d.ts +28 -0
  63. package/dist/config.d.ts.map +1 -1
  64. package/dist/config.js +39 -2
  65. package/dist/config.js.map +1 -1
  66. package/dist/contract.d.ts.map +1 -1
  67. package/dist/contract.js +14 -0
  68. package/dist/contract.js.map +1 -1
  69. package/dist/cost.d.ts +7 -0
  70. package/dist/cost.d.ts.map +1 -1
  71. package/dist/cost.js +397 -26
  72. package/dist/cost.js.map +1 -1
  73. package/dist/errors.d.ts +2 -0
  74. package/dist/errors.d.ts.map +1 -1
  75. package/dist/errors.js +48 -0
  76. package/dist/errors.js.map +1 -1
  77. package/dist/index.d.ts +3 -2
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js.map +1 -1
  80. package/dist/multiscan.d.ts +1 -0
  81. package/dist/multiscan.d.ts.map +1 -1
  82. package/dist/multiscan.js +5 -7
  83. package/dist/multiscan.js.map +1 -1
  84. package/dist/runtime.d.ts +40 -1
  85. package/dist/runtime.d.ts.map +1 -1
  86. package/dist/runtime.js +742 -46
  87. package/dist/runtime.js.map +1 -1
  88. package/dist/scan-activity.d.ts +13 -0
  89. package/dist/scan-activity.d.ts.map +1 -0
  90. package/dist/scan-activity.js +319 -0
  91. package/dist/scan-activity.js.map +1 -0
  92. package/dist/scan-dashboard.d.ts +47 -0
  93. package/dist/scan-dashboard.d.ts.map +1 -0
  94. package/dist/scan-dashboard.js +444 -0
  95. package/dist/scan-dashboard.js.map +1 -0
  96. package/dist/scan-history-renderer.d.ts.map +1 -1
  97. package/dist/scan-history-renderer.js +4 -1
  98. package/dist/scan-history-renderer.js.map +1 -1
  99. package/dist/version.d.ts +1 -1
  100. package/dist/version.js +1 -1
  101. package/dist/version.js.map +1 -1
  102. package/dist/worker-progress.d.ts +7 -0
  103. package/dist/worker-progress.d.ts.map +1 -1
  104. package/dist/worker-progress.js +68 -0
  105. package/dist/worker-progress.js.map +1 -1
  106. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -4,8 +4,7 @@ import { accessSync, constants, existsSync, lstatSync, realpathSync, writeSync,
4
4
  import { mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
5
5
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep, win32, } from "node:path";
6
6
  import { cwd } from "node:process";
7
- import { createInterface } from "node:readline";
8
- import { Readable, Writable as NodeWritable } from "node:stream";
7
+ import { Writable as NodeWritable } from "node:stream";
9
8
  import { pipeline } from "node:stream/promises";
10
9
  import { fileURLToPath, pathToFileURL } from "node:url";
11
10
  import { Cli, z } from "incur";
@@ -13,13 +12,14 @@ import { parse as parseToml } from "smol-toml";
13
12
  import { classifyConnectionFailure, CodexSecurity, scanAuthentication, } from "./api.js";
14
13
  import { accountStatus } from "./auth.js";
15
14
  import { createBulkScanDiscoveryDependencies, runBulkScanWizard, } from "./bulk-scan-discovery.js";
16
- import { DEFAULT_CODEX_CONFIG, mergedCodexConfig, scanModelConfiguration, } from "./config.js";
15
+ import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanModelConfiguration, } from "./config.js";
17
16
  import { formatUsd } from "./cost.js";
18
- import { CodexSecurityError, OutputInsideProtectedRootError, ScanInterruptedError, } from "./errors.js";
17
+ import { CodexSecurityError, ConfigurationError, InvalidTargetError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, redactedErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
19
18
  import { runMultiscan } from "./multiscan.js";
20
19
  import { bundledPluginRoot, codexSecurityCredentialHome, codexSecurityStateDirectory, expandHome, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
21
20
  import { matchScanFindings, } from "./scan-comparison.js";
22
21
  import { renderScanHistory, } from "./scan-history-renderer.js";
22
+ import { ScanDashboard } from "./scan-dashboard.js";
23
23
  import { DiffTarget } from "./targets.js";
24
24
  import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, updateNoticeEnabled, VERSION, } from "./version.js";
25
25
  const PROGRESS_REFRESH_MILLISECONDS = 1_000;
@@ -28,11 +28,15 @@ const MAX_CODEX_OVERRIDE_VALUE_LENGTH = 64 * 1_024;
28
28
  const MAX_CODEX_OVERRIDE_DEPTH = 64;
29
29
  const MAX_SKILL_INPUT_BYTES = 1_024 * 1_024;
30
30
  const MAX_SKILL_INPUT_COUNT = 64;
31
+ const MAX_SKILL_EVENT_BYTES = 1_024 * 1_024;
32
+ const MAX_SKILL_RESPONSE_BYTES = 256 * 1_024;
33
+ const SKILL_OUTPUT_LIMIT_MESSAGE = "Codex skill output exceeded the 1 MiB event or 256 KiB response safety limit.";
31
34
  const WINDOWS_NETWORK_PATH = /^[\\/]{2}/u;
32
35
  const WINDOWS_LOCAL_DEVICE_ROOT = /^[\\/]{2}[?.][\\/](?:[A-Za-z]:|Volume\{[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\}|GLOBALROOT[\\/]Device[\\/]HarddiskVolume[0-9]+)(?=[\\/]|$)/iu;
33
36
  const SCAN_HISTORY_OUTPUT_OPTION = /^--(?:format|filter-output|full-output|token-count|token-limit|token-offset)(?:=|$)/u;
34
37
  const HIDE_CURSOR = "\u001B[?25l";
35
38
  const SHOW_CURSOR = "\u001B[?25h";
39
+ const CHILD_TERMINATION_GRACE_MS = 1_000;
36
40
  const REPORTABLE_SEVERITIES = [
37
41
  "critical",
38
42
  "high",
@@ -69,6 +73,7 @@ const VALUE_OPTIONS = new Set([
69
73
  "--mode",
70
74
  "--model",
71
75
  "--effort",
76
+ "--provider",
72
77
  "--output-dir",
73
78
  "--plugin-path",
74
79
  "--python",
@@ -76,6 +81,9 @@ const VALUE_OPTIONS = new Set([
76
81
  "--fail-on-severity",
77
82
  "--max-cost",
78
83
  "--workers",
84
+ "--subagents",
85
+ "--stop-after-no-new",
86
+ "--max-discovery-runs",
79
87
  "--max-attempts",
80
88
  "--export-format",
81
89
  "--output",
@@ -87,6 +95,10 @@ const VALUE_OPTIONS = new Set([
87
95
  "--scan-root",
88
96
  "--reason",
89
97
  ]);
98
+ const PROVIDER_OPTION = z
99
+ .enum(["openai", "openrouter", "fireworks"])
100
+ .default("openai")
101
+ .describe("Inference provider for scans.");
90
102
  function optionValue(flag) {
91
103
  return z.string().min(1, `${flag} must not be empty.`);
92
104
  }
@@ -98,6 +110,32 @@ function effortOption() {
98
110
  .optional()
99
111
  .describe(`Model reasoning effort (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.reasoningEffort}).`);
100
112
  }
113
+ const DEEP_SCAN_OPTION_SCHEMAS = {
114
+ workers: z
115
+ .number()
116
+ .int()
117
+ .positive()
118
+ .optional()
119
+ .describe("Maximum concurrent deep-scan discovery workers."),
120
+ subagents: z
121
+ .number()
122
+ .int()
123
+ .nonnegative()
124
+ .optional()
125
+ .describe("Subagents available to each deep-scan worker."),
126
+ stopAfterNoNew: z
127
+ .number()
128
+ .int()
129
+ .positive()
130
+ .optional()
131
+ .describe("Stop after this many runs find no new issues."),
132
+ maxDiscoveryRuns: z
133
+ .number()
134
+ .int()
135
+ .positive()
136
+ .optional()
137
+ .describe("Maximum deep-scan discovery runs."),
138
+ };
101
139
  const DEFAULT_DEPENDENCIES = {
102
140
  createSecurity: (config) => new CodexSecurity(config),
103
141
  environment: process.env,
@@ -220,13 +258,32 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
220
258
  windowsHide: true,
221
259
  });
222
260
  let requestedSignal = null;
261
+ let skillOutputLimitExceeded = false;
262
+ let forcedTermination;
263
+ let forceStatusCompletion = null;
264
+ let forceCaptureCompletion = null;
265
+ let invocationStatus;
266
+ const requestTermination = (signal) => {
267
+ requestedSignal = signal;
268
+ invocation.kill(signal);
269
+ if (forcedTermination !== undefined)
270
+ return;
271
+ forcedTermination = setTimeout(() => {
272
+ forcedTermination = undefined;
273
+ if (invocation.exitCode === null && invocation.signalCode === null) {
274
+ invocation.kill("SIGKILL");
275
+ }
276
+ forceCaptureCompletion?.();
277
+ invocation.stdout?.destroy();
278
+ invocation.stderr?.destroy();
279
+ forceStatusCompletion?.();
280
+ }, CHILD_TERMINATION_GRACE_MS);
281
+ };
223
282
  const onInterrupt = () => {
224
- requestedSignal = "SIGINT";
225
- invocation.kill("SIGINT");
283
+ requestTermination("SIGINT");
226
284
  };
227
285
  const onTerminate = () => {
228
- requestedSignal = "SIGTERM";
229
- invocation.kill("SIGTERM");
286
+ requestTermination("SIGTERM");
230
287
  };
231
288
  process.on("SIGINT", onInterrupt);
232
289
  process.on("SIGTERM", onTerminate);
@@ -237,20 +294,42 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
237
294
  });
238
295
  const captured = output === undefined || invocation.stdout === null
239
296
  ? Promise.resolve(undefined)
240
- : readSkillCommandOutput(invocation.stdout);
241
- const [status, events] = await Promise.all([
242
- new Promise((resolve, reject) => {
243
- invocation.once("error", reject);
244
- invocation.once(output === undefined ? "exit" : "close", (code, signal) => {
245
- resolve(requestedSignal === "SIGINT" || signal === "SIGINT"
246
- ? 130
247
- : requestedSignal === "SIGTERM" || signal === "SIGTERM"
248
- ? 143
249
- : code ?? 1);
250
- });
251
- }),
252
- captured,
253
- ]);
297
+ : Promise.race([
298
+ readSkillCommandOutput(invocation.stdout, () => {
299
+ skillOutputLimitExceeded = true;
300
+ requestTermination("SIGTERM");
301
+ }),
302
+ new Promise((resolve) => {
303
+ forceCaptureCompletion = () => resolve(undefined);
304
+ }),
305
+ ]);
306
+ invocationStatus = new Promise((resolve, reject) => {
307
+ let completed = false;
308
+ const complete = (code, signal) => {
309
+ if (completed)
310
+ return;
311
+ completed = true;
312
+ forceStatusCompletion = null;
313
+ resolve(requestedSignal === "SIGINT" || signal === "SIGINT"
314
+ ? 130
315
+ : requestedSignal === "SIGTERM" || signal === "SIGTERM"
316
+ ? 143
317
+ : code ?? 1);
318
+ };
319
+ forceStatusCompletion = () => complete(null, null);
320
+ invocation.once("error", (error) => {
321
+ if (completed)
322
+ return;
323
+ completed = true;
324
+ forceStatusCompletion = null;
325
+ reject(error);
326
+ });
327
+ invocation.once(output === undefined ? "exit" : "close", complete);
328
+ });
329
+ const [status, events] = await Promise.all([invocationStatus, captured]);
330
+ if (skillOutputLimitExceeded) {
331
+ throw new CodexSecurityError(SKILL_OUTPUT_LIMIT_MESSAGE);
332
+ }
254
333
  if (output === undefined || status === 130 || status === 143)
255
334
  return status;
256
335
  if (status !== 0) {
@@ -267,10 +346,15 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
267
346
  catch (error) {
268
347
  invocation.stdout?.destroy();
269
348
  invocation.stderr?.destroy();
270
- invocation.kill();
349
+ requestTermination("SIGTERM");
350
+ await invocationStatus?.catch(() => undefined);
271
351
  throw error;
272
352
  }
273
353
  finally {
354
+ if (forcedTermination !== undefined)
355
+ clearTimeout(forcedTermination);
356
+ forceStatusCompletion = null;
357
+ forceCaptureCompletion = null;
274
358
  process.off("SIGINT", onInterrupt);
275
359
  process.off("SIGTERM", onTerminate);
276
360
  }
@@ -358,14 +442,34 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
358
442
  let renderedHistory;
359
443
  const history = async (args, select = (value) => value) => {
360
444
  try {
361
- return select(await dependencies.runWorkbench(args));
445
+ return await select(await dependencies.runWorkbench(args));
362
446
  }
363
447
  catch (error) {
364
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
448
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
365
449
  exitCode = 2;
366
450
  return undefined;
367
451
  }
368
452
  };
453
+ const matchScanPair = async (beforeId, afterId, force = false) => history([
454
+ "compare-scans",
455
+ "--before-scan-id",
456
+ beforeId,
457
+ "--after-scan-id",
458
+ afterId,
459
+ "--include-matching-inputs",
460
+ ], async ({ matchingCached, matchingInputs, ...comparison }) => {
461
+ if (matchingCached && !force)
462
+ return comparison;
463
+ return await dependencies.runWorkbench([
464
+ "save-scan-comparison",
465
+ "--before-scan-id",
466
+ beforeId,
467
+ "--after-scan-id",
468
+ afterId,
469
+ "--matches-json",
470
+ JSON.stringify(await dependencies.matchFindings(matchingInputs)),
471
+ ]);
472
+ });
369
473
  const presentHistory = (result, command, format, settings = {}) => {
370
474
  if (result === undefined ||
371
475
  format !== "toon" ||
@@ -493,8 +597,14 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
493
597
  args: z.object({
494
598
  scanId: z.string().min(1).describe("Saved scan identifier."),
495
599
  }),
600
+ options: z.object({
601
+ verbose: z
602
+ .boolean()
603
+ .default(false)
604
+ .describe("Print scan diagnostics to stderr."),
605
+ }),
496
606
  output: z.record(z.string(), z.unknown()).optional(),
497
- async run({ args, error: incurError }) {
607
+ async run({ args, error: incurError, options }) {
498
608
  let scanArguments;
499
609
  try {
500
610
  const { recipe } = await dependencies.runWorkbench([
@@ -503,9 +613,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
503
613
  args.scanId,
504
614
  ]);
505
615
  scanArguments = scanArgumentsFromRecipe(recipe, args.scanId);
616
+ scanArguments.verbose = options.verbose;
506
617
  }
507
618
  catch (error) {
508
- const message = cliErrorMessage(error);
619
+ const message = redactedErrorMessage(error);
509
620
  errorOutput.write(`codex-security: ${message}\n`);
510
621
  exitCode = 2;
511
622
  return incurError({
@@ -558,40 +669,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
558
669
  if (options.all) {
559
670
  return presentHistory(await matchAllScans(dependencies, options.force), "match-all", format);
560
671
  }
561
- const comparison = await history([
562
- "compare-scans",
563
- "--before-scan-id",
564
- args.beforeId,
565
- "--after-scan-id",
566
- args.afterId,
567
- "--include-matching-inputs",
568
- ]);
569
- if (comparison === undefined)
570
- return undefined;
571
- const { matchingCached, matchingInputs, ...visibleComparison } = comparison;
572
- if (matchingCached && !options.force) {
573
- return presentHistory(visibleComparison, "compare", format);
574
- }
575
- const matching = await dependencies.matchFindings(matchingInputs);
576
- return presentHistory(await history([
577
- "save-scan-comparison",
578
- "--before-scan-id",
579
- args.beforeId,
580
- "--after-scan-id",
581
- args.afterId,
582
- "--matches-json",
583
- JSON.stringify(matching),
584
- ]), "compare", format);
672
+ return presentHistory(await matchScanPair(args.beforeId, args.afterId, options.force), "compare", format);
585
673
  }
586
674
  catch (error) {
587
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
675
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
588
676
  exitCode = 2;
589
677
  return undefined;
590
678
  }
591
679
  },
592
680
  })
593
681
  .command("compare", {
594
- description: "Compare findings and coverage using saved matches.",
682
+ description: "Match and compare findings and coverage between scans.",
683
+ destructive: true,
595
684
  mcp: false,
596
685
  args: z.object({
597
686
  beforeId: z.string().min(1).describe("Earlier saved scan identifier."),
@@ -599,14 +688,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
599
688
  }),
600
689
  output: z.record(z.string(), z.unknown()).optional(),
601
690
  async run({ args, format }) {
602
- return presentHistory(await history([
603
- "compare-scans",
604
- "--before-scan-id",
605
- args.beforeId,
606
- "--after-scan-id",
607
- args.afterId,
608
- "--require-matches",
609
- ]), "compare", format);
691
+ return presentHistory(await matchScanPair(args.beforeId, args.afterId), "compare", format);
610
692
  },
611
693
  });
612
694
  const cli = Cli.create("codex-security", {
@@ -633,6 +715,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
633
715
  .enum(["auto", "chatgpt", "api-key"])
634
716
  .default("auto")
635
717
  .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
718
+ verbose: z
719
+ .boolean()
720
+ .default(false)
721
+ .describe("Print redacted scan diagnostics to stderr."),
636
722
  path: z
637
723
  .array(optionValue("--path"))
638
724
  .default([])
@@ -658,10 +744,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
658
744
  .enum(["standard", "deep"])
659
745
  .default("standard")
660
746
  .describe("Scan mode; deep supports repository and path targets."),
747
+ ...DEEP_SCAN_OPTION_SCHEMAS,
661
748
  model: optionValue("--model")
662
749
  .optional()
663
750
  .describe(`OpenAI model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`),
664
751
  effort: effortOption(),
752
+ provider: PROVIDER_OPTION,
665
753
  outputDir: optionValue("--output-dir")
666
754
  .optional()
667
755
  .describe("Artifact directory outside the repository (default: Codex Security state; CODEX_SECURITY_STATE_DIR)."),
@@ -688,6 +776,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
688
776
  .positive()
689
777
  .optional()
690
778
  .describe("Stop the scan if estimated USD cost exceeds AMOUNT."),
779
+ headless: z
780
+ .boolean()
781
+ .default(false)
782
+ .describe("Use plain text progress instead of the interactive dashboard."),
691
783
  dryRun: z
692
784
  .boolean()
693
785
  .default(false)
@@ -703,7 +795,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
703
795
  .refine((options) => options.base === undefined || options.workingTree, {
704
796
  message: "--base requires --working-tree.",
705
797
  })
706
- .refine((options) => !options.archiveExisting || options.outputDir !== undefined, { message: "--archive-existing requires --output-dir." }),
798
+ .refine((options) => !options.archiveExisting || options.outputDir !== undefined, { message: "--archive-existing requires --output-dir." })
799
+ .refine((options) => options.mode === "deep" ||
800
+ (options.workers === undefined &&
801
+ options.subagents === undefined &&
802
+ options.stopAfterNoNew === undefined &&
803
+ options.maxDiscoveryRuns === undefined), { message: "Deep scan settings require --mode deep." }),
707
804
  examples: [
708
805
  { args: { repository: "." } },
709
806
  { args: { repository: "." }, options: { model: "gpt-5.6-terra" } },
@@ -731,6 +828,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
731
828
  }
732
829
  const outcome = await runScan({
733
830
  auth: options.auth,
831
+ verbose: options.verbose,
734
832
  repository: args.repository,
735
833
  paths: options.path,
736
834
  knowledgeBasePaths: options.knowledgeBase,
@@ -739,8 +837,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
739
837
  head: options.head,
740
838
  base: options.base,
741
839
  mode: options.mode,
840
+ workers: options.workers,
841
+ subagents: options.subagents,
842
+ stopAfterNoNew: options.stopAfterNoNew,
843
+ maxDiscoveryRuns: options.maxDiscoveryRuns,
742
844
  model: options.model,
743
845
  effort: options.effort,
846
+ provider: options.provider,
744
847
  outputDir: options.outputDir,
745
848
  archiveExisting: options.archiveExisting,
746
849
  pluginPath: options.pluginPath,
@@ -748,6 +851,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
748
851
  codex: options.codex,
749
852
  failOnSeverity: options.failOnSeverity,
750
853
  maxCostUsd: options.maxCost,
854
+ headless: options.headless,
751
855
  dryRun: options.dryRun,
752
856
  }, errorOutput, dependencies, format !== "json" && format !== "jsonl");
753
857
  exitCode = outcome.exitCode;
@@ -825,7 +929,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
825
929
  };
826
930
  }
827
931
  catch (error) {
828
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
932
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
829
933
  exitCode = 2;
830
934
  return undefined;
831
935
  }
@@ -850,6 +954,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
850
954
  .min(1, "--output-dir must not be empty.")
851
955
  .optional()
852
956
  .describe("Resumable results directory; required with a repository CSV."),
957
+ knowledgeBase: z
958
+ .array(optionValue("--knowledge-base"))
959
+ .default([])
960
+ .describe("Read shared security docs for every repository."),
853
961
  workers: z
854
962
  .number()
855
963
  .int()
@@ -864,6 +972,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
864
972
  .optional()
865
973
  .describe(`OpenAI model for each repository (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`),
866
974
  effort: effortOption(),
975
+ provider: PROVIDER_OPTION,
867
976
  maxAttempts: z
868
977
  .number()
869
978
  .int()
@@ -914,12 +1023,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
914
1023
  const argument = argv[optionIndex];
915
1024
  if (argument === "--model" ||
916
1025
  argument === "--effort" ||
917
- argument === "--codex") {
1026
+ argument === "--provider" ||
1027
+ argument === "--codex" ||
1028
+ argument === "--knowledge-base") {
918
1029
  optionIndex += 2;
919
1030
  }
920
1031
  else if (argument.startsWith("--model=") ||
921
1032
  argument.startsWith("--effort=") ||
922
- argument.startsWith("--codex=")) {
1033
+ argument.startsWith("--provider=") ||
1034
+ argument.startsWith("--codex=") ||
1035
+ argument.startsWith("--knowledge-base=")) {
923
1036
  optionIndex += 1;
924
1037
  }
925
1038
  else {
@@ -927,7 +1040,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
927
1040
  }
928
1041
  }
929
1042
  if (argv[0] !== "bulk-scan" || optionIndex !== argv.length) {
930
- throw new Error("Run 'codex-security bulk-scan [--model MODEL] [--effort EFFORT] [--codex KEY=VALUE]' to discover repositories, or provide a CSV and --output-dir.");
1043
+ throw new Error("Run 'codex-security bulk-scan [--provider PROVIDER] [--model MODEL] [--effort EFFORT] [--codex KEY=VALUE] [--knowledge-base PATH]' to discover repositories, or provide a CSV and --output-dir.");
931
1044
  }
932
1045
  const wizard = await runBulkScanWizard(dependencies.bulkScan ??
933
1046
  createBulkScanDiscoveryDependencies({
@@ -955,15 +1068,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
955
1068
  workers: options.workers,
956
1069
  mode: options.mode,
957
1070
  maxAttempts: options.maxAttempts,
1071
+ knowledgeBasePaths: options.knowledgeBase,
958
1072
  config: {
959
1073
  pluginPath: options.pluginPath,
960
1074
  pythonPath: options.python,
961
- codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort),
1075
+ codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider),
962
1076
  },
963
1077
  createSecurity: dependencies.createSecurity,
964
1078
  signal: controller.signal,
965
1079
  onProgress: ({ repository, status, attempt, error }) => {
966
- errorOutput.write(`codex-security: ${repository} ${status} (attempt ${attempt})${error === undefined ? "" : `: ${cliErrorMessage(error)}`}\n`);
1080
+ errorOutput.write(`codex-security: ${repository} ${status} (attempt ${attempt})${error === undefined ? "" : `: ${redactedErrorMessage(error)}`}\n`);
967
1081
  },
968
1082
  });
969
1083
  exitCode = interruptedExitCode() ?? (result.failed > 0 ? 2 : 0);
@@ -975,7 +1089,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
975
1089
  (error instanceof Error && error.name === "ExitPromptError"
976
1090
  ? 130
977
1091
  : 2);
978
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
1092
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
979
1093
  }
980
1094
  finally {
981
1095
  dependencies.removeSignalListener("SIGINT", onInterrupt);
@@ -1051,7 +1165,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1051
1165
  }
1052
1166
  catch (error) {
1053
1167
  exitCode = 2;
1054
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
1168
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
1055
1169
  }
1056
1170
  },
1057
1171
  })
@@ -1078,7 +1192,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1078
1192
  }
1079
1193
  catch (error) {
1080
1194
  exitCode = 2;
1081
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
1195
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
1082
1196
  }
1083
1197
  },
1084
1198
  })
@@ -1106,7 +1220,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1106
1220
  async run({ args, options }) {
1107
1221
  const credentialHome = dependencies.prepareAuthenticationHome !== undefined
1108
1222
  ? await dependencies.prepareAuthenticationHome(dependencies.environment)
1109
- : codexSecurityCredentialHome(dependencies.environment);
1223
+ : await prepareCodexSecurityCredentialHome(dependencies.environment);
1110
1224
  const authenticationEnvironment = {
1111
1225
  ...dependencies.environment,
1112
1226
  CODEX_HOME: credentialHome,
@@ -1161,7 +1275,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1161
1275
  async run() {
1162
1276
  const credentialHome = dependencies.prepareAuthenticationHome !== undefined
1163
1277
  ? await dependencies.prepareAuthenticationHome(dependencies.environment)
1164
- : codexSecurityCredentialHome(dependencies.environment);
1278
+ : await prepareCodexSecurityCredentialHome(dependencies.environment);
1165
1279
  const authenticationEnvironment = {
1166
1280
  ...dependencies.environment,
1167
1281
  CODEX_HOME: credentialHome,
@@ -1227,7 +1341,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1227
1341
  if (frameworkExit !== undefined) {
1228
1342
  if (exitCode !== 0)
1229
1343
  return exitCode;
1230
- errorOutput.write(`codex-security: ${cliErrorMessage(incurErrorMessage(frameworkOutput))}\n`);
1344
+ errorOutput.write(`codex-security: ${redactedErrorMessage(incurErrorMessage(frameworkOutput))}\n`);
1231
1345
  return 2;
1232
1346
  }
1233
1347
  if (frameworkOutput.length === 0)
@@ -1237,7 +1351,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1237
1351
  return exitCode;
1238
1352
  }
1239
1353
  catch (error) {
1240
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
1354
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
1241
1355
  return 2;
1242
1356
  }
1243
1357
  }
@@ -1321,6 +1435,18 @@ function scanArgumentsFromRecipe(recipe, parentScanId) {
1321
1435
  maxCostUsd <= 0)) {
1322
1436
  throw new CodexSecurityError("The saved scan recipe contains an invalid cost limit.");
1323
1437
  }
1438
+ const deepScan = z
1439
+ .object(DEEP_SCAN_OPTION_SCHEMAS)
1440
+ .optional()
1441
+ .safeParse(recipe["deepScan"]);
1442
+ if (!deepScan.success) {
1443
+ throw new CodexSecurityError("The saved scan recipe contains invalid deep scan settings.");
1444
+ }
1445
+ if (mode !== "deep" &&
1446
+ deepScan.data !== undefined &&
1447
+ Object.keys(deepScan.data).length > 0) {
1448
+ throw new CodexSecurityError("The saved scan recipe contains deep scan settings for a standard scan.");
1449
+ }
1324
1450
  return {
1325
1451
  repository,
1326
1452
  paths,
@@ -1330,6 +1456,7 @@ function scanArgumentsFromRecipe(recipe, parentScanId) {
1330
1456
  head: kind === "refs" ? head ?? "HEAD" : undefined,
1331
1457
  base: kind === "working_tree" ? reference : undefined,
1332
1458
  mode,
1459
+ ...deepScan.data,
1333
1460
  archiveExisting: false,
1334
1461
  codex: [],
1335
1462
  codexOverrides: config,
@@ -1629,24 +1756,33 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
1629
1756
  stderr,
1630
1757
  });
1631
1758
  }
1632
- export async function readSkillCommandOutput(stream) {
1759
+ export async function readSkillCommandOutput(stream, onLimitExceeded) {
1633
1760
  let message;
1634
1761
  let error;
1635
1762
  let malformed = false;
1636
- for await (const line of createInterface({ input: Readable.from(stream) })) {
1763
+ let exceeded = false;
1764
+ const markExceeded = () => {
1765
+ if (exceeded)
1766
+ return;
1767
+ exceeded = true;
1768
+ onLimitExceeded?.();
1769
+ };
1770
+ const readLine = (bytes) => {
1771
+ const content = bytes.at(-1) === 0x0d ? bytes.subarray(0, bytes.length - 1) : bytes;
1772
+ const line = content.toString("utf8");
1637
1773
  if (line.trim().length === 0)
1638
- continue;
1774
+ return;
1639
1775
  let event;
1640
1776
  try {
1641
1777
  event = JSON.parse(line);
1642
1778
  }
1643
1779
  catch {
1644
1780
  malformed = true;
1645
- continue;
1781
+ return;
1646
1782
  }
1647
1783
  if (typeof event !== "object" || event === null) {
1648
1784
  malformed = true;
1649
- continue;
1785
+ return;
1650
1786
  }
1651
1787
  const value = event;
1652
1788
  if (value["type"] === "item.completed") {
@@ -1657,7 +1793,12 @@ export async function readSkillCommandOutput(stream) {
1657
1793
  item.type === "agent_message" &&
1658
1794
  "text" in item &&
1659
1795
  typeof item.text === "string") {
1660
- message = item.text;
1796
+ if (Buffer.byteLength(item.text, "utf8") > MAX_SKILL_RESPONSE_BYTES) {
1797
+ markExceeded();
1798
+ }
1799
+ else {
1800
+ message = item.text;
1801
+ }
1661
1802
  }
1662
1803
  }
1663
1804
  else if (value["type"] === "turn.failed") {
@@ -1666,14 +1807,62 @@ export async function readSkillCommandOutput(stream) {
1666
1807
  detail !== null &&
1667
1808
  "message" in detail &&
1668
1809
  typeof detail.message === "string") {
1669
- error = detail.message;
1810
+ if (Buffer.byteLength(detail.message, "utf8") > MAX_SKILL_RESPONSE_BYTES) {
1811
+ markExceeded();
1812
+ }
1813
+ else {
1814
+ error = detail.message;
1815
+ }
1670
1816
  }
1671
1817
  }
1672
1818
  else if (value["type"] === "error" &&
1673
1819
  typeof value["message"] === "string") {
1674
- error = value["message"];
1820
+ if (Buffer.byteLength(value["message"], "utf8") > MAX_SKILL_RESPONSE_BYTES) {
1821
+ markExceeded();
1822
+ }
1823
+ else {
1824
+ error = value["message"];
1825
+ }
1675
1826
  }
1827
+ };
1828
+ const pending = Buffer.alloc(MAX_SKILL_EVENT_BYTES);
1829
+ let pendingBytes = 0;
1830
+ let discardingOversizedLine = false;
1831
+ for await (const rawChunk of stream) {
1832
+ const chunk = Buffer.isBuffer(rawChunk)
1833
+ ? rawChunk
1834
+ : Buffer.from(rawChunk, "utf8");
1835
+ let start = 0;
1836
+ while (start < chunk.length) {
1837
+ const newline = chunk.indexOf(0x0a, start);
1838
+ const end = newline === -1 ? chunk.length : newline;
1839
+ const segment = chunk.subarray(start, end);
1840
+ if (!discardingOversizedLine) {
1841
+ if (pendingBytes + segment.length > MAX_SKILL_EVENT_BYTES) {
1842
+ markExceeded();
1843
+ discardingOversizedLine = true;
1844
+ pendingBytes = 0;
1845
+ }
1846
+ else if (segment.length > 0) {
1847
+ segment.copy(pending, pendingBytes);
1848
+ pendingBytes += segment.length;
1849
+ }
1850
+ }
1851
+ if (newline === -1)
1852
+ break;
1853
+ if (!discardingOversizedLine) {
1854
+ readLine(pending.subarray(0, pendingBytes));
1855
+ }
1856
+ pendingBytes = 0;
1857
+ discardingOversizedLine = false;
1858
+ start = newline + 1;
1859
+ }
1860
+ }
1861
+ if (!discardingOversizedLine && pendingBytes > 0) {
1862
+ readLine(pending.subarray(0, pendingBytes));
1676
1863
  }
1864
+ if (exceeded)
1865
+ throw new CodexSecurityError(SKILL_OUTPUT_LIMIT_MESSAGE);
1677
1866
  return {
1678
1867
  ...(message === undefined ? {} : { message }),
1679
1868
  ...(error === undefined ? {} : { error }),
@@ -1759,17 +1948,51 @@ async function runExport(arguments_, output, errorOutput, dependencies) {
1759
1948
  return 0;
1760
1949
  }
1761
1950
  catch (error) {
1762
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
1951
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
1763
1952
  return 2;
1764
1953
  }
1765
1954
  }
1955
+ function sanitizeDiagnosticValue(value) {
1956
+ return redactedErrorMessage(value)
1957
+ .replaceAll(/(\b(?:tenant(?:[_-]?id)?|org(?:anization)?(?:[_-]?id)?|project(?:[_-]?id)?|(?:x[_-]?)?(?:request|trace|correlation)[_-]?id)\b(?:\\*["'])?\s*[:=]\s*)(?!\[redacted\])(?:(\\*)(['"])(?:(?!(?<!\\)\2\3)(?:\\.|[^\\]))*(?:(?<!\\)\2\3|$)|[^\s"',;&}\]]+)/giu, "$1$2$3[redacted]$2$3")
1958
+ .replaceAll(/[\u0000-\u001F\u007F\u0085\u2028\u2029]/gu, " ");
1959
+ }
1766
1960
  async function runScan(arguments_, errorOutput, dependencies, interactive = true) {
1767
1961
  let scanDir = null;
1768
1962
  let requestedSignal = null;
1769
1963
  let firstSignalAt = 0;
1770
1964
  let progress = null;
1965
+ let dashboard = null;
1771
1966
  let lastWorkerUpdate = "";
1967
+ let lastProgressUpdate = "";
1968
+ let workerCapacity = null;
1969
+ let fileProgress = null;
1970
+ let runningCost = null;
1772
1971
  let phase = null;
1972
+ const targetWarnings = [];
1973
+ const configuredLogLevel = dependencies.environment["CODEX_SECURITY_LOG_LEVEL"]?.trim() ||
1974
+ dependencies.environment["LOG_LEVEL"]?.trim();
1975
+ const verbose = arguments_.verbose === true ||
1976
+ configuredLogLevel?.toLowerCase() === "debug";
1977
+ const writeAboveProgress = (write) => {
1978
+ if (progress === null) {
1979
+ write();
1980
+ return;
1981
+ }
1982
+ progress.writeAboveTimer(write);
1983
+ };
1984
+ const diagnostic = (event, fields = {}) => {
1985
+ if (!verbose)
1986
+ return;
1987
+ const attributes = Object.entries(fields).flatMap(([name, value]) => value === undefined
1988
+ ? []
1989
+ : [
1990
+ `${name}=${JSON.stringify(typeof value === "string" ? sanitizeDiagnosticValue(value) : value)}`,
1991
+ ]);
1992
+ writeAboveProgress(() => {
1993
+ errorOutput.write(`codex-security: debug: ${event}${attributes.length === 0 ? "" : ` ${attributes.join(" ")}`}\n`);
1994
+ });
1995
+ };
1773
1996
  const preparationAbortController = new AbortController();
1774
1997
  const signalListener = (signal) => () => {
1775
1998
  if (requestedSignal !== null) {
@@ -1780,6 +2003,7 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1780
2003
  return;
1781
2004
  }
1782
2005
  requestedSignal = signal;
2006
+ dashboard?.stop();
1783
2007
  progress?.stopTimer();
1784
2008
  if (progress?.interactive === true) {
1785
2009
  try {
@@ -1808,6 +2032,8 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1808
2032
  let security = null;
1809
2033
  let result = null;
1810
2034
  let preflight = null;
2035
+ let effectiveModel = DEFAULT_SCAN_MODEL_CONFIGURATION.model;
2036
+ let effectiveReasoningEffort = DEFAULT_SCAN_MODEL_CONFIGURATION.reasoningEffort;
1811
2037
  let selectedAuthentication = null;
1812
2038
  let failed = false;
1813
2039
  let failure;
@@ -1818,11 +2044,19 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1818
2044
  pluginPath: arguments_.pluginPath,
1819
2045
  pythonPath: arguments_.pythonPath,
1820
2046
  codexOverrides: arguments_.codexOverrides ??
1821
- parseCodexOverrides(arguments_.codex, arguments_.model, arguments_.effort),
2047
+ parseCodexOverrides(arguments_.codex, arguments_.model, arguments_.effort, arguments_.provider),
1822
2048
  };
2049
+ const selectedProfileName = config.codexOverrides?.["profile"];
2050
+ ({ model: effectiveModel, reasoningEffort: effectiveReasoningEffort } =
2051
+ scanModelConfiguration({
2052
+ ...DEFAULT_CODEX_CONFIG,
2053
+ ...config.codexOverrides,
2054
+ }));
1823
2055
  let auth = arguments_.auth;
1824
- selectedAuthentication = scanAuthentication(dependencies.environment, auth);
1825
- if ((auth === undefined || auth === "auto") &&
2056
+ const provider = config.codexOverrides?.["model_provider"];
2057
+ selectedAuthentication = scanAuthentication(dependencies.environment, auth, provider);
2058
+ if (!isExternalModelProvider(provider) &&
2059
+ (auth === undefined || auth === "auto") &&
1826
2060
  !arguments_.dryRun &&
1827
2061
  interactive &&
1828
2062
  errorOutput.isTTY === true &&
@@ -1841,23 +2075,91 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1841
2075
  { label: "ChatGPT subscription", value: "chatgpt" },
1842
2076
  { label: `API key from ${source}`, value: "api-key" },
1843
2077
  ]);
1844
- selectedAuthentication = scanAuthentication(dependencies.environment, auth);
2078
+ selectedAuthentication = scanAuthentication(dependencies.environment, auth, provider);
1845
2079
  }
1846
2080
  }
1847
- progress = new Progress(errorOutput, dependencies, interactive);
2081
+ diagnostic("scan.configuration", {
2082
+ cli_version: VERSION,
2083
+ bundled_plugin_version: BUNDLED_PLUGIN_VERSION,
2084
+ codex_version: CODEX_EXECUTABLE_VERSION,
2085
+ codex_sdk_version: CODEX_SDK_VERSION,
2086
+ mode: arguments_.mode,
2087
+ max_cost_usd: arguments_.maxCostUsd,
2088
+ target: arguments_.paths.length > 0
2089
+ ? "paths"
2090
+ : arguments_.diff !== undefined
2091
+ ? "diff"
2092
+ : arguments_.workingTree
2093
+ ? "working_tree"
2094
+ : "repository",
2095
+ requested_auth: auth ?? "auto",
2096
+ dry_run: arguments_.dryRun,
2097
+ profile: typeof selectedProfileName === "string"
2098
+ ? selectedProfileName
2099
+ : undefined,
2100
+ model: effectiveModel,
2101
+ reasoning_effort: effectiveReasoningEffort,
2102
+ });
2103
+ progress = new Progress(errorOutput, dependencies, interactive &&
2104
+ !arguments_.headless &&
2105
+ dependencies.environment["CI"] === undefined &&
2106
+ dependencies.environment["TERM"] !== "dumb");
2107
+ if (progress.interactive && !arguments_.dryRun && !verbose) {
2108
+ dashboard = new ScanDashboard(errorOutput, {
2109
+ repository,
2110
+ model: scanModelConfiguration(await mergedCodexConfig(config)),
2111
+ ...(arguments_.maxCostUsd === undefined
2112
+ ? {}
2113
+ : { maxCostUsd: arguments_.maxCostUsd }),
2114
+ clock: dependencies,
2115
+ color: dependencies.environment["NO_COLOR"] === undefined,
2116
+ sanitize: redactedErrorMessage,
2117
+ input: process.stdin,
2118
+ onInterrupt,
2119
+ });
2120
+ }
1848
2121
  const scope = scanScope(arguments_);
1849
- const runningMessage = () => phase === null
1850
- ? scope === null
1851
- ? "Running scan"
1852
- : `Running scan: ${scope}`
1853
- : `Running scan: ${phase}${scope === null ? "" : ` (${scope})`}`;
1854
- progress.startTimer(arguments_.dryRun ? "Validating scan inputs" : "Preparing scan");
2122
+ const runningMessage = () => {
2123
+ const stage = phase === null
2124
+ ? scope === null
2125
+ ? "Running scan"
2126
+ : `Running scan: ${scope}`
2127
+ : `Running scan: ${phase}${scope === null ? "" : ` (${scope})`}`;
2128
+ const details = [];
2129
+ if (workerCapacity !== null) {
2130
+ details.push(`Workers: ${workerCapacity.started}/${workerCapacity.planned}`);
2131
+ }
2132
+ if (fileProgress !== null && fileProgress.filesTotal > 0) {
2133
+ details.push(`Files: ${fileProgress.filesCompleted.toLocaleString("en-US")}/${fileProgress.filesTotal.toLocaleString("en-US")}`);
2134
+ }
2135
+ if (runningCost !== null) {
2136
+ const tokens = formatTokenUsage({
2137
+ input_tokens: runningCost.inputTokens,
2138
+ cached_input_tokens: runningCost.cachedInputTokens,
2139
+ output_tokens: runningCost.outputTokens,
2140
+ });
2141
+ if (tokens !== null)
2142
+ details.push(`Tokens: ${tokens}`);
2143
+ details.push(`Cost: ${formatUsd(runningCost.estimatedUsd)}`);
2144
+ }
2145
+ return details.length === 0 ? stage : `${stage} | ${details.join(" | ")}`;
2146
+ };
2147
+ if (dashboard === null) {
2148
+ progress.startTimer(arguments_.dryRun ? "Validating scan inputs" : "Preparing scan");
2149
+ }
2150
+ else {
2151
+ dashboard.start();
2152
+ }
1855
2153
  security = dependencies.createSecurity(config);
1856
2154
  const options = {
1857
2155
  auth,
1858
2156
  target,
1859
2157
  knowledgeBasePaths: arguments_.knowledgeBasePaths,
1860
2158
  mode: arguments_.mode,
2159
+ workers: arguments_.workers,
2160
+ subagents: arguments_.subagents,
2161
+ stopAfterNoNew: arguments_.stopAfterNoNew,
2162
+ maxDiscoveryRuns: arguments_.maxDiscoveryRuns,
1861
2163
  outputDir: arguments_.outputDir,
1862
2164
  archiveExisting: arguments_.archiveExisting,
1863
2165
  parentScanId: arguments_.parentScanId,
@@ -1865,24 +2167,67 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1865
2167
  failureSeverity: arguments_.failOnSeverity,
1866
2168
  maxCostUsd: arguments_.maxCostUsd,
1867
2169
  onCost: (cost) => {
1868
- if (arguments_.maxCostUsd === undefined)
2170
+ diagnostic("cost.updated", {
2171
+ model: cost.model,
2172
+ estimated_usd: cost.estimatedUsd,
2173
+ input_tokens: cost.inputTokens,
2174
+ cached_input_tokens: cost.cachedInputTokens,
2175
+ cache_write_input_tokens: cost.cacheWriteInputTokens,
2176
+ output_tokens: cost.outputTokens,
2177
+ max_cost_usd: arguments_.maxCostUsd,
2178
+ });
2179
+ runningCost = cost;
2180
+ if (dashboard !== null) {
2181
+ dashboard.setCost(cost);
1869
2182
  return;
2183
+ }
1870
2184
  progress?.stopTimer();
1871
- progress?.stage(`Estimated cost: ${formatUsd(cost.estimatedUsd)} of ${formatUsd(arguments_.maxCostUsd)} limit`);
1872
- if (cost.estimatedUsd <= arguments_.maxCostUsd) {
2185
+ if (arguments_.maxCostUsd === undefined) {
2186
+ const tokens = formatTokenUsage({
2187
+ input_tokens: cost.inputTokens,
2188
+ cached_input_tokens: cost.cachedInputTokens,
2189
+ output_tokens: cost.outputTokens,
2190
+ });
2191
+ progress?.stage(`${tokens === null ? "" : `Tokens: ${tokens}. `}Estimated cost: ${formatUsd(cost.estimatedUsd)} USD.`);
2192
+ }
2193
+ else {
2194
+ progress?.stage(`Estimated cost: ${formatUsd(cost.estimatedUsd)} of ${formatUsd(arguments_.maxCostUsd)} limit`);
2195
+ }
2196
+ if (arguments_.maxCostUsd === undefined ||
2197
+ cost.estimatedUsd <= arguments_.maxCostUsd) {
1873
2198
  progress?.startTimer(runningMessage());
1874
2199
  }
1875
2200
  },
1876
2201
  onOutputArchived: (archiveDir) => {
2202
+ diagnostic("scan.output_archived", { archive_dir: archiveDir });
2203
+ if (dashboard !== null) {
2204
+ dashboard.note(`Moved existing results to: ${redactedErrorMessage(archiveDir)}`);
2205
+ return;
2206
+ }
1877
2207
  progress?.stopTimer();
1878
- errorOutput.write(`Moved existing results to: ${cliErrorMessage(archiveDir)}\n`);
2208
+ errorOutput.write(`Moved existing results to: ${redactedErrorMessage(archiveDir)}\n`);
1879
2209
  },
1880
2210
  signal: preparationAbortController.signal,
1881
2211
  onOutputDirReady: (path) => {
1882
2212
  scanDir = path;
2213
+ diagnostic("scan.output_ready", { scan_dir: path });
1883
2214
  },
1884
2215
  onAuthentication: (authentication) => {
1885
2216
  selectedAuthentication = authentication;
2217
+ diagnostic("authentication.selected", {
2218
+ requested: auth ?? "auto",
2219
+ method: authentication.method,
2220
+ source: authentication.method === "api_key"
2221
+ ? authentication.source
2222
+ : undefined,
2223
+ verified: authentication.verified,
2224
+ });
2225
+ if (dashboard !== null) {
2226
+ dashboard.note(authentication.method === "api_key"
2227
+ ? `Using API key from ${authentication.source}`
2228
+ : "Using stored Codex credentials");
2229
+ return;
2230
+ }
1886
2231
  progress?.stopTimer();
1887
2232
  if (authentication.method === "api_key") {
1888
2233
  progress?.stage(`Authentication: API key from ${authentication.source}.`);
@@ -1893,11 +2238,27 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1893
2238
  }
1894
2239
  progress?.startTimer("Preparing scan");
1895
2240
  },
2241
+ onTrustedAccessStatus: (status) => {
2242
+ if (status === "granted") {
2243
+ errorOutput.write("codex-security: ✓ Your account has Trusted Access for Cyber.\n");
2244
+ }
2245
+ },
1896
2246
  onScanStarted: () => {
2247
+ diagnostic("scan.started");
2248
+ if (dashboard !== null) {
2249
+ dashboard.setStage(phase ?? "Scanning repository");
2250
+ return;
2251
+ }
1897
2252
  progress?.stopTimer();
1898
2253
  progress?.startTimer(runningMessage());
1899
2254
  },
1900
2255
  onReconnect: (attempt, maxAttempts, details) => {
2256
+ diagnostic("connection.retry", {
2257
+ reason: details?.reason ?? "unknown",
2258
+ attempt,
2259
+ max_attempts: maxAttempts,
2260
+ retry_after_seconds: details?.retryAfterSeconds,
2261
+ });
1901
2262
  progress?.stopTimer();
1902
2263
  const message = details?.reason === "rate_limit"
1903
2264
  ? `Rate limit reached; retrying${details.retryAfterSeconds === undefined
@@ -1910,9 +2271,42 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1910
2271
  : details?.reason === "authorization"
1911
2272
  ? `Model access interrupted; retrying (${attempt}/${maxAttempts}).`
1912
2273
  : `Codex connection interrupted; retrying (${attempt}/${maxAttempts})`;
2274
+ if (dashboard !== null) {
2275
+ dashboard.note(message);
2276
+ return;
2277
+ }
1913
2278
  progress?.stage(message);
1914
2279
  progress?.startTimer(runningMessage());
1915
2280
  },
2281
+ onActivity: (activity) => {
2282
+ if (dashboard === null)
2283
+ return;
2284
+ dashboard.record(activity);
2285
+ if (activity.paths.length > 0 && phase === "preflight") {
2286
+ dashboard.setStage("inspecting repository files");
2287
+ }
2288
+ },
2289
+ onProgress: (update) => {
2290
+ const key = `${update.phase}:${update.filesCompleted}:${update.filesTotal}`;
2291
+ if (key === lastProgressUpdate)
2292
+ return;
2293
+ lastProgressUpdate = key;
2294
+ fileProgress = update;
2295
+ const previousPhase = phase;
2296
+ phase = scanPhase(update.phase);
2297
+ if (dashboard !== null) {
2298
+ dashboard.setFiles(update);
2299
+ dashboard.setStage(phase);
2300
+ if (previousPhase !== phase)
2301
+ dashboard.note(`Started ${phase}`);
2302
+ return;
2303
+ }
2304
+ if (progress === null)
2305
+ return;
2306
+ progress.stopTimer();
2307
+ progress.stage(`Scan phase: ${phase}${update.filesTotal === 0 ? "" : ` (${update.filesCompleted.toLocaleString("en-US")}/${update.filesTotal.toLocaleString("en-US")} files)`}.`);
2308
+ progress.startTimer(runningMessage());
2309
+ },
1916
2310
  onWorkerStatus: (status) => {
1917
2311
  const update = status.kind === "preflight"
1918
2312
  ? `preflight:${status.delegation}:${status.configuredSlots}`
@@ -1920,20 +2314,60 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1920
2314
  if (update === lastWorkerUpdate)
1921
2315
  return;
1922
2316
  lastWorkerUpdate = update;
1923
- if (status.kind === "dispatch")
2317
+ if (status.kind === "preflight") {
2318
+ diagnostic("worker.preflight", {
2319
+ delegation: status.delegation,
2320
+ configured_slots: status.configuredSlots,
2321
+ });
2322
+ }
2323
+ else {
2324
+ diagnostic("worker.phase", {
2325
+ phase: status.phase,
2326
+ planned: status.planned,
2327
+ started: status.started,
2328
+ });
2329
+ workerCapacity = { planned: status.planned, started: status.started };
1924
2330
  phase = scanPhase(status.phase);
2331
+ }
1925
2332
  const message = workerStatusMessage(status);
2333
+ if (dashboard !== null) {
2334
+ if (status.kind === "dispatch") {
2335
+ dashboard.setStage(scanPhase(status.phase));
2336
+ }
2337
+ if (message !== null)
2338
+ dashboard.note(message);
2339
+ return;
2340
+ }
1926
2341
  if (message === null || progress === null)
1927
2342
  return;
1928
2343
  progress.stopTimer();
1929
2344
  progress.stage(message);
1930
2345
  progress.startTimer(runningMessage());
1931
2346
  },
1932
- onWarning: (warning) => {
1933
- errorOutput.write(`codex-security: warning: ${cliErrorMessage(warning)}\n`);
2347
+ onWarning: (warning, details) => {
2348
+ const message = sanitizeDiagnosticValue(warning);
2349
+ if (details?.kind === "target_changed") {
2350
+ targetWarnings.push(message);
2351
+ }
2352
+ writeAboveProgress(() => {
2353
+ diagnostic("scan.warning", { message });
2354
+ errorOutput.write(`codex-security: warning: ${message}\n`);
2355
+ });
1934
2356
  },
1935
2357
  onObserverError: (observer, error) => {
1936
- errorOutput.write(`codex-security: warning: ${observer} observer failed: ${cliErrorMessage(error)}\n`);
2358
+ diagnostic("scan.observer_failed", {
2359
+ observer,
2360
+ classification: classifyConnectionFailure(error),
2361
+ });
2362
+ const warning = `${observer} observer failed: ${sanitizeDiagnosticValue(error)}`;
2363
+ if (dashboard === null) {
2364
+ writeAboveProgress(() => {
2365
+ errorOutput.write(`codex-security: warning: ${warning}\n`);
2366
+ });
2367
+ }
2368
+ else {
2369
+ dashboard.note(`Warning: ${warning}`);
2370
+ }
1937
2371
  },
1938
2372
  };
1939
2373
  if (arguments_.dryRun) {
@@ -1943,23 +2377,33 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1943
2377
  result = await security.run(repository, options);
1944
2378
  scanDir = result.scanDir;
1945
2379
  }
1946
- progress.stopTimer();
1947
2380
  }
1948
2381
  catch (error) {
1949
2382
  failed = true;
1950
2383
  failure = error;
1951
2384
  }
1952
2385
  finally {
2386
+ dashboard?.stop();
1953
2387
  progress?.stopTimer();
1954
- await security?.close().catch((error) => {
1955
- if (!failed) {
1956
- failed = true;
1957
- failure = error;
1958
- }
1959
- });
2388
+ if (security !== null) {
2389
+ diagnostic("runtime.cleanup.started");
2390
+ await security.close().then(() => diagnostic("runtime.cleanup.completed"), (error) => {
2391
+ diagnostic("runtime.cleanup.failed", {
2392
+ classification: classifyConnectionFailure(error),
2393
+ });
2394
+ if (!failed) {
2395
+ failed = true;
2396
+ failure = error;
2397
+ }
2398
+ });
2399
+ }
1960
2400
  removeSignalListeners();
1961
2401
  }
1962
2402
  if (requestedSignal !== null) {
2403
+ diagnostic("scan.interrupted", {
2404
+ signal: requestedSignal,
2405
+ partial_output: scanDir !== null,
2406
+ });
1963
2407
  return {
1964
2408
  exitCode: interruptedExit(requestedSignal, scanDir, errorOutput),
1965
2409
  error: requestedSignal === "SIGINT"
@@ -1968,29 +2412,53 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1968
2412
  };
1969
2413
  }
1970
2414
  if (failed) {
2415
+ const costLimitFailure = failure instanceof ScanCostLimitExceededError ? failure : undefined;
1971
2416
  const message = failure instanceof OutputInsideProtectedRootError
1972
- ? cliErrorMessage(protectedRootErrorMessage(failure))
2417
+ ? redactedErrorMessage(protectedRootErrorMessage(failure))
1973
2418
  : scanFailureMessage(failure, selectedAuthentication);
1974
- if (failure instanceof OutputInsideProtectedRootError) {
1975
- errorOutput.write(`${message}\n`);
1976
- }
1977
- else {
1978
- errorOutput.write(`codex-security: ${message}\n`);
1979
- }
2419
+ diagnostic("scan.failed", {
2420
+ classification: costLimitFailure !== undefined
2421
+ ? "cost_limit_exceeded"
2422
+ : isLocalScanFailure(failure)
2423
+ ? "local"
2424
+ : classifyConnectionFailure(failure),
2425
+ partial_output: scanDir !== null,
2426
+ max_cost_usd: costLimitFailure?.maxCostUsd,
2427
+ estimated_usd: costLimitFailure?.cost.estimatedUsd,
2428
+ });
2429
+ errorOutput.write(`${message}\n`);
1980
2430
  if (failure instanceof ScanInterruptedError) {
1981
2431
  return { exitCode: 2, error: message };
1982
2432
  }
1983
2433
  if (scanDir !== null) {
1984
- errorOutput.write(`codex-security: Partial output was kept at ${cliErrorMessage(scanDir)}.\n`);
2434
+ errorOutput.write(`Partial output was kept at ${redactedErrorMessage(scanDir)}.\n`);
1985
2435
  }
1986
2436
  return { exitCode: 2, error: message };
1987
2437
  }
1988
2438
  if (preflight !== null) {
2439
+ const effectivePreflight = {
2440
+ ...preflight,
2441
+ model: effectiveModel,
2442
+ reasoningEffort: effectiveReasoningEffort,
2443
+ };
1989
2444
  progress?.stage("Preflight complete");
1990
- return { exitCode: 0, data: { dryRun: true, ...preflight } };
2445
+ diagnostic("scan.preflight.completed", {
2446
+ model: effectivePreflight.model,
2447
+ reasoning_effort: effectivePreflight.reasoningEffort,
2448
+ method: effectivePreflight.authentication.method,
2449
+ source: effectivePreflight.authentication.method === "api_key"
2450
+ ? effectivePreflight.authentication.source
2451
+ : undefined,
2452
+ verified: effectivePreflight.authentication.verified,
2453
+ });
2454
+ return { exitCode: 0, data: { dryRun: true, ...effectivePreflight } };
1991
2455
  }
1992
2456
  if (result === null) {
1993
- errorOutput.write("codex-security: scan completed without a result\n");
2457
+ diagnostic("scan.failed", {
2458
+ classification: "unknown",
2459
+ message: "Scan completed without a result.",
2460
+ });
2461
+ errorOutput.write("scan completed without a result\n");
1994
2462
  return { exitCode: 2, error: "Scan completed without a result." };
1995
2463
  }
1996
2464
  const threshold = arguments_.failOnSeverity;
@@ -1998,18 +2466,80 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1998
2466
  ? []
1999
2467
  : REPORTABLE_SEVERITIES.slice(0, REPORTABLE_SEVERITIES.indexOf(threshold) + 1));
2000
2468
  const blockingCount = result.findings.findings.filter(({ severity }) => blockingSeverities.has(severity.level)).length;
2469
+ const scanData = targetWarnings.length === 0
2470
+ ? result.toJSON()
2471
+ : { ...result.toJSON(), warnings: targetWarnings };
2001
2472
  const incomplete = result.coverage.completeness !== "complete";
2002
- progress?.stage("Scan complete");
2003
- printScanSummary(result, progress, errorOutput);
2473
+ progress?.stage(`Scan complete · ${result.manifest.scan.id.slice(0, 8)}`);
2474
+ printScanSummary(result, progress, errorOutput, progress?.interactive === true &&
2475
+ dependencies.environment["NO_COLOR"] === undefined &&
2476
+ dependencies.environment["TERM"] !== "dumb");
2477
+ diagnostic("scan.completed", {
2478
+ coverage: result.coverage.completeness,
2479
+ findings: result.findings.findings.length,
2480
+ scan_id: result.manifest.scan.id,
2481
+ estimated_usd: result.cost?.estimatedUsd,
2482
+ exit_code: targetWarnings.length > 0 || incomplete ? 2 : blockingCount > 0 ? 1 : 0,
2483
+ });
2484
+ if (targetWarnings.length > 0) {
2485
+ errorOutput.write("codex-security: Scan target changed during execution; results do not represent the current checkout.\n");
2486
+ return { exitCode: 2, data: scanData };
2487
+ }
2004
2488
  if (incomplete) {
2005
2489
  errorOutput.write(threshold === undefined
2006
2490
  ? `codex-security: Scan coverage is ${result.coverage.completeness}; results may be incomplete.\n`
2007
2491
  : `codex-security: Cannot evaluate the failure policy: coverage is ${result.coverage.completeness}.\n`);
2008
- return { exitCode: 2, data: result.toJSON() };
2492
+ return { exitCode: 2, data: scanData };
2493
+ }
2494
+ return { exitCode: blockingCount > 0 ? 1 : 0, data: scanData };
2495
+ }
2496
+ // Filesystem and OS syscall failures cannot originate from the model transport,
2497
+ // so they must never be rewritten as connectivity or credential advice. Network
2498
+ // errno codes are deliberately absent: they are genuine transport failures.
2499
+ const LOCAL_SYSCALL_CODES = new Set([
2500
+ "EACCES",
2501
+ "EBUSY",
2502
+ "EEXIST",
2503
+ "EFBIG",
2504
+ "EIO",
2505
+ "EISDIR",
2506
+ "ELOOP",
2507
+ "EMFILE",
2508
+ "ENAMETOOLONG",
2509
+ "ENFILE",
2510
+ "ENOENT",
2511
+ "ENOMEM",
2512
+ "ENOSPC",
2513
+ "ENOTDIR",
2514
+ "ENOTEMPTY",
2515
+ "EPERM",
2516
+ "EROFS",
2517
+ "EXDEV",
2518
+ ]);
2519
+ function isLocalScanFailure(error) {
2520
+ if (error instanceof InvalidTargetError ||
2521
+ error instanceof OutputDirectoryError ||
2522
+ error instanceof ConfigurationError ||
2523
+ error instanceof PluginPythonUnavailableError) {
2524
+ return true;
2009
2525
  }
2010
- return { exitCode: blockingCount > 0 ? 1 : 0, data: result.toJSON() };
2526
+ return (typeof error === "object" &&
2527
+ error !== null &&
2528
+ "code" in error &&
2529
+ typeof error.code === "string" &&
2530
+ LOCAL_SYSCALL_CODES.has(error.code));
2011
2531
  }
2012
2532
  function scanFailureMessage(error, authentication) {
2533
+ // A local failure keeps its own message. Classification matches bare words
2534
+ // such as "permission denied" anywhere in the text, so an EACCES from a
2535
+ // read-only TMPDIR would otherwise be reported as a credential problem.
2536
+ //
2537
+ // The advice branches below still replace the underlying text rather than
2538
+ // appending it. That is deliberate: upstream authentication and authorization
2539
+ // errors can name the organization or project, which must not reach stderr or
2540
+ // the JSON error field.
2541
+ if (isLocalScanFailure(error))
2542
+ return sanitizeDiagnosticValue(error);
2013
2543
  switch (classifyConnectionFailure(error)) {
2014
2544
  case "unauthorized":
2015
2545
  return authentication?.method === "api_key"
@@ -2029,7 +2559,7 @@ function scanFailureMessage(error, authentication) {
2029
2559
  case "network_error":
2030
2560
  case "timeout":
2031
2561
  case "unknown":
2032
- return cliErrorMessage(error);
2562
+ return sanitizeDiagnosticValue(error);
2033
2563
  }
2034
2564
  }
2035
2565
  function scanScope(arguments_) {
@@ -2041,7 +2571,7 @@ function scanScope(arguments_) {
2041
2571
  portable.startsWith("//")
2042
2572
  ? portable.split("/").at(-1) ?? portable
2043
2573
  : portable;
2044
- return cliErrorMessage(scoped.replaceAll(/[\u0000-\u001F\u007F]/gu, " "));
2574
+ return redactedErrorMessage(scoped.replaceAll(/[\u0000-\u001F\u007F]/gu, " "));
2045
2575
  });
2046
2576
  return `${displayed.join(", ")}${arguments_.paths.length > displayed.length ? `, +${arguments_.paths.length - displayed.length} more` : ""}`;
2047
2577
  }
@@ -2053,13 +2583,18 @@ function scanScope(arguments_) {
2053
2583
  }
2054
2584
  function scanPhase(value) {
2055
2585
  return {
2586
+ preflight: "preflight",
2587
+ threat_model: "building threat model",
2588
+ discovery: "reviewing files",
2056
2589
  ranking: "ranking scan targets",
2057
2590
  file_review: "reviewing files",
2058
2591
  validation: "validating findings",
2059
2592
  attack_path: "analyzing attack paths",
2593
+ reporting: "writing report",
2060
2594
  }[value];
2061
2595
  }
2062
- function printScanSummary(result, progress, errorOutput) {
2596
+ function printScanSummary(result, progress, errorOutput, color) {
2597
+ const paint = (value, code) => color ? `\u001B[${code}m${value}\u001B[0m` : value;
2063
2598
  const severities = new Map();
2064
2599
  for (const finding of result.findings.findings) {
2065
2600
  severities.set(finding.severity.level, (severities.get(finding.severity.level) ?? 0) + 1);
@@ -2070,7 +2605,6 @@ function printScanSummary(result, progress, errorOutput) {
2070
2605
  })
2071
2606
  .filter((value) => value !== null)
2072
2607
  .join(", ");
2073
- errorOutput.write(`codex-security: Findings: ${result.findings.findings.length}${severitySummary === "" ? "" : ` (${severitySummary})`}. Coverage: ${result.coverage.completeness}.\n`);
2074
2608
  const started = Date.parse(result.manifest.scan.startedAt);
2075
2609
  const completed = Date.parse(result.manifest.scan.completedAt);
2076
2610
  const elapsed = Number.isFinite(started) &&
@@ -2078,16 +2612,29 @@ function printScanSummary(result, progress, errorOutput) {
2078
2612
  completed >= started
2079
2613
  ? Math.floor((completed - started) / 1_000)
2080
2614
  : progress?.elapsedSeconds ?? 0;
2081
- errorOutput.write(`codex-security: Elapsed: ${elapsed}s.\n`);
2615
+ const duration = elapsed < 60
2616
+ ? `${elapsed}s`
2617
+ : `${Math.floor(elapsed / 60)}m ${elapsed % 60}s`;
2618
+ const findingCount = result.findings.findings.length;
2619
+ const findingColor = findingCount === 0
2620
+ ? 32
2621
+ : severities.has("critical") || severities.has("high")
2622
+ ? 31
2623
+ : severities.has("medium")
2624
+ ? 33
2625
+ : 36;
2626
+ errorOutput.write(`\n ${paint("REPORT", "1;36")} ${paint(redactedErrorMessage(result.reportPath), 4)}\n\n` +
2627
+ ` ${paint("FINDINGS", 1)} ${paint(`${findingCount}${severitySummary === "" ? "" : ` (${severitySummary})`}`, findingColor)}\n` +
2628
+ ` ${paint("COVERAGE", 1)} ${result.coverage.completeness}\n` +
2629
+ ` ${paint("ELAPSED", 1)} ${duration}\n`);
2082
2630
  const tokenSummary = formatTokenUsage(result.turnResult.usage);
2083
2631
  if (tokenSummary !== null) {
2084
- errorOutput.write(`codex-security: Tokens: ${tokenSummary}.\n`);
2632
+ errorOutput.write(` ${paint("TOKENS", 1)} ${tokenSummary}\n`);
2085
2633
  }
2086
2634
  if (result.cost !== null) {
2087
- errorOutput.write(`codex-security: Estimated cost: ${formatUsd(result.cost.estimatedUsd)} USD.\n`);
2635
+ errorOutput.write(` ${paint("COST", 1)} ${formatUsd(result.cost.estimatedUsd)}\n`);
2088
2636
  }
2089
- errorOutput.write(`codex-security: Report: ${cliErrorMessage(result.reportPath)}\n`);
2090
- errorOutput.write(`codex-security: Results: ${cliErrorMessage(result.scanDir)}\n`);
2637
+ errorOutput.write(` ${paint("RESULTS", 1)} ${redactedErrorMessage(result.scanDir)}\n`);
2091
2638
  }
2092
2639
  function formatTokenUsage(usage) {
2093
2640
  if (usage === null || typeof usage !== "object")
@@ -2127,7 +2674,7 @@ function protectedRootErrorMessage(error) {
2127
2674
  ? "Set TMPDIR (or TEMP on Windows) to a writable directory outside the protected root."
2128
2675
  : `Set TMPDIR (or TEMP on Windows) to ${quoteCliPath(suggestion)} after creating that directory.`;
2129
2676
  return [
2130
- `codex-security: ${description} must be outside the scanned directory and any enclosing Git worktree.`,
2677
+ `${description} must be outside the scanned directory and any enclosing Git worktree.`,
2131
2678
  ` Resolved path: ${error.outputDirectory}`,
2132
2679
  ` Protected root: ${error.protectedRoot}`,
2133
2680
  ` Reason: ${reason}`,
@@ -2183,12 +2730,18 @@ function targetFromArguments(arguments_) {
2183
2730
  }
2184
2731
  return "repository";
2185
2732
  }
2186
- export function parseCodexOverrides(values, model, effort) {
2733
+ export function parseCodexOverrides(values, model, effort, provider) {
2187
2734
  const result = Object.create(null);
2188
2735
  if (model !== undefined)
2189
2736
  result["model"] = model;
2190
2737
  if (effort !== undefined)
2191
2738
  result["model_reasoning_effort"] = effort;
2739
+ if (isExternalModelProvider(provider)) {
2740
+ result["model_provider"] = provider;
2741
+ result["model_providers"] = {
2742
+ [provider]: { ...EXTERNAL_CODEX_PROVIDERS[provider] },
2743
+ };
2744
+ }
2192
2745
  for (const value of values) {
2193
2746
  const separator = value.indexOf("=");
2194
2747
  const key = separator < 0 ? "" : value.slice(0, separator);
@@ -2238,10 +2791,16 @@ export function parseCodexOverrides(values, model, effort) {
2238
2791
  if (effort !== undefined && key === "model_reasoning_effort") {
2239
2792
  throw new CodexSecurityError("--effort conflicts with --codex model_reasoning_effort");
2240
2793
  }
2794
+ if (isExternalModelProvider(provider) && key === "model_provider") {
2795
+ throw new CodexSecurityError("--provider conflicts with --codex model_provider");
2796
+ }
2241
2797
  throw new CodexSecurityError("Duplicate --codex key");
2242
2798
  }
2243
2799
  cursor[final] = parsed;
2244
2800
  }
2801
+ if (isExternalModelProvider(provider) && !("model" in result)) {
2802
+ throw new CodexSecurityError(`--model is required when using --provider ${provider}`);
2803
+ }
2245
2804
  return result;
2246
2805
  }
2247
2806
  function workerStatusMessage(status) {
@@ -2271,6 +2830,7 @@ export class Progress {
2271
2830
  #startedAt;
2272
2831
  #interactive;
2273
2832
  #timer = null;
2833
+ #timerMessage = null;
2274
2834
  #timerLineActive = false;
2275
2835
  #cursorHidden = false;
2276
2836
  constructor(stream = process.stderr, dependencies = DEFAULT_DEPENDENCIES, interactive = true) {
@@ -2297,12 +2857,14 @@ export class Progress {
2297
2857
  this.#cursorHidden = true;
2298
2858
  this.#renderTimer(message);
2299
2859
  this.#timer = this.#dependencies.setInterval(() => this.#renderTimer(message), PROGRESS_REFRESH_MILLISECONDS);
2860
+ this.#timerMessage = message;
2300
2861
  }
2301
2862
  stopTimer() {
2302
2863
  if (this.#timer !== null) {
2303
2864
  this.#dependencies.clearInterval(this.#timer);
2304
2865
  this.#timer = null;
2305
2866
  }
2867
+ this.#timerMessage = null;
2306
2868
  if (this.#timerLineActive) {
2307
2869
  this.#stream.write("\n");
2308
2870
  this.#timerLineActive = false;
@@ -2312,6 +2874,20 @@ export class Progress {
2312
2874
  this.#cursorHidden = false;
2313
2875
  }
2314
2876
  }
2877
+ writeAboveTimer(write) {
2878
+ const message = this.#timerMessage;
2879
+ if (message === null) {
2880
+ write();
2881
+ return;
2882
+ }
2883
+ this.stopTimer();
2884
+ try {
2885
+ write();
2886
+ }
2887
+ finally {
2888
+ this.startTimer(message);
2889
+ }
2890
+ }
2315
2891
  #line(message) {
2316
2892
  const elapsedSeconds = this.elapsedSeconds;
2317
2893
  const minutes = Math.floor(elapsedSeconds / 60);
@@ -2328,7 +2904,7 @@ function interruptedExit(signal, scanDir, errorOutput) {
2328
2904
  errorOutput.write(`codex-security: Scan ${ctrlC ? "canceled by Ctrl-C" : "terminated by SIGTERM"}.\n`);
2329
2905
  errorOutput.write(scanDir === null
2330
2906
  ? "codex-security: No partial output was kept.\n"
2331
- : `codex-security: Partial output was kept at ${cliErrorMessage(scanDir)}.\n`);
2907
+ : `codex-security: Partial output was kept at ${redactedErrorMessage(scanDir)}.\n`);
2332
2908
  return ctrlC ? 130 : 143;
2333
2909
  }
2334
2910
  function isJsonObject(value) {
@@ -2347,22 +2923,11 @@ function invokedAsMain() {
2347
2923
  return false;
2348
2924
  }
2349
2925
  }
2350
- function cliErrorMessage(error) {
2351
- const message = error instanceof Error ? error.message : String(error);
2352
- return message
2353
- .replaceAll(/(\b[A-Za-z0-9_-]{0,64}(?:api[_-]?key|access[_-]?key(?:[_-]?id)?|token|secret|credential|signature|sig|password|passwd)\b(?:\\?["'])?\s*[:=]\s*(?:\\?["'])?)[^\s"',;}&\\\]]+/giu, "$1[redacted]")
2354
- .replaceAll(/sk-(?:proj-)?[A-Za-z0-9_*=-]{8,}/gu, "[redacted]")
2355
- .replaceAll(/(?:github_pat_|gh[pousr]_)[A-Za-z0-9_-]{8,}/giu, "[redacted]")
2356
- .replaceAll(/npm_[A-Za-z0-9_-]{8,}/giu, "[redacted]")
2357
- .replaceAll(/(^|%20|[^A-Za-z0-9_])(Bearer|Basic|Token)((?:\s|%20|\+)+)[A-Za-z0-9.%_~+/*=-]{8,}/giu, "$1$2$3[redacted]")
2358
- .replaceAll(/((?:https?|ssh|git\+ssh):\/\/)[^\s/@]+@/giu, "$1[redacted]@")
2359
- .replaceAll(/((?:[?&]|%3F|%26)(?:(?!%3F|%26|%3D)(?:[A-Za-z0-9_.%-]|\[|\])){0,64}(?:api[_-]?key|access(?:[_-]|%5F|%2D)?key(?:(?:[_-]|%5F|%2D)?id)?|token|secret|credential|signature|sig|password|passwd)(?:\]|%5D)?(?:=|%3D))(?:(?!%26)[^&\s])+/giu, "$1[redacted]");
2360
- }
2361
2926
  if (invokedAsMain()) {
2362
2927
  void main().then((exitCode) => {
2363
2928
  process.exitCode = exitCode;
2364
2929
  }, (error) => {
2365
- process.stderr.write(`codex-security: ${cliErrorMessage(error)}\n`);
2930
+ process.stderr.write(`codex-security: ${redactedErrorMessage(error)}\n`);
2366
2931
  process.exitCode = 2;
2367
2932
  });
2368
2933
  }