@openai/codex-security 0.1.30 → 0.2.0

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 (320) hide show
  1. package/README.md +386 -37
  2. package/_bundled_plugin/.mcp.json +1 -0
  3. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  4. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +4 -4
  5. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  6. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  7. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  8. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  9. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  10. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  11. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  12. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  13. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  14. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  15. package/_bundled_plugin/references/artifact-storage.md +4 -4
  16. package/_bundled_plugin/references/config-preflight.md +1 -1
  17. package/_bundled_plugin/references/core-scan.md +14 -2
  18. package/_bundled_plugin/references/final-report.md +4 -2
  19. package/_bundled_plugin/references/scan-artifacts.md +2 -2
  20. package/_bundled_plugin/references/scan-contract.md +2 -2
  21. package/_bundled_plugin/references/threat-model.md +2 -2
  22. package/_bundled_plugin/schemas/coverage.schema.json +22 -0
  23. package/_bundled_plugin/schemas/scan-manifest.schema.json +100 -85
  24. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +19 -4
  25. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +116 -102
  26. package/_bundled_plugin/scripts/config_preflight.py +4 -8
  27. package/_bundled_plugin/scripts/deep_scan_workbench.py +83 -217
  28. package/_bundled_plugin/scripts/filesystem_identity.py +1 -5
  29. package/_bundled_plugin/scripts/finalize_scan_contract.py +441 -166
  30. package/_bundled_plugin/scripts/finding_preview.py +42 -82
  31. package/_bundled_plugin/scripts/generate_in_scope_files.py +30 -34
  32. package/_bundled_plugin/scripts/generate_rank_input.py +58 -99
  33. package/_bundled_plugin/scripts/launch_codex_security_mcp +5 -1
  34. package/_bundled_plugin/scripts/rank_preview.py +86 -68
  35. package/_bundled_plugin/scripts/report_projection.py +37 -58
  36. package/_bundled_plugin/scripts/threat_model_projection.py +164 -0
  37. package/_bundled_plugin/scripts/windows_scan_local_files.py +11 -6
  38. package/_bundled_plugin/scripts/workbench/storage.py +11 -0
  39. package/_bundled_plugin/scripts/workbench_cli.py +11 -17
  40. package/_bundled_plugin/scripts/workbench_constants.py +6 -14
  41. package/_bundled_plugin/scripts/workbench_db.py +116 -228
  42. package/_bundled_plugin/scripts/workbench_finding_index.py +1 -6
  43. package/_bundled_plugin/scripts/workbench_native_indexes.py +1 -4
  44. package/_bundled_plugin/scripts/workbench_progress.py +12 -34
  45. package/_bundled_plugin/scripts/workbench_publication.py +47 -62
  46. package/_bundled_plugin/scripts/workbench_remediation.py +2 -20
  47. package/_bundled_plugin/scripts/workbench_saved_results.py +1246 -230
  48. package/_bundled_plugin/scripts/workbench_scan_start.py +4 -11
  49. package/_bundled_plugin/scripts/workbench_scan_usage.py +7 -15
  50. package/_bundled_plugin/scripts/workbench_schema.py +86 -271
  51. package/_bundled_plugin/scripts/workbench_severity.py +3 -0
  52. package/_bundled_plugin/scripts/workbench_source_excerpt.py +5 -6
  53. package/_bundled_plugin/scripts/workbench_target.py +98 -10
  54. package/_bundled_plugin/scripts/workbench_target_state.py +1 -5
  55. package/_bundled_plugin/scripts/workbench_validation.py +6 -20
  56. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +3 -3
  57. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +3 -3
  58. package/_bundled_plugin/skills/security-scan/SKILL.md +2 -2
  59. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +2 -2
  60. package/_bundled_plugin/skills/threat-model/SKILL.md +2 -2
  61. package/dist/api.d.ts +3 -5
  62. package/dist/api.d.ts.map +1 -1
  63. package/dist/api.js +201 -207
  64. package/dist/api.js.map +1 -1
  65. package/dist/artifact-export.d.ts +70 -0
  66. package/dist/artifact-export.d.ts.map +1 -0
  67. package/dist/artifact-export.js +277 -0
  68. package/dist/artifact-export.js.map +1 -0
  69. package/dist/auth.d.ts.map +1 -1
  70. package/dist/auth.js +9 -4
  71. package/dist/auth.js.map +1 -1
  72. package/dist/bulk-scan-discovery.d.ts +1 -0
  73. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  74. package/dist/bulk-scan-discovery.js +8 -9
  75. package/dist/bulk-scan-discovery.js.map +1 -1
  76. package/dist/classify-scan-severity.d.ts.map +1 -1
  77. package/dist/classify-scan-severity.js +2 -5
  78. package/dist/classify-scan-severity.js.map +1 -1
  79. package/dist/classify-severity.d.ts +2 -8
  80. package/dist/classify-severity.d.ts.map +1 -1
  81. package/dist/classify-severity.js +3 -5
  82. package/dist/classify-severity.js.map +1 -1
  83. package/dist/cli-help.d.ts +3 -0
  84. package/dist/cli-help.d.ts.map +1 -0
  85. package/dist/cli-help.js +281 -0
  86. package/dist/cli-help.js.map +1 -0
  87. package/dist/cli.d.ts +21 -22
  88. package/dist/cli.d.ts.map +1 -1
  89. package/dist/cli.js +673 -701
  90. package/dist/cli.js.map +1 -1
  91. package/dist/cloud-publish.d.ts.map +1 -1
  92. package/dist/cloud-publish.js +1 -8
  93. package/dist/cloud-publish.js.map +1 -1
  94. package/dist/codex-prompt.d.ts.map +1 -1
  95. package/dist/codex-prompt.js +1 -2
  96. package/dist/codex-prompt.js.map +1 -1
  97. package/dist/codex-sdk-environment.d.ts +2 -0
  98. package/dist/codex-sdk-environment.d.ts.map +1 -0
  99. package/dist/codex-sdk-environment.js +30 -0
  100. package/dist/codex-sdk-environment.js.map +1 -0
  101. package/dist/component-plan.d.ts.map +1 -1
  102. package/dist/component-plan.js +2 -6
  103. package/dist/component-plan.js.map +1 -1
  104. package/dist/component-scan.d.ts +1 -0
  105. package/dist/component-scan.d.ts.map +1 -1
  106. package/dist/component-scan.js +31 -9
  107. package/dist/component-scan.js.map +1 -1
  108. package/dist/config.d.ts.map +1 -1
  109. package/dist/config.js +32 -33
  110. package/dist/config.js.map +1 -1
  111. package/dist/contract.d.ts +2 -1
  112. package/dist/contract.d.ts.map +1 -1
  113. package/dist/contract.js +63 -122
  114. package/dist/contract.js.map +1 -1
  115. package/dist/cost-model.d.ts.map +1 -1
  116. package/dist/cost-model.js +65 -34
  117. package/dist/cost-model.js.map +1 -1
  118. package/dist/cost.d.ts.map +1 -1
  119. package/dist/cost.js +15 -31
  120. package/dist/cost.js.map +1 -1
  121. package/dist/custom-validation-prompt.js +4 -4
  122. package/dist/custom-validation-prompt.js.map +1 -1
  123. package/dist/custom-validation.d.ts.map +1 -1
  124. package/dist/custom-validation.js +17 -16
  125. package/dist/custom-validation.js.map +1 -1
  126. package/dist/deduplication/checkpointed-review.d.ts.map +1 -1
  127. package/dist/deduplication/checkpointed-review.js +10 -11
  128. package/dist/deduplication/checkpointed-review.js.map +1 -1
  129. package/dist/deduplication/codex-review.d.ts +2 -0
  130. package/dist/deduplication/codex-review.d.ts.map +1 -1
  131. package/dist/deduplication/codex-review.js +3 -3
  132. package/dist/deduplication/codex-review.js.map +1 -1
  133. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  134. package/dist/deduplication/deduplication-reviewer.js +2 -0
  135. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  136. package/dist/deduplication/deduplication.js +40 -62
  137. package/dist/deduplication/deduplication.js.map +1 -1
  138. package/dist/deduplication/records-protocol.d.ts.map +1 -1
  139. package/dist/deduplication/records-protocol.js +1 -4
  140. package/dist/deduplication/records-protocol.js.map +1 -1
  141. package/dist/deduplication/records.d.ts +2 -1
  142. package/dist/deduplication/records.d.ts.map +1 -1
  143. package/dist/deduplication/records.js +24 -6
  144. package/dist/deduplication/records.js.map +1 -1
  145. package/dist/deduplication/review.d.ts +7 -0
  146. package/dist/deduplication/review.d.ts.map +1 -1
  147. package/dist/deduplication/review.js.map +1 -1
  148. package/dist/deduplication/scan.js +3 -7
  149. package/dist/deduplication/scan.js.map +1 -1
  150. package/dist/deep-config.d.ts.map +1 -1
  151. package/dist/deep-config.js +3 -19
  152. package/dist/deep-config.js.map +1 -1
  153. package/dist/deep-progress.d.ts +0 -1
  154. package/dist/deep-progress.d.ts.map +1 -1
  155. package/dist/deep-progress.js +22 -40
  156. package/dist/deep-progress.js.map +1 -1
  157. package/dist/errors.d.ts +3 -2
  158. package/dist/errors.d.ts.map +1 -1
  159. package/dist/errors.js +5 -7
  160. package/dist/errors.js.map +1 -1
  161. package/dist/finding-catalogue.d.ts.map +1 -1
  162. package/dist/finding-catalogue.js +22 -22
  163. package/dist/finding-catalogue.js.map +1 -1
  164. package/dist/finding-workflow.d.ts.map +1 -1
  165. package/dist/finding-workflow.js +4 -7
  166. package/dist/finding-workflow.js.map +1 -1
  167. package/dist/findings-import.d.ts.map +1 -1
  168. package/dist/findings-import.js +7 -17
  169. package/dist/findings-import.js.map +1 -1
  170. package/dist/github.d.ts.map +1 -1
  171. package/dist/github.js +2 -3
  172. package/dist/github.js.map +1 -1
  173. package/dist/import-scan.js +2 -2
  174. package/dist/import-scan.js.map +1 -1
  175. package/dist/index.d.ts +6 -2
  176. package/dist/index.d.ts.map +1 -1
  177. package/dist/index.js +3 -1
  178. package/dist/index.js.map +1 -1
  179. package/dist/knowledge-base.js +7 -3
  180. package/dist/knowledge-base.js.map +1 -1
  181. package/dist/linear.d.ts.map +1 -1
  182. package/dist/linear.js +2 -3
  183. package/dist/linear.js.map +1 -1
  184. package/dist/models.d.ts +24 -0
  185. package/dist/models.d.ts.map +1 -1
  186. package/dist/models.js.map +1 -1
  187. package/dist/multiscan.d.ts.map +1 -1
  188. package/dist/multiscan.js +36 -31
  189. package/dist/multiscan.js.map +1 -1
  190. package/dist/owner-evidence.d.ts +29 -0
  191. package/dist/owner-evidence.d.ts.map +1 -0
  192. package/dist/owner-evidence.js +192 -0
  193. package/dist/owner-evidence.js.map +1 -0
  194. package/dist/patch-tui.d.ts.map +1 -1
  195. package/dist/patch-tui.js +2 -4
  196. package/dist/patch-tui.js.map +1 -1
  197. package/dist/project-config-schema.d.ts +10 -0
  198. package/dist/project-config-schema.d.ts.map +1 -1
  199. package/dist/project-config-schema.js +1 -0
  200. package/dist/project-config-schema.js.map +1 -1
  201. package/dist/project-config.d.ts +1 -0
  202. package/dist/project-config.d.ts.map +1 -1
  203. package/dist/project-config.js +2 -0
  204. package/dist/project-config.js.map +1 -1
  205. package/dist/prompt-files.d.ts +0 -1
  206. package/dist/prompt-files.d.ts.map +1 -1
  207. package/dist/prompt-files.js +2 -4
  208. package/dist/prompt-files.js.map +1 -1
  209. package/dist/publication-events.d.ts.map +1 -1
  210. package/dist/publication-events.js +15 -29
  211. package/dist/publication-events.js.map +1 -1
  212. package/dist/publication-store.d.ts.map +1 -1
  213. package/dist/publication-store.js +9 -13
  214. package/dist/publication-store.js.map +1 -1
  215. package/dist/publication.d.ts.map +1 -1
  216. package/dist/publication.js +11 -14
  217. package/dist/publication.js.map +1 -1
  218. package/dist/publish.d.ts.map +1 -1
  219. package/dist/publish.js +31 -41
  220. package/dist/publish.js.map +1 -1
  221. package/dist/record.d.ts +2 -0
  222. package/dist/record.d.ts.map +1 -0
  223. package/dist/record.js +4 -0
  224. package/dist/record.js.map +1 -0
  225. package/dist/result.d.ts +4 -1
  226. package/dist/result.d.ts.map +1 -1
  227. package/dist/result.js +7 -0
  228. package/dist/result.js.map +1 -1
  229. package/dist/runtime.d.ts +10 -13
  230. package/dist/runtime.d.ts.map +1 -1
  231. package/dist/runtime.js +230 -145
  232. package/dist/runtime.js.map +1 -1
  233. package/dist/saved-scan.d.ts.map +1 -1
  234. package/dist/saved-scan.js +10 -20
  235. package/dist/saved-scan.js.map +1 -1
  236. package/dist/scan-activity.d.ts.map +1 -1
  237. package/dist/scan-activity.js +8 -22
  238. package/dist/scan-activity.js.map +1 -1
  239. package/dist/scan-comparison.d.ts +4 -4
  240. package/dist/scan-comparison.d.ts.map +1 -1
  241. package/dist/scan-comparison.js +38 -73
  242. package/dist/scan-comparison.js.map +1 -1
  243. package/dist/scan-dashboard.d.ts +0 -1
  244. package/dist/scan-dashboard.d.ts.map +1 -1
  245. package/dist/scan-dashboard.js +10 -19
  246. package/dist/scan-dashboard.js.map +1 -1
  247. package/dist/scan-history-renderer.d.ts.map +1 -1
  248. package/dist/scan-history-renderer.js +1 -2
  249. package/dist/scan-history-renderer.js.map +1 -1
  250. package/dist/scan-logs.d.ts.map +1 -1
  251. package/dist/scan-logs.js +2 -6
  252. package/dist/scan-logs.js.map +1 -1
  253. package/dist/scan-sessions.d.ts.map +1 -1
  254. package/dist/scan-sessions.js +1 -3
  255. package/dist/scan-sessions.js.map +1 -1
  256. package/dist/scan-settings.d.ts +5 -0
  257. package/dist/scan-settings.d.ts.map +1 -1
  258. package/dist/scan-settings.js +4 -0
  259. package/dist/scan-settings.js.map +1 -1
  260. package/dist/security-policy-cli.d.ts.map +1 -1
  261. package/dist/security-policy-cli.js +8 -6
  262. package/dist/security-policy-cli.js.map +1 -1
  263. package/dist/security-policy.d.ts +8 -4
  264. package/dist/security-policy.d.ts.map +1 -1
  265. package/dist/security-policy.js +98 -84
  266. package/dist/security-policy.js.map +1 -1
  267. package/dist/server/dashboard/app.js +5 -5
  268. package/dist/server/embeddings.d.ts.map +1 -1
  269. package/dist/server/embeddings.js +1 -0
  270. package/dist/server/embeddings.js.map +1 -1
  271. package/dist/server/routes.d.ts +3 -2
  272. package/dist/server/routes.d.ts.map +1 -1
  273. package/dist/server/routes.js +19 -7
  274. package/dist/server/routes.js.map +1 -1
  275. package/dist/server/server.d.ts.map +1 -1
  276. package/dist/server/server.js +2 -3
  277. package/dist/server/server.js.map +1 -1
  278. package/dist/server/sqlite-store.d.ts.map +1 -1
  279. package/dist/server/sqlite-store.js +4 -14
  280. package/dist/server/sqlite-store.js.map +1 -1
  281. package/dist/severity-store.js +8 -15
  282. package/dist/severity-store.js.map +1 -1
  283. package/dist/suggest-owners.d.ts +37 -0
  284. package/dist/suggest-owners.d.ts.map +1 -0
  285. package/dist/suggest-owners.js +111 -0
  286. package/dist/suggest-owners.js.map +1 -0
  287. package/dist/targets.d.ts +7 -2
  288. package/dist/targets.d.ts.map +1 -1
  289. package/dist/targets.js +29 -25
  290. package/dist/targets.js.map +1 -1
  291. package/dist/thread-source.d.ts +1 -0
  292. package/dist/thread-source.d.ts.map +1 -1
  293. package/dist/thread-source.js +1 -0
  294. package/dist/thread-source.js.map +1 -1
  295. package/dist/trusted-executable.d.ts +5 -0
  296. package/dist/trusted-executable.d.ts.map +1 -1
  297. package/dist/trusted-executable.js +22 -5
  298. package/dist/trusted-executable.js.map +1 -1
  299. package/dist/value.d.ts +2 -0
  300. package/dist/value.d.ts.map +1 -0
  301. package/dist/value.js +20 -0
  302. package/dist/value.js.map +1 -0
  303. package/dist/version.d.ts.map +1 -1
  304. package/dist/version.js +3 -6
  305. package/dist/version.js.map +1 -1
  306. package/dist/windows-path.d.ts.map +1 -1
  307. package/dist/windows-path.js +1 -2
  308. package/dist/windows-path.js.map +1 -1
  309. package/dist/worker-progress.d.ts +1 -0
  310. package/dist/worker-progress.d.ts.map +1 -1
  311. package/dist/worker-progress.js +13 -34
  312. package/dist/worker-progress.js.map +1 -1
  313. package/docs/dedupe-records.md +24 -0
  314. package/package.json +15 -13
  315. package/schemas/project-config.schema.json +5 -0
  316. package/_bundled_plugin/scripts/normalize_candidates.py +0 -338
  317. package/dist/server/findings-service.d.ts +0 -20
  318. package/dist/server/findings-service.d.ts.map +0 -1
  319. package/dist/server/findings-service.js +0 -31
  320. package/dist/server/findings-service.js.map +0 -1
package/dist/cli.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { isNonEmptyString } from "./value.js";
2
3
  import { execFile as execFileCallback, execFileSync, spawn, } from "node:child_process";
3
4
  import { createHash } from "node:crypto";
4
5
  import { accessSync, constants, createReadStream, existsSync, lstatSync, realpathSync, writeSync, } from "node:fs";
@@ -8,15 +9,20 @@ import { basename, dirname, isAbsolute, join, parse, relative, resolve, win32, }
8
9
  import { cwd } from "node:process";
9
10
  import { createInterface } from "node:readline";
10
11
  import { Readable, Writable as NodeWritable } from "node:stream";
11
- import { pipeline } from "node:stream/promises";
12
12
  import { fileURLToPath, pathToFileURL } from "node:url";
13
13
  import { promisify, stripVTControlCharacters } from "node:util";
14
14
  import { Cli, z } from "incur";
15
+ import { formatCliHelp } from "./cli-help.js";
15
16
  import { scanLogsJson } from "./cli-scan-logs-json.js";
17
+ import { ARTIFACT_EXPORT_FILENAMES, exportEnvironment, resolveArtifactFormat, resolveArtifactExportOutput, resolveSavedArtifactDirectory, runArtifactExport, writeArtifactOutput as writeCliOutput, } from "./artifact-export.js";
18
+ export { exportEnvironment } from "./artifact-export.js";
16
19
  import { parse as parseToml } from "smol-toml";
17
20
  import { classifyConnectionFailure, createSecurityInternal, environmentValue, formatEnvironmentVariableRemovalGuidance, initialCredentialsAvailable, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, runtimeScanAuthentication, selectedScanEnvironment, } from "./api.js";
18
- import { accountStatus, CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, configuredCodexHome, readCodexHomeConfig, } from "./auth.js";
19
- import { loadContract } from "./contract.js";
21
+ import { accountStatus, CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, configuredCodexHome, environmentEntry, readCodexHomeConfig, } from "./auth.js";
22
+ import { loadContract, sha256Text } from "./contract.js";
23
+ import { isRecord as isJsonObject } from "./record.js";
24
+ import { suggestOwnersInternal } from "./suggest-owners.js";
25
+ import { parseImportedFindings } from "./findings-import.js";
20
26
  import { publishScanToCustom } from "./custom-publish.js";
21
27
  import { DEFAULT_DEDUPE_CONCURRENCY } from "./deduplication/deduplication.js";
22
28
  import { deduplicateScanInternal } from "./deduplication/scan.js";
@@ -24,12 +30,12 @@ import { runRecordsProtocol } from "./deduplication/records-protocol.js";
24
30
  import { classifyScanSeverityInternal, classifyScanDirectorySeverityInternal, } from "./classify-scan-severity.js";
25
31
  import { resolveCompletedScan, resolveWorkflowScan, } from "./saved-scan.js";
26
32
  import { publishFindingsCsvToCloud, publishScanToCloud, } from "./cloud-publish.js";
27
- import { createBulkScanDiscoveryDependencies, runBulkScanWizard, } from "./bulk-scan-discovery.js";
28
- import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergeCodexOverrides, hasCommandAuth, inlineToml, modelProviderConfigOverride, resolveCommandAuthConfig, mergedCodexConfig, scanModel, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
33
+ import { createBulkScanDiscoveryDependencies, createTerminalPrompt, runBulkScanWizard, } from "./bulk-scan-discovery.js";
34
+ import { DEFAULT_CODEX_CONFIG, deepMerge, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergeCodexOverrides, hasCommandAuth, inlineToml, modelProviderConfigOverride, resolveCommandAuthConfig, resolveCodexProfile, mergedCodexConfig, scanModel, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
29
35
  import { formatUsd } from "./cost.js";
30
36
  import { formatScanCost, formatScanCostTokens, formatTokenUsage, } from "./cost-model.js";
31
- import { isOutsidePath, readRegularInputFile, resolveScanPrompts, } from "./prompt-files.js";
32
- import { CodexSecurityError, AuthenticationRequiredError, ConfigurationError, InvalidTargetError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
37
+ import { readRegularInputFile, resolveScanPrompts } from "./prompt-files.js";
38
+ import { CodexSecurityError, AuthenticationRequiredError, ConfigurationError, InvalidTargetError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, errorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
33
39
  import { GITHUB_ALERT_STATES, importGitHubCodeScanningAlerts, } from "./github.js";
34
40
  import { importLinearIssues, isLinearIssueIdentifier, resolveLinearApiKey, } from "./linear.js";
35
41
  import { runMultiscan } from "./multiscan.js";
@@ -37,7 +43,7 @@ import { componentPlanSchema } from "./component-plan.js";
37
43
  import { runComponentScans, } from "./component-scan.js";
38
44
  import { checkScanPublication, forceTerminatePublicationProcesses as terminatePublishers, publishScan, } from "./publish.js";
39
45
  import { importScan } from "./import-scan.js";
40
- import { bundledPluginRoot, acquireCodexSecurityCredentialHomeLock, requireOutputOutsideRepositories, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, executablePathForSpawn, expandHome, prepareCodexSecurityCredentialHome, pythonUtf8Environment, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
46
+ import { bundledPluginRoot, acquireCodexSecurityCredentialHomeLock, requireOutputOutsideRepositories, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, executablePathForSpawn, expandHome, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
41
47
  import { comparisonFindingGroups, comparisonForScan, matchScanFindingsInternal, unionFindingGroups, } from "./scan-comparison.js";
42
48
  import { scanActivitiesFromEvent } from "./scan-activity.js";
43
49
  import { CODEX_SECURITY_THREAD_SOURCES, } from "./thread-source.js";
@@ -47,7 +53,7 @@ import { renderScanHistory, } from "./scan-history-renderer.js";
47
53
  import { ScanDashboard } from "./scan-dashboard.js";
48
54
  import { policyDisplayData, runPolicyCommand, } from "./security-policy-cli.js";
49
55
  import { scanPhaseLabel as scanPhase, } from "./worker-progress.js";
50
- import { abortable, DiffTarget, enclosingGitWorktreeRoots, } from "./targets.js";
56
+ import { abortable, DiffTarget, enclosingGitWorktreeRoots, relativePathIsOutside as isOutsidePath, } from "./targets.js";
51
57
  import { resolveTrustedExecutable } from "./trusted-executable.js";
52
58
  import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, updateNoticeEnabled, VERSION, } from "./version.js";
53
59
  import { readProjectConfig, resolveScanSettings, projectScopeTarget, configurationSources, projectConfigStarter, } from "./project-config.js";
@@ -67,27 +73,37 @@ const DUPLICATE_SIGNAL_WINDOW_MS = 500;
67
73
  const PUBLICATION_GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, {
68
74
  granularity: "grapheme",
69
75
  });
70
- const DISPLAY_SEVERITIES = SCAN_SEVERITIES;
71
- const MODEL_REASONING_EFFORTS = [
72
- "minimal",
73
- "low",
74
- "medium",
75
- "high",
76
- "xhigh",
77
- "max",
78
- ];
79
76
  const DEFAULT_SCAN_MODEL_CONFIGURATION = scanModelConfiguration(DEFAULT_CODEX_CONFIG);
77
+ const MODEL_OPTIONS = modelOptions();
78
+ const MATCHING_MODEL_OPTIONS = modelOptions("Model for finding matching (default: Codex's configured model).", "Matching reasoning effort (default: medium).");
79
+ const SKILL_CODEX_OVERRIDE_DESCRIPTION = 'Repeat TOML model="gpt-5.6-terra", model_reasoning_effort="high", model_provider="gateway", model_providers.<name>.<key>=VALUE, or analytics.enabled=false.';
80
+ const SKILL_CONFIG_OPTIONS = MODEL_OPTIONS.extend({
81
+ codex: z
82
+ .array(optionValue("--codex"))
83
+ .default([])
84
+ .describe(SKILL_CODEX_OVERRIDE_DESCRIPTION),
85
+ });
80
86
  const CODEX_OVERRIDE_DESCRIPTION = 'Repeat TOML KEY=VALUE; e.g. model_reasoning_effort="high" or features.multi_agent_v2.max_concurrent_threads_per_session=4.';
81
87
  const PLUGIN_PATH_DESCRIPTION = "Codex Security plugin directory or ZIP (default: bundled plugin).";
82
88
  const PYTHON_PATH_DESCRIPTION = "Python interpreter (default: PYTHON or automatic discovery).";
89
+ const RUNTIME_OPTION_SCHEMAS = {
90
+ pluginPath: optionValue("--plugin-path")
91
+ .optional()
92
+ .describe(PLUGIN_PATH_DESCRIPTION),
93
+ python: optionValue("--python").optional().describe(PYTHON_PATH_DESCRIPTION),
94
+ codex: z
95
+ .array(optionValue("--codex"))
96
+ .default([])
97
+ .describe(CODEX_OVERRIDE_DESCRIPTION),
98
+ };
99
+ const SKILL_AUTH_OPTION = z
100
+ .enum(SCAN_AUTH_MODES)
101
+ .default("auto")
102
+ .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication.");
83
103
  const PROJECT_CONFIG_OPTION = optionValue("--config")
84
104
  .optional()
85
105
  .describe("Load a trusted YAML/JSON file (default: CODEX_SECURITY_PROJECT_CONFIG, otherwise no file).");
86
- const EXPORT_DEFAULT_OUTPUTS = {
87
- csv: "findings.csv",
88
- json: "findings.json",
89
- sarif: "results.sarif",
90
- };
106
+ const EXPORT_DEFAULT_OUTPUTS = ARTIFACT_EXPORT_FILENAMES;
91
107
  const VALUE_OPTIONS = new Set([
92
108
  "--config",
93
109
  "-c",
@@ -96,6 +112,7 @@ const VALUE_OPTIONS = new Set([
96
112
  "--concurrency",
97
113
  "--auth",
98
114
  "--safety-identifier",
115
+ "--cyber-access-program",
99
116
  "--path",
100
117
  "--component",
101
118
  "--components-file",
@@ -136,6 +153,7 @@ const VALUE_OPTIONS = new Set([
136
153
  "--max-time-hours",
137
154
  "--max-attempts",
138
155
  "--export-format",
156
+ "--artifact",
139
157
  "--csv",
140
158
  "--output",
141
159
  "--source-root",
@@ -273,8 +291,7 @@ function publicationIssueUrl(value) {
273
291
  if (value === undefined ||
274
292
  value !== value.trim() ||
275
293
  value !== stripVTControlCharacters(value) ||
276
- /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/u.test(value) ||
277
- safeErrorMessage(value) !== value) {
294
+ /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/u.test(value)) {
278
295
  return undefined;
279
296
  }
280
297
  let url;
@@ -306,7 +323,7 @@ function renderPublicationSummary(result, color) {
306
323
  : `${marker} ${title}`;
307
324
  const lines = [heading, ""];
308
325
  for (const issue of result.created.slice(0, 5)) {
309
- const identifier = stripVTControlCharacters(safeErrorMessage(issue.issueIdentifier))
326
+ const identifier = stripVTControlCharacters(issue.issueIdentifier)
310
327
  .replaceAll(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu, " ")
311
328
  .replace(/\s+/gu, " ")
312
329
  .trim() || "Unknown Linear issue";
@@ -346,7 +363,6 @@ class PublicationProgressPresenter {
346
363
  presentation: "publication",
347
364
  clock: this.#dependencies,
348
365
  color: this.#dependencies.environment["NO_COLOR"] === undefined,
349
- sanitize: safeErrorMessage,
350
366
  });
351
367
  dashboard.setStage("Connecting to Linear");
352
368
  try {
@@ -387,9 +403,7 @@ class PublicationProgressPresenter {
387
403
  }
388
404
  for (const activity of scanActivitiesFromEvent(event.event, this.#repository)) {
389
405
  const item = event.event["item"];
390
- const tool = typeof item === "object" && item !== null && !Array.isArray(item)
391
- ? item["tool"]
392
- : undefined;
406
+ const tool = isJsonObject(item) ? item["tool"] : undefined;
393
407
  const hidesShellCommand = activity.kind === "command" ||
394
408
  (activity.kind === "tool" &&
395
409
  typeof tool === "string" &&
@@ -450,7 +464,7 @@ class PublicationProgressPresenter {
450
464
  }
451
465
  }
452
466
  #write(message, compact = false) {
453
- const sanitized = diagnosticValue(safeErrorMessage(message));
467
+ const sanitized = diagnosticValue(message);
454
468
  if (!compact) {
455
469
  this.#stream.write(`${sanitized}\n`);
456
470
  return;
@@ -487,7 +501,6 @@ class FindingProgressPresenter {
487
501
  presentation: "verification",
488
502
  clock: this.#dependencies,
489
503
  color: this.#dependencies.environment["NO_COLOR"] === undefined,
490
- sanitize: safeErrorMessage,
491
504
  });
492
505
  dashboard.setPublicationProgress(0, this.#total);
493
506
  dashboard.setStage(`Verifying findings · 0/${this.#total}`);
@@ -516,16 +529,13 @@ class FindingProgressPresenter {
516
529
  observe(event) {
517
530
  const method = event["method"];
518
531
  const params = event["params"];
519
- if (typeof params !== "object" ||
520
- params === null ||
521
- Array.isArray(params)) {
532
+ if (!isJsonObject(params)) {
522
533
  return;
523
534
  }
524
- const values = params;
525
535
  let normalized;
526
536
  if (method === "item/reasoning/summaryTextDelta") {
527
- const id = values["itemId"];
528
- const delta = values["delta"];
537
+ const id = params["itemId"];
538
+ const delta = params["delta"];
529
539
  if (typeof id !== "string" || typeof delta !== "string")
530
540
  return;
531
541
  if (this.#dashboard === null)
@@ -538,34 +548,33 @@ class FindingProgressPresenter {
538
548
  };
539
549
  }
540
550
  else if (method === "item/started" || method === "item/completed") {
541
- const item = values["item"];
542
- if (typeof item !== "object" || item === null || Array.isArray(item)) {
551
+ const item = params["item"];
552
+ if (!isJsonObject(item)) {
543
553
  return;
544
554
  }
545
- const current = item;
546
- const type = current["type"];
555
+ const type = item["type"];
547
556
  let converted;
548
557
  if (type === "commandExecution") {
549
- converted = { ...current, type: "command_execution" };
558
+ converted = { ...item, type: "command_execution" };
550
559
  }
551
560
  else if (type === "mcpToolCall") {
552
- converted = { ...current, type: "mcp_tool_call" };
561
+ converted = { ...item, type: "mcp_tool_call" };
553
562
  }
554
563
  else if (type === "agentMessage") {
555
- if (current["phase"] !== "commentary")
564
+ if (item["phase"] !== "commentary")
556
565
  return;
557
- converted = { ...current, type: "agent_message" };
566
+ converted = { ...item, type: "agent_message" };
558
567
  }
559
568
  else if (type === "reasoning") {
560
- const summary = current["summary"];
569
+ const summary = item["summary"];
561
570
  const text = Array.isArray(summary)
562
571
  ? summary
563
572
  .filter((entry) => typeof entry === "string")
564
573
  .join("\n")
565
- : current["text"];
574
+ : item["text"];
566
575
  if (typeof text !== "string")
567
576
  return;
568
- converted = { ...current, text };
577
+ converted = { ...item, text };
569
578
  }
570
579
  else {
571
580
  return;
@@ -619,18 +628,15 @@ class FindingProgressPresenter {
619
628
  catch { }
620
629
  }
621
630
  }
622
- function effortOption() {
623
- return z
624
- .enum(MODEL_REASONING_EFFORTS, {
625
- error: "--effort must be minimal, low, medium, high, xhigh, or max.",
626
- })
627
- .optional()
628
- .describe(`Model reasoning effort (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.reasoningEffort}).`);
631
+ function modelOptions(modelDescription = `Model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`, effortDescription = `Model reasoning effort (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.reasoningEffort}).`) {
632
+ return z.object({
633
+ model: optionValue("--model").optional().describe(modelDescription),
634
+ effort: optionValue("--effort")
635
+ .optional()
636
+ .describe(`${effortDescription} Passed through to Codex; supported values depend on the model, provider, and Codex version.`),
637
+ });
629
638
  }
630
- const DEEP_SCAN_OPTION_SCHEMAS = Object.fromEntries(DEEP_SCAN_SETTINGS.filter(([, , , flag]) => flag !== null).map(([name]) => [
631
- name,
632
- DeepScanSettingsSchema.shape[name],
633
- ]));
639
+ const DEEP_SCAN_OPTION_SCHEMAS = Object.fromEntries(DEEP_SCAN_SETTINGS.flatMap(([name, , , flag]) => flag !== null ? [[name, DeepScanSettingsSchema.shape[name]]] : []));
634
640
  export function resolveCliPath(directory, value) {
635
641
  return resolveConfigPath(directory, value);
636
642
  }
@@ -713,70 +719,18 @@ const DEFAULT_DEPENDENCIES = {
713
719
  });
714
720
  return options?.trim === false ? stdout : stdout.trim();
715
721
  },
716
- exportFindings: async (arguments_, output) => {
717
- const environment = exportEnvironment();
718
- const python = await resolvePluginPython({
719
- configuredPath: arguments_.pythonPath,
720
- environment,
721
- });
722
- const plugin = await bundledPluginRoot();
723
- const invocation = spawn(python, [
724
- "-I",
725
- "-X",
726
- "utf8",
727
- join(plugin, "scripts", "finalize_scan_contract.py"),
728
- "--scan-dir",
729
- arguments_.scanDir,
730
- "--export-format",
731
- arguments_.format,
732
- ...(arguments_.output === "-"
733
- ? []
734
- : ["--export-output", arguments_.output]),
735
- ...(arguments_.sourceRoot === undefined
736
- ? []
737
- : ["--source-root", arguments_.sourceRoot]),
738
- ], {
739
- env: environment,
740
- stdio: ["ignore", "pipe", "pipe"],
741
- windowsHide: true,
742
- });
743
- let stderr = "";
744
- invocation.stderr.on("data", (chunk) => {
745
- stderr = `${stderr}${chunk.toString("utf8")}`.slice(-64 * 1024);
746
- });
747
- const forwarded = arguments_.output === "-" && output !== undefined
748
- ? writeCliOutput(output, invocation.stdout)
749
- : Promise.resolve(invocation.stdout.resume());
750
- let status;
751
- try {
752
- [status] = await Promise.all([
753
- new Promise((resolve, reject) => {
754
- invocation.once("error", reject);
755
- invocation.once("close", (code, signal) => resolve(signal === null ? (code ?? 1) : 1));
756
- }),
757
- forwarded,
758
- ]);
759
- }
760
- catch (error) {
761
- invocation.stdout.destroy();
762
- invocation.kill();
763
- throw error;
764
- }
765
- if (status !== 0) {
766
- const detail = stderr.trim().split("\n").at(-1);
767
- throw new CodexSecurityError(detail?.replace(/^finalize_scan_contract\.py: error: /, "") ||
768
- `Could not export Codex Security findings as ${arguments_.format.toUpperCase()}.`);
769
- }
770
- return undefined;
771
- },
772
- runWorkbench: async (args, input, signal) => {
722
+ exportFindings: runArtifactExport,
723
+ runWorkbench: async (args, input, signal, pythonPath) => {
773
724
  const environment = {
774
725
  ...exportEnvironment(),
775
726
  CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
776
727
  };
777
- const python = await resolvePluginPython({ environment, signal });
778
728
  return await runWorkbench({
779
- python,
729
+ python: await resolvePluginPython({
730
+ configuredPath: pythonPath,
731
+ environment,
732
+ signal,
733
+ }),
780
734
  pluginRoot: await bundledPluginRoot(),
781
735
  environment,
782
736
  signal,
@@ -785,6 +739,10 @@ const DEFAULT_DEPENDENCIES = {
785
739
  },
786
740
  matchFindings: (input, options) => matchScanFindingsInternal(input, options, { surface: "cli" }),
787
741
  };
742
+ function signalHandlers(dependencies, operation, interrupt, terminate) {
743
+ dependencies[`${operation}SignalListener`]("SIGINT", interrupt);
744
+ dependencies[`${operation}SignalListener`]("SIGTERM", terminate);
745
+ }
788
746
  export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env, input) {
789
747
  let releaseCredentialHome;
790
748
  try {
@@ -793,36 +751,83 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
793
751
  let modelProvider;
794
752
  // runSkill selects auth; other process callers supply their own environment.
795
753
  if (output?.auth !== undefined) {
796
- const config = output.modelProvider !== undefined
797
- ? {
798
- model_provider: output.modelProvider,
799
- ...(output.providerConfiguration === undefined
800
- ? {}
801
- : {
802
- model_providers: {
803
- [output.modelProvider]: output.providerConfiguration,
804
- },
805
- }),
806
- }
807
- : output.appServer === undefined
808
- ? {}
809
- : await readCodexHomeConfig(processEnvironment);
810
- const provider = scanModelProvider(config);
811
- const providerConfiguration = typeof provider === "string"
754
+ const ambientConfig = output.appServer === undefined
755
+ ? {}
756
+ : resolveCodexProfile(await readCodexHomeConfig(processEnvironment));
757
+ const overrides = structuredClone(output.codexOverrides ?? {});
758
+ const config = deepMerge(ambientConfig, overrides);
759
+ const provider = output.modelProvider ?? scanModelProvider(config);
760
+ // Native Codex ignores configured tables for these built-in providers.
761
+ const providerConfiguration = typeof provider === "string" &&
762
+ !["openai", "ollama", "lmstudio"].includes(provider)
812
763
  ? config["model_providers"]?.[provider]
813
764
  : undefined;
814
- const requiresOpenAiAuth = provider === undefined ||
815
- provider === "openai" ||
816
- providerConfiguration?.["requires_openai_auth"] === true;
765
+ const providerEnvKey = typeof providerConfiguration?.["env_key"] === "string"
766
+ ? providerConfiguration["env_key"]
767
+ : undefined;
768
+ const commandAuth = providerConfiguration?.["auth"] !== undefined;
769
+ const explicitChatgpt = output.auth === "chatgpt" && !isExternalModelProvider(provider);
770
+ const providerBearer = typeof providerConfiguration?.["experimental_bearer_token"] ===
771
+ "string";
772
+ const providerKeyConfigured = providerEnvKey !== undefined || providerBearer;
773
+ const requiresOpenAiAuth = !commandAuth &&
774
+ (explicitChatgpt || !providerKeyConfigured) &&
775
+ (provider === undefined ||
776
+ provider === "openai" ||
777
+ providerConfiguration?.["requires_openai_auth"] === true ||
778
+ (explicitChatgpt && providerKeyConfigured));
817
779
  modelProvider = output.modelProvider;
818
780
  let credentialConfig;
819
- authentication = scanAuthentication(processEnvironment, output.auth, provider, hasCommandAuth(config));
781
+ if (providerEnvKey !== undefined && !commandAuth && !explicitChatgpt) {
782
+ const key = environmentEntry(processEnvironment, providerEnvKey)?.trim();
783
+ if (!key && output.auth === "api-key") {
784
+ throw new AuthenticationRequiredError(`API-key authentication requires ${providerEnvKey}. Set a valid API key for the selected provider.`);
785
+ }
786
+ authentication = key
787
+ ? { method: "api_key", source: providerEnvKey, verified: false }
788
+ : { method: "stored_credentials", verified: false };
789
+ }
790
+ else {
791
+ authentication = scanAuthentication(processEnvironment, output.auth, provider, commandAuth);
792
+ }
820
793
  if (authentication.method === "stored_credentials" &&
821
794
  isExternalModelProvider(provider)) {
822
795
  const externalProvider = EXTERNAL_CODEX_PROVIDERS[provider];
823
- throw new AuthenticationRequiredError(`Set ${externalProvider.env_key} to run ${output.command} through ${externalProvider.name}.`);
796
+ throw new AuthenticationRequiredError(`Set ${providerEnvKey ?? externalProvider.env_key} to run ${output.command} through ${externalProvider.name}.`);
824
797
  }
825
798
  let selected = selectedScanEnvironment(processEnvironment, authentication.method === "command" ? "chatgpt" : output.auth, provider);
799
+ if (explicitChatgpt &&
800
+ !commandAuth &&
801
+ providerConfiguration !== undefined &&
802
+ providerKeyConfigured) {
803
+ if (providerEnvKey !== undefined) {
804
+ selected = Object.fromEntries(Object.entries(selected).filter(([name]) => process.platform === "win32"
805
+ ? name.toUpperCase() !== providerEnvKey.toUpperCase()
806
+ : name !== providerEnvKey));
807
+ }
808
+ // Native provider keys take precedence over stored authentication.
809
+ // Apply explicit ChatGPT selection to the home and CLI configuration.
810
+ const providerOverrides = typeof provider === "string"
811
+ ? overrides["model_providers"]?.[provider]
812
+ : undefined;
813
+ for (const selectedConfig of [
814
+ providerConfiguration,
815
+ providerOverrides,
816
+ ]) {
817
+ if (selectedConfig === undefined)
818
+ continue;
819
+ delete selectedConfig["env_key"];
820
+ delete selectedConfig["experimental_bearer_token"];
821
+ selectedConfig["requires_openai_auth"] = true;
822
+ }
823
+ args = [
824
+ ...args,
825
+ ...modelProviderConfigOverride(overrides).flatMap((value) => [
826
+ "--config",
827
+ value,
828
+ ]),
829
+ ];
830
+ }
826
831
  if (authentication.method === "stored_credentials" &&
827
832
  requiresOpenAiAuth) {
828
833
  const directory = await realpath(output.directory ?? output.appServer?.directory ?? process.cwd());
@@ -890,6 +895,12 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
890
895
  ];
891
896
  }
892
897
  }
898
+ if (authentication.method === "api_key" && providerEnvKey !== undefined) {
899
+ const providerKey = environmentEntry(processEnvironment, providerEnvKey);
900
+ if (providerKey !== undefined) {
901
+ selected = { ...selected, [providerEnvKey]: providerKey };
902
+ }
903
+ }
893
904
  if (output.appServer === undefined) {
894
905
  const authConfig = credentialConfig ?? (await readCodexHomeConfig(selected));
895
906
  args = [
@@ -1054,60 +1065,6 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
1054
1065
  await releaseCredentialHome?.();
1055
1066
  }
1056
1067
  }
1057
- async function writeCliOutput(output, value) {
1058
- const destination = new NodeWritable({
1059
- write(chunk, _encoding, callback) {
1060
- try {
1061
- if (output instanceof NodeWritable) {
1062
- output.write(chunk, callback);
1063
- }
1064
- else if (output.write(chunk)) {
1065
- callback();
1066
- }
1067
- else {
1068
- callback(new CodexSecurityError("The export stdout stream cannot report backpressure safely."));
1069
- }
1070
- }
1071
- catch (error) {
1072
- callback(error instanceof Error ? error : new Error(String(error)));
1073
- }
1074
- },
1075
- });
1076
- const forwardError = (error) => {
1077
- destination.destroy(error);
1078
- };
1079
- if (output instanceof NodeWritable)
1080
- output.once("error", forwardError);
1081
- try {
1082
- await pipeline(typeof value === "string" || value instanceof Uint8Array
1083
- ? [value]
1084
- : value, destination);
1085
- }
1086
- finally {
1087
- if (output instanceof NodeWritable) {
1088
- output.removeListener("error", forwardError);
1089
- }
1090
- }
1091
- }
1092
- export function exportEnvironment(environment = process.env) {
1093
- return pythonUtf8Environment(Object.fromEntries([
1094
- "PATH",
1095
- "Path",
1096
- "PATHEXT",
1097
- "SystemRoot",
1098
- "SYSTEMROOT",
1099
- "WINDIR",
1100
- "TMP",
1101
- "TEMP",
1102
- "TMPDIR",
1103
- "PYTHON",
1104
- "LANG",
1105
- "LC_ALL",
1106
- "LC_CTYPE",
1107
- ]
1108
- .filter((key) => environment[key] !== undefined)
1109
- .map((key) => [key, environment[key]])));
1110
- }
1111
1068
  export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES) {
1112
1069
  if (argv[0] === "dedupe" &&
1113
1070
  argv.includes("--records") &&
@@ -1119,10 +1076,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1119
1076
  return 2;
1120
1077
  }
1121
1078
  const controller = new AbortController();
1122
- const interrupt = () => controller.abort("SIGINT");
1123
- const terminate = () => controller.abort("SIGTERM");
1124
- dependencies.addSignalListener("SIGINT", interrupt);
1125
- dependencies.addSignalListener("SIGTERM", terminate);
1079
+ const removeSignals = listenForAbort(dependencies, controller);
1126
1080
  let exitCode;
1127
1081
  try {
1128
1082
  const code = await runRecordsProtocol(dependencies.recordsInput ?? process.stdin, output, controller.signal);
@@ -1134,8 +1088,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1134
1088
  : code;
1135
1089
  }
1136
1090
  finally {
1137
- dependencies.removeSignalListener("SIGINT", interrupt);
1138
- dependencies.removeSignalListener("SIGTERM", terminate);
1091
+ removeSignals();
1139
1092
  }
1140
1093
  // Protocol writes have flushed or been canceled. Node's stdout ignores destroy().
1141
1094
  if (output === process.stdout)
@@ -1170,7 +1123,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1170
1123
  : undefined;
1171
1124
  let exitCode = 0;
1172
1125
  let frameworkExit;
1173
- let frameworkOutput = "";
1126
+ const frameworkCapture = captureOutput();
1174
1127
  let streamedLogs;
1175
1128
  let renderedHistory;
1176
1129
  let renderedPublication;
@@ -1179,9 +1132,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1179
1132
  let patchStructuredError = false;
1180
1133
  let scanStructuredError = false;
1181
1134
  const runImport = (options) => runScanImport(options, errorOutput, dependencies);
1182
- const history = async (args, select = (value) => value) => {
1135
+ const history = async (args, select = (value) => value, pythonPath) => {
1183
1136
  try {
1184
- return await select(await dependencies.runWorkbench(args));
1137
+ return await select(await dependencies.runWorkbench(args, undefined, undefined, pythonPath));
1185
1138
  }
1186
1139
  catch (error) {
1187
1140
  errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
@@ -1189,7 +1142,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1189
1142
  throw error;
1190
1143
  }
1191
1144
  };
1192
- const latestScans = async (count = 1, status = "complete") => {
1145
+ const latestScans = async (count = 1, status = "complete", pythonPath) => {
1193
1146
  const result = await history([
1194
1147
  "list-scans",
1195
1148
  "--repository",
@@ -1205,10 +1158,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1205
1158
  : `At least ${count} ${kind} scans are required for the current repository.`);
1206
1159
  }
1207
1160
  return value;
1208
- });
1161
+ }, pythonPath);
1209
1162
  return result?.["scans"];
1210
1163
  };
1211
- const runMatching = async (operation) => {
1164
+ const runMatching = async (operation, selection) => {
1212
1165
  const controller = new AbortController();
1213
1166
  let firstSignalAt = 0;
1214
1167
  const cancel = (signal) => {
@@ -1228,14 +1181,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1228
1181
  const onInterrupt = () => cancel("SIGINT");
1229
1182
  const onTerminate = () => cancel("SIGTERM");
1230
1183
  const removeListeners = () => {
1231
- dependencies.removeSignalListener("SIGINT", onInterrupt);
1232
- dependencies.removeSignalListener("SIGTERM", onTerminate);
1184
+ signalHandlers(dependencies, "remove", onInterrupt, onTerminate);
1233
1185
  };
1234
- dependencies.addSignalListener("SIGINT", onInterrupt);
1235
- dependencies.addSignalListener("SIGTERM", onTerminate);
1186
+ signalHandlers(dependencies, "add", onInterrupt, onTerminate);
1236
1187
  let previousProgress = "";
1237
1188
  try {
1238
1189
  const result = await operation({
1190
+ ...(selection.model === undefined ? {} : { model: selection.model }),
1191
+ ...(selection.effort === undefined
1192
+ ? {}
1193
+ : { reasoningEffort: selection.effort }),
1239
1194
  environment: dependencies.environment,
1240
1195
  workingDirectory: dependencies.currentDirectory(),
1241
1196
  signal: controller.signal,
@@ -1256,8 +1211,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1256
1211
  }
1257
1212
  catch (error) {
1258
1213
  const interrupted = controller.signal.reason;
1259
- exitCode =
1260
- interrupted === "SIGINT" ? 130 : interrupted === "SIGTERM" ? 143 : 2;
1214
+ exitCode = interruptedExitCode(controller.signal) ?? 2;
1261
1215
  const message = interrupted === "SIGINT"
1262
1216
  ? "Finding matching canceled by Ctrl-C. Saved comparisons are preserved."
1263
1217
  : interrupted === "SIGTERM"
@@ -1270,7 +1224,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1270
1224
  removeListeners();
1271
1225
  }
1272
1226
  };
1273
- const matchScanPair = async (beforeId, afterId, force = false) => runMatching(async (options) => {
1227
+ const matchScanPair = async (beforeId, afterId, selection) => runMatching(async (options) => {
1274
1228
  const { matchingCached, matchingInputs, ...comparison } = await dependencies.runWorkbench([
1275
1229
  "compare-scans",
1276
1230
  "--before-scan-id",
@@ -1279,7 +1233,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1279
1233
  afterId,
1280
1234
  "--include-matching-inputs",
1281
1235
  ], undefined, options.signal);
1282
- if (matchingCached && !force)
1236
+ if (matchingCached && !selection.force)
1283
1237
  return comparison;
1284
1238
  const input = matchingInputs;
1285
1239
  const matching = await dependencies.matchFindings(input, options);
@@ -1292,7 +1246,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1292
1246
  afterId,
1293
1247
  "--matches-json-stdin",
1294
1248
  ], JSON.stringify(matching), options.signal);
1295
- });
1249
+ }, selection);
1296
1250
  const presentHistory = (result, command, format, settings = {}) => {
1297
1251
  if (result === undefined ||
1298
1252
  format !== "toon" ||
@@ -1312,7 +1266,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1312
1266
  return result;
1313
1267
  };
1314
1268
  const findingFeedback = Cli.create("findings", {
1315
- description: "Review and manage saved Codex Security findings.",
1269
+ description: "Review saved findings (default: list).",
1316
1270
  }).command("false-positive", {
1317
1271
  description: "Mark a finding as a false positive for future scans.",
1318
1272
  destructive: true,
@@ -1370,7 +1324,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1370
1324
  },
1371
1325
  });
1372
1326
  const scanHistory = Cli.create("scans", {
1373
- description: "List, inspect, rerun, match, and compare saved Codex Security scans.",
1327
+ description: "Review saved scans (default: list).",
1374
1328
  })
1375
1329
  .command("list", {
1376
1330
  description: "List saved scans for a repository or scan root.",
@@ -1424,6 +1378,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1424
1378
  .default(false)
1425
1379
  .describe("Show findings linked across previous scans."),
1426
1380
  }),
1381
+ examples: [
1382
+ { args: {}, description: "Show the latest completed scan." },
1383
+ {
1384
+ args: { scanId: "scan_abc123" },
1385
+ description: "Show a saved scan by ID or unique prefix.",
1386
+ },
1387
+ ],
1427
1388
  output: z.record(z.string(), z.unknown()).optional(),
1428
1389
  async run({ args, format, options }) {
1429
1390
  const scanId = args.scanId ?? (await latestScans())?.[0]?.scanId;
@@ -1449,6 +1410,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1449
1410
  .optional()
1450
1411
  .describe("Scan identifier or unique prefix (default: latest)."),
1451
1412
  }),
1413
+ examples: [
1414
+ { args: {}, description: "Show activity from the latest scan." },
1415
+ {
1416
+ args: { scanId: "scan_abc123" },
1417
+ description: "Show activity from a saved scan.",
1418
+ },
1419
+ ],
1452
1420
  output: z.record(z.string(), z.unknown()).optional(),
1453
1421
  async run({ args, format }) {
1454
1422
  const scanId = args.scanId ?? (await latestScans(1, "any"))?.[0]?.scanId;
@@ -1478,7 +1446,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1478
1446
  verbose: z
1479
1447
  .boolean()
1480
1448
  .default(false)
1481
- .describe("Print scan diagnostics to stderr."),
1449
+ .describe("Print additional scan diagnostics to stderr."),
1482
1450
  }),
1483
1451
  output: z.record(z.string(), z.unknown()).optional(),
1484
1452
  async run({ args, error: incurError, options }) {
@@ -1550,10 +1518,15 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1550
1518
  verbose: z
1551
1519
  .boolean()
1552
1520
  .default(false)
1553
- .describe("Print scan diagnostics to stderr."),
1521
+ .describe("Print additional scan diagnostics to stderr."),
1554
1522
  }),
1555
1523
  output: z.record(z.string(), z.unknown()).optional(),
1556
- async run({ args, error: incurError, options }) {
1524
+ async run({ args, error: incurError, format, options }) {
1525
+ if (format === "md") {
1526
+ errorOutput.write("codex-security: Markdown output is not supported for scan results.\n");
1527
+ exitCode = 2;
1528
+ return;
1529
+ }
1557
1530
  const scanId = args.scanId ?? (await latestScans())?.[0]?.scanId;
1558
1531
  if (scanId === undefined)
1559
1532
  return;
@@ -1564,8 +1537,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1564
1537
  "--scan-id",
1565
1538
  scanId,
1566
1539
  ]);
1567
- if (recipe !== undefined &&
1568
- isJsonObject(recipe) &&
1540
+ if (isJsonObject(recipe) &&
1569
1541
  recipe["import"] !== undefined &&
1570
1542
  isJsonObject(recipe["import"])) {
1571
1543
  if (options.validationPromptFile !== undefined ||
@@ -1578,8 +1550,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1578
1550
  const imported = recipe["import"];
1579
1551
  const sourcePath = imported["sourcePath"];
1580
1552
  const format = imported["format"];
1581
- if (typeof sourcePath !== "string" ||
1582
- sourcePath.length === 0 ||
1553
+ if (!isNonEmptyString(sourcePath) ||
1583
1554
  (format !== "csv" && format !== "json")) {
1584
1555
  throw new CodexSecurityError("The saved scan recipe contains invalid import settings.");
1585
1556
  }
@@ -1619,7 +1590,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1619
1590
  exitCode,
1620
1591
  });
1621
1592
  }
1622
- const outcome = await runScan(scanArguments, errorOutput, dependencies);
1593
+ const outcome = await runScan(scanArguments, errorOutput, dependencies, format !== "json" && format !== "jsonl");
1623
1594
  exitCode = outcome.exitCode;
1624
1595
  if (outcome.error !== undefined) {
1625
1596
  return incurError({
@@ -1656,13 +1627,14 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1656
1627
  .boolean()
1657
1628
  .default(false)
1658
1629
  .describe("Recompute an existing semantic finding comparison."),
1630
+ ...MATCHING_MODEL_OPTIONS.shape,
1659
1631
  }),
1660
1632
  output: z.record(z.string(), z.unknown()).optional(),
1661
1633
  async run({ args, format, options }) {
1662
1634
  if (options.all) {
1663
- return presentHistory(await runMatching((matchingOptions) => matchAllScans(dependencies, options.force, matchingOptions)), "match-all", format);
1635
+ return presentHistory(await runMatching((matchingOptions) => matchAllScans(dependencies, options.force, matchingOptions), options), "match-all", format);
1664
1636
  }
1665
- return presentHistory(await matchScanPair(args.beforeId, args.afterId, options.force), "compare", format);
1637
+ return presentHistory(await matchScanPair(args.beforeId, args.afterId, options), "compare", format);
1666
1638
  },
1667
1639
  })
1668
1640
  .command("compare", {
@@ -1681,8 +1653,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1681
1653
  .optional()
1682
1654
  .describe("Later saved scan identifier (default: latest completed)."),
1683
1655
  }),
1656
+ options: MATCHING_MODEL_OPTIONS,
1684
1657
  output: z.record(z.string(), z.unknown()).optional(),
1685
- async run({ args, format }) {
1658
+ async run({ args, format, options }) {
1686
1659
  let { beforeId, afterId } = args;
1687
1660
  if (beforeId === undefined) {
1688
1661
  const scans = await latestScans(2);
@@ -1696,7 +1669,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1696
1669
  if (afterId === undefined)
1697
1670
  return;
1698
1671
  }
1699
- return presentHistory(await matchScanPair(beforeId, afterId), "compare", format);
1672
+ return presentHistory(await matchScanPair(beforeId, afterId, options), "compare", format);
1700
1673
  },
1701
1674
  });
1702
1675
  const reportPublicationError = (error, signal) => {
@@ -1704,7 +1677,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1704
1677
  const reason = signal === "SIGINT"
1705
1678
  ? "Publication canceled by Ctrl-C."
1706
1679
  : "Publication terminated by SIGTERM.";
1707
- const recovery = error === signal ? "" : ` ${diagnosticValue(safeErrorMessage(error))}`;
1680
+ const recovery = error === signal ? "" : ` ${diagnosticValue(error)}`;
1708
1681
  errorOutput.write(`codex-security: ${reason}${recovery}\n`);
1709
1682
  exitCode = signal === "SIGINT" ? 130 : 143;
1710
1683
  }
@@ -1716,7 +1689,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1716
1689
  const publication = Cli.create("publish", {
1717
1690
  description: "Publish Codex Security findings.",
1718
1691
  }).command("scan", {
1719
- description: "Publish findings from a completed scan or CSV.",
1692
+ description: "Publish findings from a completed scan, or a CSV for internal publication.",
1693
+ hint: "Examples:\n" +
1694
+ " codex-security publish scan --to linear --scan latest --linear-team TEAM_ID --dry-run\n" +
1695
+ " codex-security publish scan --to custom --scan latest --findings-url http://localhost:3000",
1720
1696
  destructive: true,
1721
1697
  mcp: false,
1722
1698
  args: z.object({
@@ -1747,7 +1723,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1747
1723
  .refine((value) => value === "linear" || value === "cloud" || value === "custom", {
1748
1724
  message: "Unsupported publication destination. Use --to linear or --to custom.",
1749
1725
  })
1750
- .describe("Publication destination (linear or custom)."),
1726
+ .describe("Required publication destination: linear or custom."),
1751
1727
  findingsUrl: optionValue("--findings-url")
1752
1728
  .url()
1753
1729
  .optional()
@@ -1758,7 +1734,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1758
1734
  .describe("Preview the findings without publishing them."),
1759
1735
  csv: optionValue("--csv")
1760
1736
  .optional()
1761
- .describe("Findings CSV to publish instead of a completed scan."),
1737
+ .describe("Findings CSV for internal publication; not supported with linear or custom."),
1762
1738
  skipExisting: z
1763
1739
  .boolean()
1764
1740
  .default(false)
@@ -1801,7 +1777,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1801
1777
  : "Publication terminated by SIGTERM.";
1802
1778
  const recovery = error === undefined || error === signal
1803
1779
  ? ""
1804
- : ` ${diagnosticValue(safeErrorMessage(error))}`;
1780
+ : ` ${diagnosticValue(error)}`;
1805
1781
  errorOutput.write(`codex-security: ${reason}${recovery}\n`);
1806
1782
  exitCode = signal === "SIGINT" ? 130 : 143;
1807
1783
  return true;
@@ -1811,8 +1787,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1811
1787
  const removeSignalListeners = () => {
1812
1788
  if (!observingSignals)
1813
1789
  return;
1814
- dependencies.removeSignalListener("SIGINT", onInterrupt);
1815
- dependencies.removeSignalListener("SIGTERM", onTerminate);
1790
+ signalHandlers(dependencies, "remove", onInterrupt, onTerminate);
1816
1791
  observingSignals = false;
1817
1792
  };
1818
1793
  try {
@@ -1871,8 +1846,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1871
1846
  ? publicationDestination({ ...options, to: "linear" }, dependencies.environment)
1872
1847
  : undefined;
1873
1848
  if (options.to !== "linear") {
1874
- dependencies.addSignalListener("SIGINT", onInterrupt);
1875
- dependencies.addSignalListener("SIGTERM", onTerminate);
1849
+ signalHandlers(dependencies, "add", onInterrupt, onTerminate);
1876
1850
  observingSignals = true;
1877
1851
  }
1878
1852
  if (csvPath !== undefined) {
@@ -1897,12 +1871,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1897
1871
  let scanDir = selectedScans[0]?.scanDir;
1898
1872
  let publicationRepository = scanDir === undefined ? "scan" : basename(scanDir);
1899
1873
  if (scanDir === undefined) {
1900
- const prompt = dependencies.publishPrompt ??
1901
- createBulkScanDiscoveryDependencies({
1902
- output: errorOutput,
1903
- now: dependencies.now,
1904
- currentDirectory: dependencies.currentDirectory,
1905
- }).prompt;
1874
+ const prompt = dependencies.publishPrompt ?? createTerminalPrompt(errorOutput);
1906
1875
  if (!prompt.isInteractive()) {
1907
1876
  throw new CodexSecurityError(`Interactive scan selection requires a terminal. Select a saved scan: codex-security publish scan --scan SCAN_ID --to ${options.to}${options.to === "linear" ? " --linear-team TEAM_ID" : ""}.`);
1908
1877
  }
@@ -1919,14 +1888,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1919
1888
  if (!isJsonObject(scan))
1920
1889
  return undefined;
1921
1890
  const directory = scan["scanDir"];
1922
- if (typeof directory !== "string" || directory.length === 0) {
1891
+ if (!isNonEmptyString(directory)) {
1923
1892
  return undefined;
1924
1893
  }
1925
1894
  const metadata = await lstat(resolveCliPath(currentDirectory, directory)).catch(() => undefined);
1926
- return metadata?.isDirectory() === true &&
1927
- !metadata.isSymbolicLink()
1928
- ? scan
1929
- : undefined;
1895
+ return metadata?.isDirectory() === true ? scan : undefined;
1930
1896
  }))).filter((scan) => scan !== undefined);
1931
1897
  const now = dependencies.now();
1932
1898
  const emphasizeRepository = errorOutput.isTTY === true &&
@@ -1940,11 +1906,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1940
1906
  const progress = scan["progress"];
1941
1907
  const scanId = scan["scanId"];
1942
1908
  const directory = scan["scanDir"];
1943
- if (typeof scanId !== "string" ||
1944
- scanId.length === 0 ||
1945
- typeof directory !== "string" ||
1946
- directory.length === 0 ||
1947
- progress === undefined ||
1909
+ if (!isNonEmptyString(scanId) ||
1910
+ !isNonEmptyString(directory) ||
1948
1911
  !isJsonObject(progress) ||
1949
1912
  progress["status"] !== "complete") {
1950
1913
  return [];
@@ -2078,7 +2041,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2078
2041
  cloudBatch.results.push({ scanDir: directory, ...result });
2079
2042
  }
2080
2043
  catch (error) {
2081
- const message = safeErrorMessage(error);
2044
+ const message = errorMessage(error);
2082
2045
  cloudBatch.failed.push({
2083
2046
  scanDir: directory,
2084
2047
  ...(scanId === undefined ? {} : { scanId }),
@@ -2087,7 +2050,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2087
2050
  if (controller.signal.aborted)
2088
2051
  throw error;
2089
2052
  exitCode = 2;
2090
- errorOutput.write(`codex-security: ${diagnosticValue(safeErrorMessage(scanId ?? directory))}: ${diagnosticValue(message)}\n`);
2053
+ errorOutput.write(`codex-security: ${diagnosticValue(scanId ?? directory)}: ${diagnosticValue(message)}\n`);
2091
2054
  }
2092
2055
  }
2093
2056
  return cloudBatch;
@@ -2119,8 +2082,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2119
2082
  }
2120
2083
  const progress = new PublicationProgressPresenter(errorOutput, dependencies, publicationRepository);
2121
2084
  presentation = progress;
2122
- dependencies.addSignalListener("SIGINT", onInterrupt);
2123
- dependencies.addSignalListener("SIGTERM", onTerminate);
2085
+ signalHandlers(dependencies, "add", onInterrupt, onTerminate);
2124
2086
  observingSignals = true;
2125
2087
  if (!options.dryRun) {
2126
2088
  progress.start();
@@ -2155,7 +2117,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2155
2117
  for (const warning of result.warnings) {
2156
2118
  if (typeof warning !== "string")
2157
2119
  continue;
2158
- errorOutput.write(`codex-security: ${diagnosticValue(safeErrorMessage(warning))}\n`);
2120
+ errorOutput.write(`codex-security: ${diagnosticValue(warning)}\n`);
2159
2121
  }
2160
2122
  }
2161
2123
  if (format === "toon" &&
@@ -2170,7 +2132,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2170
2132
  }
2171
2133
  catch (error) {
2172
2134
  if (!finishCancellation(error)) {
2173
- errorOutput.write(`codex-security: ${options.to === "cloud" ? safeErrorMessage(error) : errorMessage(error)}\n`);
2135
+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
2174
2136
  exitCode = 2;
2175
2137
  }
2176
2138
  return cloudBatch;
@@ -2190,10 +2152,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2190
2152
  output: z.record(z.string(), z.unknown()).optional(),
2191
2153
  async run({ args, options }) {
2192
2154
  const controller = new AbortController();
2193
- const onInterrupt = () => controller.abort("SIGINT");
2194
- const onTerminate = () => controller.abort("SIGTERM");
2195
- dependencies.addSignalListener("SIGINT", onInterrupt);
2196
- dependencies.addSignalListener("SIGTERM", onTerminate);
2155
+ const removeSignals = listenForAbort(dependencies, controller);
2197
2156
  try {
2198
2157
  const result = await (dependencies.checkScanPublication ?? checkScanPublication)(resolve(dependencies.currentDirectory(), args.scanDir), {
2199
2158
  ...publicationDestination(options, dependencies.environment),
@@ -2207,15 +2166,15 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2207
2166
  return undefined;
2208
2167
  }
2209
2168
  finally {
2210
- dependencies.removeSignalListener("SIGINT", onInterrupt);
2211
- dependencies.removeSignalListener("SIGTERM", onTerminate);
2169
+ removeSignals();
2212
2170
  }
2213
2171
  },
2214
2172
  });
2215
2173
  const imports = Cli.create("import", {
2216
- description: "Read upstream findings for local validation or triage.",
2174
+ description: "Read GitHub code scanning alerts.",
2217
2175
  }).command("github", {
2218
- description: "Import GitHub code scanning alerts without changing GitHub.",
2176
+ description: "Read GitHub code scanning alerts without changing GitHub.",
2177
+ hint: "To save CSV or JSON findings as a local scan, use codex-security scan import --help.",
2219
2178
  destructive: false,
2220
2179
  mcp: false,
2221
2180
  args: z.object({
@@ -2248,10 +2207,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2248
2207
  .optional(),
2249
2208
  async run({ args, options }) {
2250
2209
  const controller = new AbortController();
2251
- const onInterrupt = () => controller.abort("SIGINT");
2252
- const onTerminate = () => controller.abort("SIGTERM");
2253
- dependencies.addSignalListener("SIGINT", onInterrupt);
2254
- dependencies.addSignalListener("SIGTERM", onTerminate);
2210
+ const removeSignals = listenForAbort(dependencies, controller);
2255
2211
  try {
2256
2212
  return await (dependencies.importGitHubAlerts ?? importGitHubCodeScanningAlerts)({
2257
2213
  repository: args.repository,
@@ -2272,18 +2228,17 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2272
2228
  }
2273
2229
  else {
2274
2230
  exitCode = 2;
2275
- errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
2231
+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
2276
2232
  }
2277
2233
  return undefined;
2278
2234
  }
2279
2235
  finally {
2280
- dependencies.removeSignalListener("SIGINT", onInterrupt);
2281
- dependencies.removeSignalListener("SIGTERM", onTerminate);
2236
+ removeSignals();
2282
2237
  }
2283
2238
  },
2284
2239
  });
2285
2240
  const cli = Cli.create("codex-security", {
2286
- description: "Draft security policies; run, import, validate, patch, verify fixes, export, and publish Codex Security findings.",
2241
+ description: "Find, review, and fix security issues in your code.",
2287
2242
  version: VERSION,
2288
2243
  mcp: {
2289
2244
  command: "npx --yes @openai/codex-security --mcp",
@@ -2292,7 +2247,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2292
2247
  },
2293
2248
  })
2294
2249
  .command("policy", {
2295
- description: "Draft SECURITY.md guidance for future scans and owner review.",
2250
+ description: "Draft SECURITY.md guidance for review.",
2296
2251
  destructive: true,
2297
2252
  mcp: false,
2298
2253
  args: z.object({
@@ -2323,27 +2278,15 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2323
2278
  auth: z
2324
2279
  .enum(["auto", "chatgpt", "api-key"])
2325
2280
  .default("auto")
2326
- .describe("Select ChatGPT, API-key, or automatic authentication."),
2327
- model: optionValue("--model")
2328
- .optional()
2329
- .describe(`Model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`),
2330
- effort: effortOption(),
2281
+ .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
2282
+ ...MODEL_OPTIONS.shape,
2331
2283
  provider: PROVIDER_OPTION.describe("Inference provider for policy generation."),
2332
2284
  maxCost: z
2333
2285
  .number()
2334
2286
  .positive()
2335
2287
  .optional()
2336
2288
  .describe("Stop when estimated total USD cost across all three stages exceeds AMOUNT."),
2337
- pluginPath: optionValue("--plugin-path")
2338
- .optional()
2339
- .describe(PLUGIN_PATH_DESCRIPTION),
2340
- python: optionValue("--python")
2341
- .optional()
2342
- .describe(PYTHON_PATH_DESCRIPTION),
2343
- codex: z
2344
- .array(optionValue("--codex"))
2345
- .default([])
2346
- .describe(CODEX_OVERRIDE_DESCRIPTION),
2289
+ ...RUNTIME_OPTION_SCHEMAS,
2347
2290
  }),
2348
2291
  examples: [
2349
2292
  { args: { repository: "." } },
@@ -2404,11 +2347,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2404
2347
  signal,
2405
2348
  }, errorOutput, dependencies),
2406
2349
  prompt: dependencies.policyPrompt ??
2407
- createBulkScanDiscoveryDependencies({
2408
- output: errorOutput,
2409
- now: dependencies.now,
2410
- currentDirectory: dependencies.currentDirectory,
2411
- }).prompt,
2350
+ createTerminalPrompt(errorOutput),
2412
2351
  environment: dependencies.environment,
2413
2352
  errorOutput,
2414
2353
  now: dependencies.now,
@@ -2434,9 +2373,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2434
2373
  : outcome.data;
2435
2374
  }
2436
2375
  catch (error) {
2437
- const message = safeErrorMessage(error);
2376
+ const message = errorMessage(error);
2438
2377
  try {
2439
- errorOutput.write(`codex-security: ${message}\n`);
2378
+ errorOutput.write(`codex-security: ${diagnosticValue(message)}\n`);
2440
2379
  }
2441
2380
  catch { }
2442
2381
  return fail(message, 2);
@@ -2444,8 +2383,14 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2444
2383
  },
2445
2384
  })
2446
2385
  .command("scan", {
2447
- description: "Run a Codex Security scan.",
2448
- hint: "Import existing findings without security analysis:\n" +
2386
+ description: "Scan a repository, selected paths, or Git changes.",
2387
+ hint: "Examples:\n" +
2388
+ " codex-security scan .\n" +
2389
+ " codex-security scan . --path src --path tests\n" +
2390
+ " codex-security scan . --working-tree\n" +
2391
+ " codex-security scan . --diff origin/main\n" +
2392
+ " codex-security scan . --mode deep\n\n" +
2393
+ "Import existing findings without security analysis:\n" +
2449
2394
  " codex-security scan import --csv findings.csv\n" +
2450
2395
  " codex-security scan import --json findings.json\n" +
2451
2396
  "Use ./import to scan a repository named import.",
@@ -2464,11 +2409,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2464
2409
  workflowId: optionValue("--workflow-id")
2465
2410
  .optional()
2466
2411
  .describe("Reuse completed work in the named local findings workflow."),
2412
+ cyberAccessProgram: ScanSettingsSchema.shape.cyberAccessProgram,
2467
2413
  auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication (default: auto)."),
2468
2414
  verbose: z
2469
2415
  .boolean()
2470
2416
  .default(false)
2471
- .describe("Print scan diagnostics to stderr."),
2417
+ .describe("Print additional scan diagnostics to stderr."),
2472
2418
  safetyIdentifier: optionValue("--safety-identifier")
2473
2419
  .optional()
2474
2420
  .describe("Stable hashed end-user ID for this scan's model requests (1–64 characters)."),
@@ -2507,10 +2453,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2507
2453
  .describe("Git base ref for --working-tree (default: HEAD)."),
2508
2454
  mode: ScanSettingsSchema.shape.mode.describe("Scan mode (default: standard); deep supports repository and path targets."),
2509
2455
  ...DEEP_SCAN_OPTION_SCHEMAS,
2510
- model: optionValue("--model")
2511
- .optional()
2512
- .describe(`OpenAI model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`),
2513
- effort: effortOption(),
2456
+ ...modelOptions(`OpenAI model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`).shape,
2514
2457
  provider: PROVIDER_OPTION,
2515
2458
  outputDir: optionValue("--output-dir")
2516
2459
  .optional()
@@ -2519,16 +2462,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2519
2462
  .boolean()
2520
2463
  .default(false)
2521
2464
  .describe("Archive existing results; requires --output-dir."),
2522
- pluginPath: optionValue("--plugin-path")
2523
- .optional()
2524
- .describe(PLUGIN_PATH_DESCRIPTION),
2525
- python: optionValue("--python")
2526
- .optional()
2527
- .describe(PYTHON_PATH_DESCRIPTION),
2528
- codex: z
2529
- .array(optionValue("--codex"))
2530
- .default([])
2531
- .describe(CODEX_OVERRIDE_DESCRIPTION),
2465
+ ...RUNTIME_OPTION_SCHEMAS,
2532
2466
  failOnSeverity: FailureSeveritySchema.optional().describe("Exit 1 for findings at or above LEVEL."),
2533
2467
  patch: z
2534
2468
  .boolean()
@@ -2538,7 +2472,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2538
2472
  .enum(REPORTABLE_SEVERITIES)
2539
2473
  .optional()
2540
2474
  .describe("Patch findings at or above LEVEL; requires --patch."),
2541
- createPr: CREATE_PR_OPTION,
2475
+ createPr: CREATE_PR_OPTION.describe("Create a draft pull request or merge request after verified patches; requires --patch."),
2542
2476
  maxCost: ScanSettingsSchema.shape.maxCostUsd.describe("Stop above AMOUNT in estimated USD; the dashboard offers increases near the limit."),
2543
2477
  showCost: SHOW_COST_OPTION,
2544
2478
  headless: z
@@ -2566,28 +2500,6 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2566
2500
  .refine((options) => !options.mock || (!options.dryRun && !options.patch), {
2567
2501
  message: "--mock cannot be combined with --dry-run or --patch.",
2568
2502
  }),
2569
- examples: [
2570
- { args: { repository: "." } },
2571
- {
2572
- args: { repository: "." },
2573
- options: { config: "codex-security.yaml" },
2574
- },
2575
- { args: { repository: "." }, options: { model: "gpt-5.6-terra" } },
2576
- {
2577
- args: { repository: "." },
2578
- options: { model: "gpt-5.6-terra", effort: "high" },
2579
- },
2580
- { args: { repository: "." }, options: { path: ["src"] } },
2581
- { args: { repository: "." }, options: { diff: "origin/main" } },
2582
- {
2583
- args: { repository: "." },
2584
- options: {
2585
- codex: [
2586
- "features.multi_agent_v2.max_concurrent_threads_per_session=4",
2587
- ],
2588
- },
2589
- },
2590
- ],
2591
2503
  output: scanOutputSchema,
2592
2504
  async run({ args, error: incurError, format, options }) {
2593
2505
  if (format === "md") {
@@ -2607,19 +2519,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2607
2519
  base: options.base,
2608
2520
  });
2609
2521
  const { config, options: settings, projectConfig: provenance, } = resolveScanSettings(project, {
2610
- auth: options.auth,
2522
+ ...pickScanSettings(options),
2611
2523
  target: scope.target,
2612
2524
  knowledgeBasePaths: options.knowledgeBase,
2613
- scanPromptFile: options.scanPromptFile,
2614
- validationPromptFile: options.validationPromptFile,
2615
- postScanPromptFile: options.postScanPromptFile,
2616
- mode: options.mode,
2617
- workers: options.workers,
2618
- subagents: options.subagents,
2619
- stopAfterNoNew: options.stopAfterNoNew,
2620
- maxDiscoveryRuns: options.maxDiscoveryRuns,
2621
- maxTimeHours: options.maxTimeHours,
2622
- outputDir: options.outputDir,
2623
2525
  failureSeverity: options.failOnSeverity,
2624
2526
  maxCostUsd: options.maxCost,
2625
2527
  codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider, project?.input.codex),
@@ -2655,7 +2557,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2655
2557
  exitCode = outcome.exitCode;
2656
2558
  if (outcome.error !== undefined) {
2657
2559
  if (format === "json" || format === "jsonl") {
2658
- const message = safeErrorMessage(outcome.error);
2560
+ const message = errorMessage(outcome.error);
2659
2561
  if (!argv.includes("--full-output"))
2660
2562
  return { status: "failed", code: "SCAN_FAILED", message };
2661
2563
  // Incur would wrap returned data in an ok: true envelope.
@@ -2677,7 +2579,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2677
2579
  },
2678
2580
  })
2679
2581
  .command("install-hook", {
2680
- description: "Install a Git pre-commit security scan.",
2582
+ description: "Install an advisory Git pre-commit check.",
2583
+ hint: "Require a passing scan in CI to enforce a scan before merging.",
2681
2584
  destructive: true,
2682
2585
  mcp: false,
2683
2586
  args: z.object({
@@ -2744,8 +2647,54 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2744
2647
  .command(scanHistory)
2745
2648
  .command(findingFeedback)
2746
2649
  .command(publication)
2650
+ .command("suggest-owners", {
2651
+ description: "Suggest finding owners from source and Git history.",
2652
+ destructive: false,
2653
+ mcp: false,
2654
+ args: z.object({
2655
+ findings: z
2656
+ .string()
2657
+ .min(1)
2658
+ .describe("Codex Security findings JSON file."),
2659
+ }),
2660
+ options: z.object({
2661
+ sourceRoot: optionValue("--source-root")
2662
+ .optional()
2663
+ .describe("Local Git repository (default: current directory); analyzes committed HEAD."),
2664
+ ...modelOptions("Model for owner suggestions (default: Codex Security model).", "Reasoning effort (default: Codex Security effort).").shape,
2665
+ }),
2666
+ output: z.record(z.string(), z.unknown()).optional(),
2667
+ async run({ args, options }) {
2668
+ const controller = new AbortController();
2669
+ const removeSignals = listenForAbort(dependencies, controller);
2670
+ try {
2671
+ const directory = dependencies.currentDirectory();
2672
+ const repository = resolveCliPath(directory, options.sourceRoot ?? ".");
2673
+ const findings = await parseImportedFindings(await readRegularInputFile(resolveCliPath(directory, args.findings), repository), "json", await bundledPluginRoot());
2674
+ const result = await (dependencies.suggestOwners ?? suggestOwnersInternal)(repository, findings, {
2675
+ environment: dependencies.environment,
2676
+ signal: controller.signal,
2677
+ model: options.model,
2678
+ reasoningEffort: options.effort,
2679
+ }, "cli");
2680
+ if (result.results.some(({ status }) => status === "error"))
2681
+ exitCode = 2;
2682
+ return { ...result };
2683
+ }
2684
+ catch (error) {
2685
+ const signal = controller.signal.reason;
2686
+ errorOutput.write(`codex-security: ${signal === "SIGINT" || signal === "SIGTERM" ? "Owner suggestions canceled." : diagnosticValue(error)}\n`);
2687
+ exitCode = interruptedExitCode(controller.signal) ?? 2;
2688
+ return undefined;
2689
+ }
2690
+ finally {
2691
+ removeSignals();
2692
+ }
2693
+ },
2694
+ })
2747
2695
  .command("classify-severity", {
2748
- description: "Classify saved findings using an optional rubric and save a separate severity assessment.",
2696
+ description: "Assess severity for saved findings.",
2697
+ hint: "Use --rubric to classify findings with a policy. The assessment is saved separately.",
2749
2698
  destructive: true,
2750
2699
  mcp: false,
2751
2700
  options: z.object({
@@ -2770,18 +2719,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2770
2719
  .array(optionValue("--finding-id"))
2771
2720
  .default([])
2772
2721
  .describe("Classify only this finding ID; repeat to select deduplicated findings."),
2773
- model: optionValue("--model")
2774
- .optional()
2775
- .describe("Model for rubric classification."),
2776
- effort: effortOption().describe("Classification reasoning effort (default: medium)."),
2722
+ ...modelOptions("Model for rubric classification.", "Classification reasoning effort (default: medium).").shape,
2777
2723
  }),
2778
2724
  output: z.record(z.string(), z.unknown()).optional(),
2779
2725
  async run({ options }) {
2780
2726
  const controller = new AbortController();
2781
- const onInterrupt = () => controller.abort("SIGINT");
2782
- const onTerminate = () => controller.abort("SIGTERM");
2783
- dependencies.addSignalListener("SIGINT", onInterrupt);
2784
- dependencies.addSignalListener("SIGTERM", onTerminate);
2727
+ const removeSignals = listenForAbort(dependencies, controller);
2785
2728
  try {
2786
2729
  if ((options.scan === undefined) ===
2787
2730
  (options.scanDir === undefined)) {
@@ -2810,18 +2753,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2810
2753
  }
2811
2754
  catch (error) {
2812
2755
  const signal = controller.signal.reason;
2813
- errorOutput.write(`codex-security: ${signal === "SIGINT" || signal === "SIGTERM" ? "Severity classification canceled." : safeErrorMessage(error)}\n`);
2814
- exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2;
2756
+ errorOutput.write(`codex-security: ${signal === "SIGINT" || signal === "SIGTERM" ? "Severity classification canceled." : diagnosticValue(error)}\n`);
2757
+ exitCode = interruptedExitCode(controller.signal) ?? 2;
2815
2758
  return undefined;
2816
2759
  }
2817
2760
  finally {
2818
- dependencies.removeSignalListener("SIGINT", onInterrupt);
2819
- dependencies.removeSignalListener("SIGTERM", onTerminate);
2761
+ removeSignals();
2820
2762
  }
2821
2763
  },
2822
2764
  })
2823
2765
  .command("dedupe", {
2824
- description: "Dedupe a saved scan, or use --records for host-provided reviews over JSON-RPC.",
2766
+ description: "Identify duplicate findings in a saved scan.",
2767
+ hint: "Use --records alone for host-provided reviews over JSON-RPC.",
2825
2768
  destructive: true,
2826
2769
  mcp: false,
2827
2770
  options: z.object({
@@ -2872,10 +2815,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2872
2815
  if (options.records)
2873
2816
  throw new CodexSecurityError("Use dedupe --records alone.");
2874
2817
  const controller = new AbortController();
2875
- const onInterrupt = () => controller.abort("SIGINT");
2876
- const onTerminate = () => controller.abort("SIGTERM");
2877
- dependencies.addSignalListener("SIGINT", onInterrupt);
2878
- dependencies.addSignalListener("SIGTERM", onTerminate);
2818
+ const removeSignals = listenForAbort(dependencies, controller);
2879
2819
  try {
2880
2820
  if (options.findingsUrl === undefined)
2881
2821
  throw new CodexSecurityError("Saved-scan deduplication requires --findings-url.");
@@ -2913,19 +2853,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2913
2853
  const signal = controller.signal.reason;
2914
2854
  errorOutput.write(`codex-security: ${signal === "SIGINT" || signal === "SIGTERM"
2915
2855
  ? "Deduplication canceled. Findings are unchanged."
2916
- : safeErrorMessage(error)}\n`);
2917
- exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2;
2856
+ : diagnosticValue(error)}\n`);
2857
+ exitCode = interruptedExitCode(controller.signal) ?? 2;
2918
2858
  return undefined;
2919
2859
  }
2920
2860
  finally {
2921
- dependencies.removeSignalListener("SIGINT", onInterrupt);
2922
- dependencies.removeSignalListener("SIGTERM", onTerminate);
2861
+ removeSignals();
2923
2862
  }
2924
2863
  },
2925
2864
  })
2926
2865
  .command(imports)
2927
2866
  .command("scan-components", {
2928
- description: "Run standard scans for project components and combine the results.",
2867
+ description: "Scan project components and combine results.",
2929
2868
  destructive: true,
2930
2869
  mcp: false,
2931
2870
  alias: { config: "c" },
@@ -2939,7 +2878,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2939
2878
  options: z
2940
2879
  .object({
2941
2880
  config: PROJECT_CONFIG_OPTION,
2942
- auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
2881
+ cyberAccessProgram: ScanSettingsSchema.shape.cyberAccessProgram,
2882
+ auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication (default: auto)."),
2943
2883
  component: z
2944
2884
  .array(optionValue("--component"))
2945
2885
  .default([])
@@ -2979,10 +2919,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2979
2919
  postScanPromptFile: optionValue("--post-scan-prompt-file")
2980
2920
  .optional()
2981
2921
  .describe("Run FILE after each scan, including failures."),
2982
- model: optionValue("--model")
2983
- .optional()
2984
- .describe("Model for planning and component scans."),
2985
- effort: effortOption(),
2922
+ ...modelOptions("Model for planning and component scans.").shape,
2986
2923
  provider: PROVIDER_OPTION,
2987
2924
  maxCost: z
2988
2925
  .number()
@@ -2990,16 +2927,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
2990
2927
  .optional()
2991
2928
  .describe("Stop each component scan if estimated USD cost exceeds AMOUNT."),
2992
2929
  showCost: SHOW_COST_OPTION,
2993
- pluginPath: optionValue("--plugin-path")
2994
- .optional()
2995
- .describe(PLUGIN_PATH_DESCRIPTION),
2996
- python: optionValue("--python")
2997
- .optional()
2998
- .describe(PYTHON_PATH_DESCRIPTION),
2999
- codex: z
3000
- .array(optionValue("--codex"))
3001
- .default([])
3002
- .describe(CODEX_OVERRIDE_DESCRIPTION),
2930
+ ...RUNTIME_OPTION_SCHEMAS,
3003
2931
  })
3004
2932
  .refine((options) => Number(options.component.length > 0) +
3005
2933
  Number(options.componentsFile !== undefined) +
@@ -3020,23 +2948,14 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3020
2948
  };
3021
2949
  const onInterrupt = () => controller.abort("SIGINT");
3022
2950
  const onTerminate = () => controller.abort("SIGTERM");
3023
- const interruptedExitCode = () => controller.signal.reason === "SIGINT"
3024
- ? 130
3025
- : controller.signal.reason === "SIGTERM"
3026
- ? 143
3027
- : undefined;
3028
- dependencies.addSignalListener("SIGINT", onInterrupt);
3029
- dependencies.addSignalListener("SIGTERM", onTerminate);
2951
+ signalHandlers(dependencies, "add", onInterrupt, onTerminate);
3030
2952
  try {
3031
2953
  const directory = dependencies.currentDirectory();
3032
2954
  const repository = resolveCliPath(directory, args.repository ?? ".");
3033
2955
  const project = await selectedProjectConfig(options.config, dependencies);
3034
2956
  const resolved = resolveScanSettings(project, {
3035
- auth: options.auth,
3036
- outputDir: options.outputDir,
2957
+ ...pickScanSettings({ ...options, workers: undefined }),
3037
2958
  knowledgeBasePaths: options.knowledgeBase,
3038
- scanPromptFile: options.scanPromptFile,
3039
- postScanPromptFile: options.postScanPromptFile,
3040
2959
  maxCostUsd: options.maxCost,
3041
2960
  codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider, project?.input.codex),
3042
2961
  }, directory);
@@ -3065,7 +2984,6 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3065
2984
  showCost: options.showCost,
3066
2985
  clock: dependencies,
3067
2986
  color: dependencies.environment["NO_COLOR"] === undefined,
3068
- sanitize: safeErrorMessage,
3069
2987
  input: process.stdin,
3070
2988
  onInterrupt,
3071
2989
  });
@@ -3121,7 +3039,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3121
3039
  if (dashboard !== null)
3122
3040
  dashboard.updateComponent(component);
3123
3041
  else
3124
- errorOutput.write(`codex-security: ${component.name} ${component.status}${component.error === undefined ? "" : `: ${component.error}`}\n`);
3042
+ errorOutput.write(`codex-security: ${component.name} ${component.status}${component.error === undefined ? "" : `: ${diagnosticValue(component.error)}`}\n`);
3125
3043
  },
3126
3044
  onComplete: (result) => {
3127
3045
  dashboard?.finishComponents(result);
@@ -3132,7 +3050,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3132
3050
  },
3133
3051
  });
3134
3052
  exitCode =
3135
- interruptedExitCode() ??
3053
+ interruptedExitCode(controller.signal) ??
3136
3054
  (result.failed ||
3137
3055
  result.incomplete ||
3138
3056
  result.deduplication?.status === "incomplete"
@@ -3144,18 +3062,17 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3144
3062
  }
3145
3063
  catch (error) {
3146
3064
  stopDashboard();
3147
- exitCode = interruptedExitCode() ?? 2;
3065
+ exitCode = interruptedExitCode(controller.signal) ?? 2;
3148
3066
  errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
3149
3067
  }
3150
3068
  finally {
3151
3069
  stopDashboard();
3152
- dependencies.removeSignalListener("SIGINT", onInterrupt);
3153
- dependencies.removeSignalListener("SIGTERM", onTerminate);
3070
+ signalHandlers(dependencies, "remove", onInterrupt, onTerminate);
3154
3071
  }
3155
3072
  },
3156
3073
  })
3157
3074
  .command("bulk-scan", {
3158
- description: "Discover repositories and run resumable bulk security scans.",
3075
+ description: "Discover and scan multiple repositories.",
3159
3076
  destructive: true,
3160
3077
  mcp: false,
3161
3078
  alias: { config: "c" },
@@ -3198,10 +3115,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3198
3115
  postScanPromptFile: optionValue("--post-scan-prompt-file")
3199
3116
  .optional()
3200
3117
  .describe("Run FILE after each scan, including failures."),
3201
- model: optionValue("--model")
3202
- .optional()
3203
- .describe(`OpenAI model for each repository (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`),
3204
- effort: effortOption(),
3118
+ ...modelOptions(`OpenAI model for each repository (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`).shape,
3205
3119
  provider: PROVIDER_OPTION,
3206
3120
  maxAttempts: z
3207
3121
  .number()
@@ -3238,15 +3152,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3238
3152
  output: z.record(z.string(), z.unknown()).optional(),
3239
3153
  async run({ args, options }) {
3240
3154
  const controller = new AbortController();
3241
- const onInterrupt = () => controller.abort("SIGINT");
3242
- const onTerminate = () => controller.abort("SIGTERM");
3243
- const interruptedExitCode = () => controller.signal.reason === "SIGINT"
3244
- ? 130
3245
- : controller.signal.reason === "SIGTERM"
3246
- ? 143
3247
- : undefined;
3248
- dependencies.addSignalListener("SIGINT", onInterrupt);
3249
- dependencies.addSignalListener("SIGTERM", onTerminate);
3155
+ const removeSignals = listenForAbort(dependencies, controller);
3250
3156
  try {
3251
3157
  const currentDirectory = dependencies.currentDirectory();
3252
3158
  if (options.recover && args.input === undefined) {
@@ -3254,12 +3160,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3254
3160
  }
3255
3161
  const project = await selectedProjectConfig(options.config, dependencies);
3256
3162
  const overrides = {
3257
- mode: options.mode,
3258
- outputDir: options.outputDir,
3163
+ ...pickScanSettings({ ...options, workers: undefined }),
3259
3164
  knowledgeBasePaths: options.knowledgeBase,
3260
- scanPromptFile: options.scanPromptFile,
3261
- validationPromptFile: options.validationPromptFile,
3262
- postScanPromptFile: options.postScanPromptFile,
3263
3165
  maxCostUsd: options.maxCost,
3264
3166
  };
3265
3167
  const resolved = resolveScanSettings(project, overrides, currentDirectory);
@@ -3388,11 +3290,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3388
3290
  signal: controller.signal,
3389
3291
  onProgress: ({ repository, status, attempt, error, warning }) => {
3390
3292
  const detail = error ?? warning;
3391
- errorOutput.write(`codex-security: ${repository} ${status} (attempt ${attempt})${detail === undefined ? "" : `: ${errorMessage(detail)}`}\n`);
3293
+ errorOutput.write(`codex-security: ${repository} ${status} (attempt ${attempt})${detail === undefined ? "" : `: ${diagnosticValue(detail)}`}\n`);
3392
3294
  },
3393
3295
  });
3394
3296
  exitCode =
3395
- interruptedExitCode() ??
3297
+ interruptedExitCode(controller.signal) ??
3396
3298
  (result.failed > 0 || result.incomplete > 0
3397
3299
  ? 2
3398
3300
  : result.policyFailed
@@ -3402,37 +3304,50 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3402
3304
  }
3403
3305
  catch (error) {
3404
3306
  exitCode =
3405
- interruptedExitCode() ??
3307
+ interruptedExitCode(controller.signal) ??
3406
3308
  (error instanceof Error && error.name === "ExitPromptError"
3407
3309
  ? 130
3408
3310
  : 2);
3409
3311
  errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
3410
3312
  }
3411
3313
  finally {
3412
- dependencies.removeSignalListener("SIGINT", onInterrupt);
3413
- dependencies.removeSignalListener("SIGTERM", onTerminate);
3314
+ removeSignals();
3414
3315
  }
3415
3316
  },
3416
3317
  })
3417
3318
  .command("export", {
3418
- description: "Export findings from a completed scan as CSV, JSON, or SARIF.",
3319
+ description: "Export saved findings or a threat model without running an analysis.",
3320
+ hint: "Examples:\n" +
3321
+ " codex-security export\n" +
3322
+ " codex-security export --export-format json --output -\n" +
3323
+ " codex-security export ../scan-results --export-format csv\n" +
3324
+ " codex-security export --artifact threat-model --output -\n\n" +
3325
+ "Use --export-format for artifact format. The global --format option controls\n" +
3326
+ "framework output such as --schema; it does not change exported files.",
3419
3327
  destructive: true,
3420
3328
  mcp: false,
3421
3329
  args: z.object({
3422
3330
  scanDir: z
3423
3331
  .string()
3424
3332
  .optional()
3425
- .describe("Completed scan directory (default: latest completed)."),
3333
+ .describe("Saved result directory (default: latest completed scan)."),
3426
3334
  }),
3427
3335
  options: z
3428
3336
  .object({
3337
+ artifact: z
3338
+ .enum(["findings", "threat-model"])
3339
+ .default("findings")
3340
+ .describe("Saved artifact to export."),
3341
+ scan: optionValue("--scan")
3342
+ .optional()
3343
+ .describe("Saved scan ID or unique prefix; cannot be combined with a result directory."),
3429
3344
  exportFormat: z
3430
- .enum(["csv", "json", "sarif"])
3431
- .default("sarif")
3432
- .describe("Artifact format to export from the completed scan."),
3345
+ .enum(["csv", "json", "sarif", "md"])
3346
+ .optional()
3347
+ .describe("Findings: csv, json, or sarif (default); threat-model: md (default)."),
3433
3348
  output: optionValue("--output")
3434
3349
  .optional()
3435
- .describe("FILE or '-' for stdout (default: results.sarif, findings.json, or findings.csv)."),
3350
+ .describe("FILE or '-' for stdout (default: results.sarif, findings.json, findings.csv, or threatmodel.md)."),
3436
3351
  sourceRoot: optionValue("--source-root")
3437
3352
  .optional()
3438
3353
  .describe("Repository checkout used for SARIF source-line fingerprints."),
@@ -3441,26 +3356,45 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3441
3356
  .describe("Python interpreter for the bundled plugin exporter."),
3442
3357
  })
3443
3358
  .refine((options) => options.sourceRoot === undefined ||
3444
- options.exportFormat === "sarif", {
3359
+ (options.artifact === "findings" &&
3360
+ (options.exportFormat === undefined ||
3361
+ options.exportFormat === "sarif")), {
3445
3362
  message: "--source-root is only supported with --export-format sarif",
3446
3363
  }),
3447
3364
  async run({ args, options }) {
3448
- const currentDirectory = dependencies.currentDirectory();
3449
- const scanDir = args.scanDir ?? (await latestScans())?.[0]?.scanDir;
3450
- if (scanDir === undefined)
3451
- return;
3452
- exitCode = await runExport({
3453
- scanDir: resolveCliPath(currentDirectory, scanDir),
3454
- format: options.exportFormat,
3455
- output: options.output === "-"
3456
- ? "-"
3457
- : resolveCliPath(currentDirectory, options.output ??
3458
- EXPORT_DEFAULT_OUTPUTS[options.exportFormat]),
3459
- sourceRoot: options.sourceRoot === undefined
3460
- ? undefined
3461
- : resolveCliPath(currentDirectory, options.sourceRoot),
3462
- pythonPath: options.python,
3463
- }, output, errorOutput, dependencies);
3365
+ try {
3366
+ const currentDirectory = dependencies.currentDirectory();
3367
+ if (args.scanDir !== undefined && options.scan !== undefined) {
3368
+ throw new CodexSecurityError("--scan cannot be combined with a result directory.");
3369
+ }
3370
+ const format = resolveArtifactFormat(options.artifact, options.exportFormat);
3371
+ let scanDir = args.scanDir;
3372
+ if (scanDir === undefined) {
3373
+ const scanId = options.scan ??
3374
+ (await latestScans(1, "complete", options.python))?.[0]?.scanId;
3375
+ if (scanId === undefined)
3376
+ return;
3377
+ scanDir = await resolveSavedArtifactDirectory(scanId, options.artifact, format, (args) => dependencies.runWorkbench(args, undefined, undefined, options.python));
3378
+ }
3379
+ exitCode = await runExport({
3380
+ scanDir: resolveCliPath(currentDirectory, scanDir),
3381
+ artifact: options.artifact,
3382
+ format,
3383
+ output: options.output === "-"
3384
+ ? "-"
3385
+ : resolveCliPath(currentDirectory, options.output ?? EXPORT_DEFAULT_OUTPUTS[format]),
3386
+ sourceRoot: options.sourceRoot === undefined
3387
+ ? undefined
3388
+ : resolveCliPath(currentDirectory, options.sourceRoot),
3389
+ pythonPath: options.python,
3390
+ }, output, errorOutput, dependencies);
3391
+ }
3392
+ catch (error) {
3393
+ if (exitCode !== 2) {
3394
+ errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
3395
+ }
3396
+ exitCode = 2;
3397
+ }
3464
3398
  },
3465
3399
  })
3466
3400
  .command("validate", {
@@ -3474,19 +3408,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3474
3408
  .describe("Finding text or a file containing findings."),
3475
3409
  }),
3476
3410
  options: z.object({
3477
- auth: z
3478
- .enum(SCAN_AUTH_MODES)
3479
- .default("auto")
3480
- .describe("Credential source: auto, chatgpt, or api-key."),
3481
- effort: effortOption(),
3482
- codex: z
3483
- .array(optionValue("--codex"))
3484
- .default([])
3485
- .describe('Repeat TOML model="gpt-5.6-terra", model_reasoning_effort="high", or analytics.enabled=false.'),
3411
+ auth: SKILL_AUTH_OPTION,
3412
+ ...SKILL_CONFIG_OPTIONS.shape,
3486
3413
  }),
3487
3414
  async run({ options }) {
3488
3415
  try {
3489
- exitCode = await runSkill("validation", positionals, options.codex, options.effort, output, errorOutput, dependencies, { auth: options.auth });
3416
+ exitCode = await runSkill("validation", positionals, options, output, errorOutput, dependencies, { auth: options.auth });
3490
3417
  }
3491
3418
  catch (error) {
3492
3419
  exitCode = 2;
@@ -3506,14 +3433,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3506
3433
  .describe("Finding text, a file, or a saved finding identifier."),
3507
3434
  }),
3508
3435
  options: z.object({
3509
- auth: z
3510
- .enum(SCAN_AUTH_MODES)
3511
- .default("auto")
3512
- .describe("Credential source: auto, chatgpt, or api-key."),
3513
- effort: effortOption(),
3436
+ auth: SKILL_AUTH_OPTION,
3437
+ ...MODEL_OPTIONS.shape,
3514
3438
  scan: optionValue("--scan")
3515
3439
  .optional()
3516
- .describe("Verify open findings from a saved scan."),
3440
+ .describe("Verify open findings from a saved scan ID or the latest completed scan."),
3517
3441
  severity: z
3518
3442
  .enum(REPORTABLE_SEVERITIES)
3519
3443
  .optional()
@@ -3529,11 +3453,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3529
3453
  .optional()
3530
3454
  .describe("JSON Linear issue filter for --linear-project."),
3531
3455
  linearApiKey: linearApiKeyOption(),
3532
- codex: z
3533
- .array(optionValue("--codex"))
3534
- .default([])
3535
- .describe('Repeat TOML model="gpt-5.6-terra", model_reasoning_effort="high", or analytics.enabled=false.'),
3456
+ codex: SKILL_CONFIG_OPTIONS.shape.codex,
3536
3457
  }),
3458
+ examples: [
3459
+ {
3460
+ options: { scan: "latest" },
3461
+ description: "Verify fixes for the latest completed scan.",
3462
+ },
3463
+ {
3464
+ args: { "findings...": "finding.md" },
3465
+ description: "Verify a fix described in a file.",
3466
+ },
3467
+ ],
3537
3468
  output: z.record(z.string(), z.unknown()).optional(),
3538
3469
  async run({ format, options }) {
3539
3470
  try {
@@ -3585,18 +3516,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3585
3516
  if (identifiers.length > 0) {
3586
3517
  const environment = imports.length === 0
3587
3518
  ? undefined
3588
- : Object.fromEntries(Object.entries(dependencies.environment).filter(([name]) => !/^(?:CODEX_SECURITY_)?LINEAR_(?:API_KEY|ACCESS_TOKEN)$/iu.test(name)));
3589
- let response = "";
3590
- const verificationOutput = {
3591
- write(value) {
3592
- response += value.toString();
3593
- return true;
3594
- },
3595
- };
3519
+ : withoutLinearCredentials(dependencies.environment);
3520
+ const response = captureOutput();
3596
3521
  const progress = new FindingProgressPresenter(errorOutput, dependencies, repository, identifiers.length);
3597
3522
  progress.startVerification();
3598
3523
  try {
3599
- exitCode = await runSkill("verify-fix", selected === undefined ? [...positionals, ...imports] : [], options.codex, options.effort, verificationOutput, errorOutput, dependencies, {
3524
+ exitCode = await runSkill("verify-fix", selected === undefined ? [...positionals, ...imports] : [], options, response.stream, errorOutput, dependencies, {
3600
3525
  directory: repository,
3601
3526
  ...(selected === undefined
3602
3527
  ? {}
@@ -3613,7 +3538,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3613
3538
  }
3614
3539
  let reported;
3615
3540
  try {
3616
- reported = JSON.parse(response);
3541
+ reported = JSON.parse(response.text());
3617
3542
  }
3618
3543
  catch {
3619
3544
  throw new CodexSecurityError("Verification results were not valid JSON.");
@@ -3652,7 +3577,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3652
3577
  }
3653
3578
  catch (error) {
3654
3579
  exitCode = 2;
3655
- errorOutput.write(`codex-security: ${safeErrorMessage(error)}\n`);
3580
+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
3656
3581
  return undefined;
3657
3582
  }
3658
3583
  },
@@ -3666,21 +3591,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3666
3591
  .string()
3667
3592
  .min(1, "An issue must not be empty.")
3668
3593
  .optional()
3669
- .describe("Issue text or a file containing issues."),
3594
+ .describe("Issue text, a file, or a saved finding identifier."),
3670
3595
  }),
3671
3596
  options: z.object({
3672
- auth: z
3673
- .enum(SCAN_AUTH_MODES)
3674
- .default("auto")
3675
- .describe("Credential source: auto, chatgpt, or api-key."),
3676
- effort: effortOption(),
3597
+ auth: SKILL_AUTH_OPTION,
3598
+ ...MODEL_OPTIONS.shape,
3677
3599
  externalSandbox: z
3678
3600
  .boolean()
3679
3601
  .default(false)
3680
3602
  .describe("Use the container's isolation instead of the Codex sandbox (default: false)."),
3681
3603
  scan: optionValue("--scan")
3682
3604
  .optional()
3683
- .describe("Patch open findings from a saved scan."),
3605
+ .describe("Patch open findings from a saved scan ID or the latest completed scan."),
3684
3606
  severity: z
3685
3607
  .enum(REPORTABLE_SEVERITIES)
3686
3608
  .optional()
@@ -3704,11 +3626,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3704
3626
  resumePr: optionValue("--resume-pr")
3705
3627
  .optional()
3706
3628
  .describe("Resume publication of a saved patch branch without patching again."),
3707
- codex: z
3708
- .array(optionValue("--codex"))
3709
- .default([])
3710
- .describe('Repeat TOML model="gpt-5.6-terra", model_reasoning_effort="high", or analytics.enabled=false.'),
3629
+ codex: SKILL_CONFIG_OPTIONS.shape.codex,
3711
3630
  }),
3631
+ examples: [
3632
+ {
3633
+ options: { scan: "latest", severity: "high" },
3634
+ description: "Patch high and critical findings from the latest completed scan.",
3635
+ },
3636
+ {
3637
+ args: { "issues...": "finding.md" },
3638
+ description: "Patch a finding described in a file.",
3639
+ },
3640
+ ],
3712
3641
  output: z.record(z.string(), z.unknown()).optional(),
3713
3642
  async run({ format, options, error: commandError }) {
3714
3643
  const jsonOutput = format === "json" || format === "jsonl";
@@ -3732,6 +3661,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3732
3661
  linear ||
3733
3662
  options.linearFilter !== undefined ||
3734
3663
  options.linearApiKey !== undefined ||
3664
+ options.model !== undefined ||
3735
3665
  options.effort !== undefined ||
3736
3666
  options.auth !== "auto" ||
3737
3667
  options.codex.length > 0) {
@@ -3768,7 +3698,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3768
3698
  : undefined;
3769
3699
  const patchBase = patchRiskBase ??
3770
3700
  (await snapshotPatchState(selected.repository, dependencies));
3771
- const patches = await runFindingPatches(selected, options.codex, options.effort, errorOutput, dependencies, {
3701
+ const patches = await runFindingPatches(selected, options, errorOutput, dependencies, {
3772
3702
  auth: options.auth,
3773
3703
  externalSandbox: options.externalSandbox,
3774
3704
  validationPrompt,
@@ -3795,8 +3725,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3795
3725
  repository: selected.repository,
3796
3726
  base: patchRiskBase,
3797
3727
  files,
3798
- codexOverrides: options.codex,
3799
- effort: options.effort,
3728
+ configuration: options,
3800
3729
  auth: options.auth,
3801
3730
  }, errorOutput, dependencies);
3802
3731
  }
@@ -3835,7 +3764,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3835
3764
  : [];
3836
3765
  const environment = imports.length === 0
3837
3766
  ? undefined
3838
- : Object.fromEntries(Object.entries(dependencies.environment).filter(([name]) => !/^(?:CODEX_SECURITY_)?LINEAR_(?:API_KEY|ACCESS_TOKEN)$/iu.test(name)));
3767
+ : withoutLinearCredentials(dependencies.environment);
3839
3768
  const patchGitBase = options.assessPatchRisk || options.createPr
3840
3769
  ? await snapshotPatchTree(repository, dependencies)
3841
3770
  : undefined;
@@ -3844,20 +3773,15 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3844
3773
  if (options.createPr) {
3845
3774
  await requireCleanPatchPullRequestBase(repository, patchGitBase, dependencies);
3846
3775
  }
3847
- let report = "";
3848
- exitCode = await runSkill("fix-finding", [...positionals, ...imports], options.codex, options.effort, {
3849
- write: (value) => {
3850
- report += value.toString();
3851
- return true;
3852
- },
3853
- }, errorOutput, dependencies, {
3776
+ const report = captureOutput();
3777
+ exitCode = await runSkill("fix-finding", [...positionals, ...imports], options, report.stream, errorOutput, dependencies, {
3854
3778
  environment,
3855
3779
  auth: options.auth,
3856
3780
  externalSandbox: options.externalSandbox,
3857
3781
  validationPrompt,
3858
3782
  });
3859
3783
  if (!jsonOutput)
3860
- output.write(report);
3784
+ output.write(report.text());
3861
3785
  const files = await changedPatchFiles(repository, patchBase, dependencies);
3862
3786
  patchResult = {
3863
3787
  repository,
@@ -3878,8 +3802,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3878
3802
  environment,
3879
3803
  base: patchGitBase,
3880
3804
  files,
3881
- codexOverrides: options.codex,
3882
- effort: options.effort,
3805
+ configuration: options,
3883
3806
  auth: options.auth,
3884
3807
  }, errorOutput, dependencies)
3885
3808
  : undefined;
@@ -3892,14 +3815,14 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3892
3815
  if (structuredOutput)
3893
3816
  return {
3894
3817
  ...patchResult,
3895
- ...(jsonOutput ? { report } : {}),
3818
+ ...(jsonOutput ? { report: report.text() } : {}),
3896
3819
  };
3897
3820
  }
3898
3821
  catch (error) {
3899
3822
  if (exitCode === 0)
3900
3823
  exitCode = 2;
3901
- const message = safeErrorMessage(error);
3902
- errorOutput.write(`codex-security: ${message}\n`);
3824
+ const message = errorMessage(error);
3825
+ errorOutput.write(`codex-security: ${diagnosticValue(message)}\n`);
3903
3826
  if (!structuredOutput)
3904
3827
  return;
3905
3828
  patchStructuredError = true;
@@ -3921,16 +3844,28 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3921
3844
  })
3922
3845
  .command("login", {
3923
3846
  description: "Sign in with ChatGPT or store credentials.",
3847
+ hint: "For remote login, use --device-auth if your workspace allows it.\n" +
3848
+ "If device auth is disabled, sign in over SSH:\n" +
3849
+ " On your local machine (replace user@remote):\n" +
3850
+ " ssh -L 1455:localhost:1455 user@remote\n" +
3851
+ " In that SSH session:\n" +
3852
+ " codex-security login\n" +
3853
+ " Open the sign-in URL in your local browser.\n" +
3854
+ " Keep SSH connected until login finishes.\n" +
3855
+ "Docs: https://learn.chatgpt.com/docs/auth?surface=cli#cli-fallback-forward-the-localhost-callback-over-ssh",
3924
3856
  destructive: true,
3925
3857
  mcp: false,
3926
3858
  args: z.object({
3927
- action: z.enum(["status"]).optional().describe("Show login status."),
3859
+ action: z
3860
+ .enum(["status"])
3861
+ .optional()
3862
+ .describe("Use status to inspect credentials; omit to sign in."),
3928
3863
  }),
3929
3864
  options: z.object({
3930
3865
  deviceAuth: z
3931
3866
  .boolean()
3932
3867
  .default(false)
3933
- .describe("Use device-code authentication."),
3868
+ .describe("Use device auth if your workspace allows it."),
3934
3869
  withApiKey: z
3935
3870
  .boolean()
3936
3871
  .default(false)
@@ -3940,6 +3875,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3940
3875
  .default(false)
3941
3876
  .describe("Read an access token from stdin."),
3942
3877
  }),
3878
+ examples: [
3879
+ { args: {}, description: "Sign in with ChatGPT." },
3880
+ { args: { action: "status" }, description: "Check authentication." },
3881
+ ],
3943
3882
  async run({ args, options }) {
3944
3883
  const credentialHome = dependencies.prepareAuthenticationHome !== undefined
3945
3884
  ? await dependencies.prepareAuthenticationHome(dependencies.environment)
@@ -3977,11 +3916,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
3977
3916
  else if (exitCode === 0 && !options.withApiKey) {
3978
3917
  const authentication = scanAuthentication(dependencies.environment);
3979
3918
  if (authentication.method === "api_key") {
3980
- const configuredApiKeyVariables = Object.entries(dependencies.environment)
3981
- .filter(([name, value]) => value?.trim() &&
3919
+ const configuredApiKeyVariables = Object.entries(dependencies.environment).flatMap(([name, value]) => value?.trim() &&
3982
3920
  (name.toUpperCase() === "OPENAI_API_KEY" ||
3983
- name.toUpperCase() === "CODEX_API_KEY"))
3984
- .map(([name]) => name);
3921
+ name.toUpperCase() === "CODEX_API_KEY")
3922
+ ? name
3923
+ : []);
3985
3924
  const loginWarning = options.withAccessToken
3986
3925
  ? `Access-token login succeeded, but noninteractive scans will use ${authentication.source}.\n`
3987
3926
  : "ChatGPT login succeeded. Interactive scans will ask which account to use; " +
@@ -4016,7 +3955,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4016
3955
  },
4017
3956
  })
4018
3957
  .command("serve", {
4019
- description: "Start the findings HTTP service (HOST=127.0.0.1, PORT=3000). CODEX_SECURITY_EMBEDDINGS_URL overrides the embeddings endpoint (default: https://api.openai.com/v1/embeddings).",
3958
+ description: "Start the local findings HTTP service.",
3959
+ hint: "Environment: HOST=127.0.0.1, PORT=3000.\n" +
3960
+ "CODEX_SECURITY_EMBEDDINGS_URL overrides the embeddings endpoint\n" +
3961
+ "(default: https://api.openai.com/v1/embeddings).",
4020
3962
  destructive: true,
4021
3963
  mcp: false,
4022
3964
  options: z.object({
@@ -4042,7 +3984,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4042
3984
  },
4043
3985
  })
4044
3986
  .command("init", {
4045
- description: "Write a starter project configuration without overwriting an existing file.",
3987
+ description: "Create a starter project configuration.",
3988
+ hint: "Existing files are never overwritten.",
4046
3989
  destructive: true,
4047
3990
  mcp: false,
4048
3991
  args: z.object({
@@ -4107,10 +4050,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4107
4050
  ? undefined
4108
4051
  : (await history(["get-scan", "--scan-id", scanId]))["scan"];
4109
4052
  const controller = new AbortController();
4110
- const onInterrupt = () => controller.abort("SIGINT");
4111
- const onTerminate = () => controller.abort("SIGTERM");
4112
- dependencies.addSignalListener("SIGINT", onInterrupt);
4113
- dependencies.addSignalListener("SIGTERM", onTerminate);
4053
+ const removeSignals = listenForAbort(dependencies, controller);
4114
4054
  try {
4115
4055
  return await (dependencies.sendFeedback ?? sendFeedback)({
4116
4056
  ...options,
@@ -4128,13 +4068,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4128
4068
  throw error;
4129
4069
  }
4130
4070
  finally {
4131
- dependencies.removeSignalListener("SIGINT", onInterrupt);
4132
- dependencies.removeSignalListener("SIGTERM", onTerminate);
4071
+ removeSignals();
4133
4072
  }
4134
4073
  },
4135
4074
  })
4136
4075
  .command("info", {
4137
- description: "Show SDK metadata and resolved configuration without preparing a scan.",
4076
+ description: "Show SDK metadata and resolved configuration.",
4138
4077
  alias: { config: "c" },
4139
4078
  options: z.object({ config: PROJECT_CONFIG_OPTION }),
4140
4079
  mcp: {
@@ -4254,12 +4193,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4254
4193
  }
4255
4194
  let notice;
4256
4195
  try {
4257
- await cli.serve(argv.flatMap((argument) => argument.startsWith("--format=")
4258
- ? ["--format", argument.slice("--format=".length)]
4259
- : [argument]), {
4260
- stdout: (value) => {
4261
- frameworkOutput += value;
4262
- },
4196
+ await cli.serve(argv.flatMap((argument) => {
4197
+ if (!/^--(?:format|filter-output|token-limit|token-offset)=/u.test(argument))
4198
+ return [argument];
4199
+ const separator = argument.indexOf("=");
4200
+ return [argument.slice(0, separator), argument.slice(separator + 1)];
4201
+ }), {
4202
+ stdout: frameworkCapture.stream.write,
4263
4203
  exit: (code) => {
4264
4204
  frameworkExit = code;
4265
4205
  },
@@ -4271,6 +4211,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4271
4211
  finally {
4272
4212
  updateController.abort();
4273
4213
  }
4214
+ const frameworkOutput = frameworkCapture.text();
4274
4215
  if (notice !== undefined)
4275
4216
  errorOutput.write(formatUpdateNotice(notice));
4276
4217
  if (frameworkExit !== undefined) {
@@ -4297,7 +4238,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4297
4238
  renderedPatch ??
4298
4239
  renderedPublication ??
4299
4240
  renderedHistory ??
4300
- frameworkOutput);
4241
+ formatCliHelp(frameworkOutput, output.columns));
4301
4242
  return exitCode;
4302
4243
  }
4303
4244
  catch (error) {
@@ -4307,10 +4248,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
4307
4248
  }
4308
4249
  async function runScanImport(options, errorOutput, dependencies) {
4309
4250
  const controller = new AbortController();
4310
- const onInterrupt = () => controller.abort("SIGINT");
4311
- const onTerminate = () => controller.abort("SIGTERM");
4312
- dependencies.addSignalListener("SIGINT", onInterrupt);
4313
- dependencies.addSignalListener("SIGTERM", onTerminate);
4251
+ const removeSignals = listenForAbort(dependencies, controller);
4314
4252
  try {
4315
4253
  const result = await (dependencies.importScan ?? importScan)({ ...options, signal: controller.signal }, { environment: dependencies.environment });
4316
4254
  if ("dryRun" in result)
@@ -4326,16 +4264,15 @@ async function runScanImport(options, errorOutput, dependencies) {
4326
4264
  const signal = controller.signal.reason;
4327
4265
  const message = signal === "SIGINT" || signal === "SIGTERM"
4328
4266
  ? "Scan import canceled."
4329
- : safeErrorMessage(error);
4330
- errorOutput.write(`codex-security: ${message}\n`);
4267
+ : errorMessage(error);
4268
+ errorOutput.write(`codex-security: ${diagnosticValue(message)}\n`);
4331
4269
  return {
4332
- exitCode: signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2,
4270
+ exitCode: interruptedExitCode(controller.signal) ?? 2,
4333
4271
  error: message,
4334
4272
  };
4335
4273
  }
4336
4274
  finally {
4337
- dependencies.removeSignalListener("SIGINT", onInterrupt);
4338
- dependencies.removeSignalListener("SIGTERM", onTerminate);
4275
+ removeSignals();
4339
4276
  }
4340
4277
  }
4341
4278
  function isScanImportCommand(argv) {
@@ -4403,7 +4340,7 @@ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt
4403
4340
  throw new CodexSecurityError("This scan used custom validation. Supply --validation-prompt-file to rerun it.");
4404
4341
  }
4405
4342
  const repository = recipe["repository"];
4406
- if (typeof repository !== "string" || repository.length === 0) {
4343
+ if (!isNonEmptyString(repository)) {
4407
4344
  throw new CodexSecurityError("The saved scan recipe does not contain a repository.");
4408
4345
  }
4409
4346
  const target = recipe["target"];
@@ -4411,13 +4348,12 @@ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt
4411
4348
  throw new CodexSecurityError("The saved scan recipe contains no target.");
4412
4349
  }
4413
4350
  const paths = target["paths"];
4414
- if (!Array.isArray(paths) ||
4415
- !paths.every((path) => typeof path === "string" && path.length > 0)) {
4351
+ if (!Array.isArray(paths) || !paths.every(isNonEmptyString)) {
4416
4352
  throw new CodexSecurityError("The saved scan recipe contains invalid paths.");
4417
4353
  }
4418
4354
  const knowledgeBasePaths = recipe["knowledgeBasePaths"] ?? [];
4419
4355
  if (!Array.isArray(knowledgeBasePaths) ||
4420
- !knowledgeBasePaths.every((path) => typeof path === "string" && path.length > 0)) {
4356
+ !knowledgeBasePaths.every(isNonEmptyString)) {
4421
4357
  throw new CodexSecurityError("The saved scan recipe contains invalid knowledge base paths.");
4422
4358
  }
4423
4359
  const kind = target["kind"];
@@ -4441,7 +4377,7 @@ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt
4441
4377
  throw new CodexSecurityError("The saved scan recipe has an invalid Git base.");
4442
4378
  }
4443
4379
  const head = target["headRef"];
4444
- if (head !== undefined && (typeof head !== "string" || head.length === 0)) {
4380
+ if (head !== undefined && !isNonEmptyString(head)) {
4445
4381
  throw new CodexSecurityError("The saved scan recipe has an invalid Git head.");
4446
4382
  }
4447
4383
  const threshold = recipe["failOnSeverity"];
@@ -4466,6 +4402,10 @@ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt
4466
4402
  throw new CodexSecurityError("The saved scan recipe is missing resolved deep scan settings.");
4467
4403
  }
4468
4404
  const auth = z.enum(SCAN_AUTH_MODES).optional().safeParse(recipe["auth"]);
4405
+ const cyberAccessProgram = ScanSettingsSchema.shape.cyberAccessProgram.safeParse(recipe["cyberAccessProgram"]);
4406
+ if (!cyberAccessProgram.success) {
4407
+ throw new CodexSecurityError("The saved scan recipe contains an invalid Cyber access program.");
4408
+ }
4469
4409
  if (!auth.success)
4470
4410
  throw new CodexSecurityError("The saved scan recipe contains an invalid authentication choice.");
4471
4411
  if (mode !== "deep" &&
@@ -4486,6 +4426,7 @@ async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt
4486
4426
  return {
4487
4427
  repository,
4488
4428
  auth: auth.data ?? DEFAULT_SCAN_AUTH,
4429
+ cyberAccessProgram: cyberAccessProgram.data,
4489
4430
  target: paths.length > 0
4490
4431
  ? paths
4491
4432
  : kind === "refs"
@@ -4532,6 +4473,9 @@ function validateCliArguments(argv, positionals) {
4532
4473
  "import",
4533
4474
  "validate",
4534
4475
  "verify-fix",
4476
+ "suggest-owners",
4477
+ "classify-severity",
4478
+ "dedupe",
4535
4479
  "patch",
4536
4480
  "login",
4537
4481
  "logout",
@@ -4563,6 +4507,16 @@ function validateCliArguments(argv, positionals) {
4563
4507
  (value === "--export-format" && argv[index + 1] === "csv"))) {
4564
4508
  return "CSV stdout cannot be combined with JSON output; write CSV to a file or omit --json.";
4565
4509
  }
4510
+ if (command === "export" &&
4511
+ structuredOutput &&
4512
+ argv.some((value, index) => value === "--output=-" ||
4513
+ (value === "--output" && argv[index + 1] === "-")) &&
4514
+ argv.some((value, index) => value === "--artifact=threat-model" ||
4515
+ (value === "--artifact" && argv[index + 1] === "threat-model") ||
4516
+ value === "--export-format=md" ||
4517
+ (value === "--export-format" && argv[index + 1] === "md"))) {
4518
+ return "Markdown stdout cannot be combined with JSON output; write Markdown to a file or omit --json.";
4519
+ }
4566
4520
  if (command === "scan" && !argv.includes("--schema")) {
4567
4521
  if (argv.some((value) => value === "--filter-output" || value.startsWith("--filter-output="))) {
4568
4522
  return "--filter-output is not supported for scan results.";
@@ -4616,8 +4570,10 @@ function validateCliArguments(argv, positionals) {
4616
4570
  }
4617
4571
  const equals = value.indexOf("=");
4618
4572
  const option = equals < 0 ? value : value.slice(0, equals);
4573
+ const canonicalOption = option.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
4619
4574
  if (equals >= 0 ||
4620
- (!VALUE_OPTIONS.has(option) && !(scanImport && option === "--json")))
4575
+ (!VALUE_OPTIONS.has(canonicalOption) &&
4576
+ !(scanImport && option === "--json")))
4621
4577
  continue;
4622
4578
  const next = argv[index + 1];
4623
4579
  if (next === undefined || next.startsWith("--") || next === "-h") {
@@ -4807,8 +4763,7 @@ async function selectSavedFindings(identifiers, requestedScanId, severity, depen
4807
4763
  }
4808
4764
  }
4809
4765
  const selected = findings.filter((finding) => {
4810
- const triage = finding["triage"];
4811
- return (triage?.["status"] !== "closed" &&
4766
+ return (finding["triage"]?.["status"] !== "closed" &&
4812
4767
  (identifiers.length === 0 ||
4813
4768
  identifiers.includes(finding.occurrenceId) ||
4814
4769
  identifiers.includes(finding.findingId)) &&
@@ -4857,10 +4812,7 @@ function directPatchIdentifier(positionals, imports) {
4857
4812
  return isLinearIssueIdentifier(candidate) ? candidate : undefined;
4858
4813
  }
4859
4814
  function directPatchDigest(positionals, imports) {
4860
- return `issues-${createHash("sha256")
4861
- .update(JSON.stringify([...positionals, ...imports.map(({ id }) => id)]))
4862
- .digest("hex")
4863
- .slice(0, 12)}`;
4815
+ return `issues-${sha256Text(JSON.stringify([...positionals, ...imports.map(({ id }) => id)])).slice(0, 12)}`;
4864
4816
  }
4865
4817
  async function publishPatchBranch(repository, branch, body, stderr, dependencies) {
4866
4818
  const run = (command, args) => dependencies.runRepositoryCommand(command, args, repository);
@@ -5068,7 +5020,7 @@ async function snapshotPatchDirectory(repository) {
5068
5020
  return files;
5069
5021
  }
5070
5022
  function safePatchText(value) {
5071
- return stripVTControlCharacters(safeErrorMessage(value)).replaceAll(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu, " ");
5023
+ return stripVTControlCharacters(value).replaceAll(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu, " ");
5072
5024
  }
5073
5025
  function safePatchReport(value) {
5074
5026
  return value.split(/\r?\n/gu).map(safePatchText).join("\n").trim();
@@ -5143,14 +5095,8 @@ async function assessPatchRisk(request, stderr, dependencies) {
5143
5095
  for await (const chunk of createReadStream(patchPath)) {
5144
5096
  digest.update(chunk);
5145
5097
  }
5146
- let report = "";
5147
- const stdout = {
5148
- write(value) {
5149
- report += value.toString();
5150
- return true;
5151
- },
5152
- };
5153
- const status = await runSkill("assess-patch-risk", [], request.codexOverrides, request.effort, stdout, stderr, dependencies, {
5098
+ const report = captureOutput();
5099
+ const status = await runSkill("assess-patch-risk", [], request.configuration, report.stream, stderr, dependencies, {
5154
5100
  directory: request.repository,
5155
5101
  auth: request.auth,
5156
5102
  environment: request.environment,
@@ -5167,7 +5113,7 @@ async function assessPatchRisk(request, stderr, dependencies) {
5167
5113
  if (status !== 0) {
5168
5114
  throw new CodexSecurityError(`Patch risk assessment exited with status ${status}.`);
5169
5115
  }
5170
- return { report: report.trim() };
5116
+ return { report: report.text().trim() };
5171
5117
  }
5172
5118
  finally {
5173
5119
  await rm(root, { recursive: true, force: true });
@@ -5200,7 +5146,7 @@ async function resolvePatchValidationPrompt(file, repository, directory) {
5200
5146
  const { validationPrompt } = await resolveScanPrompts({ validationPromptFile: file }, [...roots], directory);
5201
5147
  return validationPrompt;
5202
5148
  }
5203
- async function runFindingPatches(selected, codexOverrides, effort, stderr, dependencies, options = {}, interactive = true) {
5149
+ async function runFindingPatches(selected, configuration, stderr, dependencies, options = {}, interactive = true) {
5204
5150
  if (selected.findings.length === 0) {
5205
5151
  stderr.write("No matching open findings to patch.\n");
5206
5152
  return [];
@@ -5208,13 +5154,7 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
5208
5154
  stderr.write(`\nPatching ${selected.findings.length} confirmed finding${selected.findings.length === 1 ? "" : "s"}...\n`);
5209
5155
  const patches = [];
5210
5156
  for (const finding of selected.findings) {
5211
- let response = "";
5212
- const stdout = {
5213
- write(value) {
5214
- response += value.toString();
5215
- return true;
5216
- },
5217
- };
5157
+ const response = captureOutput();
5218
5158
  const instruction = options.findingInstructions?.[finding.occurrenceId];
5219
5159
  const progress = new FindingProgressPresenter(stderr, dependencies, selected.repository, selected.findings.length, interactive);
5220
5160
  progress.startPatch(finding, patches.length);
@@ -5228,7 +5168,7 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
5228
5168
  let changedFiles;
5229
5169
  try {
5230
5170
  const base = await snapshotPatchState(selected.repository, dependencies);
5231
- status = await runSkill("fix-finding", [], codexOverrides, effort, stdout, patchErrors, dependencies, {
5171
+ status = await runSkill("fix-finding", [], configuration, response.stream, patchErrors, dependencies, {
5232
5172
  ...options,
5233
5173
  directory: selected.repository,
5234
5174
  findings: [finding],
@@ -5257,7 +5197,7 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
5257
5197
  }
5258
5198
  else {
5259
5199
  try {
5260
- const reported = JSON.parse(response);
5200
+ const reported = JSON.parse(response.text());
5261
5201
  const entries = Array.isArray(reported?.patches)
5262
5202
  ? reported.patches
5263
5203
  : [];
@@ -5269,7 +5209,8 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
5269
5209
  if (matches.length !== 1 || !parsed.success) {
5270
5210
  patch = failed("No complete patch result was returned for this finding.");
5271
5211
  }
5272
- else if (parsed.data.status === "verified" &&
5212
+ else if ((parsed.data.status === "verified" ||
5213
+ parsed.data.status === "no_change") &&
5273
5214
  !parsed.data.verification?.trim()) {
5274
5215
  patch = failed("Patch verification was not reported.", parsed.data.files);
5275
5216
  }
@@ -5292,16 +5233,49 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
5292
5233
  }
5293
5234
  return patches;
5294
5235
  }
5295
- async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, dependencies, options = {}) {
5296
- const overrides = parseCodexOverrides(codexOverrides, undefined, effort);
5236
+ function captureOutput() {
5237
+ let text = "";
5238
+ return {
5239
+ stream: {
5240
+ write(value) {
5241
+ text += value.toString();
5242
+ return true;
5243
+ },
5244
+ },
5245
+ text: () => text,
5246
+ };
5247
+ }
5248
+ async function runSkill(skill, inputs, configuration, stdout, stderr, dependencies, options = {}) {
5249
+ const { codex, model: selectedModel, effort } = configuration;
5250
+ const overrides = parseCodexOverrides(codex, selectedModel, effort);
5297
5251
  if (Object.entries(overrides).some(([key, value]) => key !== "model" &&
5298
5252
  key !== "model_reasoning_effort" &&
5253
+ key !== "model_provider" &&
5254
+ key !== "model_providers" &&
5299
5255
  !(key === "analytics" &&
5300
5256
  isJsonObject(value) &&
5301
5257
  Object.keys(value).every((key) => key === "enabled")))) {
5302
- throw new CodexSecurityError("Skill commands only support model, model_reasoning_effort, and analytics.enabled overrides.");
5258
+ throw new CodexSecurityError("Skill commands only support model, model_reasoning_effort, model_provider, model_providers, and analytics.enabled overrides.");
5303
5259
  }
5260
+ if (options.serviceTier !== undefined)
5261
+ overrides["service_tier"] = options.serviceTier;
5304
5262
  const { model, reasoningEffort } = scanModelConfiguration(await mergedCodexConfig({ codexOverrides: overrides }));
5263
+ const provider = options.provider ?? overrides["model_provider"];
5264
+ const providerConfiguration = options.providerConfiguration ??
5265
+ (provider === undefined
5266
+ ? undefined
5267
+ : (overrides["model_providers"]?.[provider] ??
5268
+ (isExternalModelProvider(provider)
5269
+ ? EXTERNAL_CODEX_PROVIDERS[provider]
5270
+ : undefined)));
5271
+ const effectiveOverrides = resolveCommandAuthConfig(mergeCodexOverrides(overrides, provider === undefined
5272
+ ? {}
5273
+ : {
5274
+ model_provider: provider,
5275
+ ...(providerConfiguration === undefined
5276
+ ? {}
5277
+ : { model_providers: { [provider]: providerConfiguration } }),
5278
+ }), configuredCodexHome(options.environment ?? dependencies.environment));
5305
5279
  const directory = options.directory ?? dependencies.currentDirectory();
5306
5280
  const contents = [...(options.findings ?? [])];
5307
5281
  for (const input of inputs) {
@@ -5376,7 +5350,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
5376
5350
  ...(options.findings === undefined
5377
5351
  ? []
5378
5352
  : [
5379
- 'Return exactly one JSON object with a "patches" array. Include one object for every supplied finding: {"occurrenceId":"...","status":"verified|no_change|blocked|failed","files":["relative/path"],"verification":"proof that the original issue is fixed and legitimate behavior still works","reason":"required for blocked or failed outcomes"}. Use "verified" only after the original issue no longer reproduces and relevant checks pass. Preserve unrelated local changes.',
5353
+ 'Return exactly one JSON object with a "patches" array. Include one object for every supplied finding: {"occurrenceId":"...","status":"verified|no_change|blocked|failed","files":["relative/path"],"verification":"required for verified and no_change outcomes: proof that the original issue is fixed or that the current code is already safe, and that legitimate behavior still works","reason":"required for blocked or failed outcomes"}. Use "verified" only after the original issue no longer reproduces and relevant checks pass. Preserve unrelated local changes.',
5380
5354
  ]),
5381
5355
  ]),
5382
5356
  ...(options.findingInstructions === undefined
@@ -5426,20 +5400,19 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
5426
5400
  `model=${JSON.stringify(model)}`,
5427
5401
  "--config",
5428
5402
  `model_reasoning_effort=${JSON.stringify(reasoningEffort)}`,
5429
- ...codexOverrides
5403
+ ...(options.serviceTier === undefined
5404
+ ? []
5405
+ : ["--config", `service_tier=${JSON.stringify(options.serviceTier)}`]),
5406
+ ...codex
5430
5407
  .filter((value) => value.startsWith("analytics.") || value.startsWith("analytics="))
5431
5408
  .flatMap((value) => ["--config", value]),
5432
- ...(options.provider === undefined
5409
+ ...(provider === undefined
5433
5410
  ? []
5434
- : ["--config", `model_provider=${JSON.stringify(options.provider)}`]),
5435
- ...(options.provider === undefined ||
5436
- options.providerConfiguration === undefined
5437
- ? []
5438
- : modelProviderConfigOverride(resolveCommandAuthConfig({
5439
- model_providers: {
5440
- [options.provider]: options.providerConfiguration,
5441
- },
5442
- }, configuredCodexHome(options.environment ?? dependencies.environment))).flatMap((value) => ["--config", value])),
5411
+ : ["--config", `model_provider=${JSON.stringify(provider)}`]),
5412
+ ...modelProviderConfigOverride(effectiveOverrides).flatMap((value) => [
5413
+ "--config",
5414
+ value,
5415
+ ]),
5443
5416
  "--config",
5444
5417
  verify || assess
5445
5418
  ? 'approval_policy="on-request"'
@@ -5469,8 +5442,8 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
5469
5442
  command: verify ? "verify-fix" : patch || assess ? "patch" : "validate",
5470
5443
  auth: options.auth ?? "auto",
5471
5444
  directory,
5472
- modelProvider: options.provider,
5473
- providerConfiguration: options.providerConfiguration,
5445
+ modelProvider: provider,
5446
+ codexOverrides: effectiveOverrides,
5474
5447
  stdout,
5475
5448
  stderr,
5476
5449
  ...(appServer
@@ -5492,7 +5465,6 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
5492
5465
  export async function readSkillCommandOutput(stream, appServer) {
5493
5466
  let message;
5494
5467
  let error;
5495
- let malformed = false;
5496
5468
  let threadId;
5497
5469
  let turnId;
5498
5470
  let completed = false;
@@ -5548,11 +5520,9 @@ export async function readSkillCommandOutput(stream, appServer) {
5548
5520
  event = JSON.parse(line);
5549
5521
  }
5550
5522
  catch {
5551
- malformed = true;
5552
5523
  continue;
5553
5524
  }
5554
5525
  if (typeof event !== "object" || event === null) {
5555
- malformed = true;
5556
5526
  continue;
5557
5527
  }
5558
5528
  const value = event;
@@ -5583,7 +5553,7 @@ export async function readSkillCommandOutput(stream, appServer) {
5583
5553
  }
5584
5554
  else if (value["id"] === 1 || value["id"] === "login") {
5585
5555
  if (value["id"] === 1) {
5586
- send({ method: "notifications/initialized" });
5556
+ send({ method: "initialized" });
5587
5557
  if (appServer.apiKey !== undefined) {
5588
5558
  send({
5589
5559
  id: "login",
@@ -5756,7 +5726,6 @@ export async function readSkillCommandOutput(stream, appServer) {
5756
5726
  return {
5757
5727
  ...(message === undefined ? {} : { message }),
5758
5728
  ...(error === undefined ? {} : { error }),
5759
- malformed,
5760
5729
  ...(appServer === undefined ? {} : { completed }),
5761
5730
  ...(sandboxUnavailable ? { sandboxUnavailable } : {}),
5762
5731
  };
@@ -5796,36 +5765,8 @@ function incurErrorMessage(output) {
5796
5765
  }
5797
5766
  async function runExport(arguments_, output, errorOutput, dependencies) {
5798
5767
  try {
5799
- const canonicalScan = await realpath(arguments_.scanDir).catch(() => arguments_.scanDir);
5800
- const scanRelativeOutput = relative(arguments_.scanDir, arguments_.output);
5801
- const scanLocalOutput = join("exports", EXPORT_DEFAULT_OUTPUTS[arguments_.format]);
5802
- if (arguments_.output !== "-" &&
5803
- !isOutsidePath(scanRelativeOutput) &&
5804
- scanRelativeOutput !== scanLocalOutput) {
5805
- throw new CodexSecurityError("The export output path cannot overwrite a scan artifact.");
5806
- }
5807
- const outputPath = arguments_.output === "-"
5808
- ? "-"
5809
- : !isOutsidePath(scanRelativeOutput)
5810
- ? join(canonicalScan, scanRelativeOutput)
5811
- : join(await realpath(dirname(arguments_.output)).catch((error) => {
5812
- if (error.code === "ENOENT") {
5813
- throw new CodexSecurityError(`Export output directory does not exist: ${dirname(arguments_.output)}. Create the directory and retry.`);
5814
- }
5815
- throw error;
5816
- }), basename(arguments_.output));
5817
- if (arguments_.output !== "-") {
5818
- const currentDirectory = dependencies.currentDirectory();
5819
- const outputFromCurrent = relative(currentDirectory, arguments_.output);
5820
- if (!isOutsidePath(outputFromCurrent)) {
5821
- const canonicalCurrent = await realpath(currentDirectory).catch(() => currentDirectory);
5822
- if (relative(resolve(canonicalCurrent, outputFromCurrent), outputPath) !==
5823
- "") {
5824
- throw new CodexSecurityError("The export output path cannot traverse a repository symlink.");
5825
- }
5826
- }
5827
- }
5828
- const contents = await dependencies.exportFindings({ ...arguments_, scanDir: canonicalScan, output: outputPath }, output);
5768
+ const prepared = await resolveArtifactExportOutput(arguments_, dependencies.currentDirectory());
5769
+ const contents = await dependencies.exportFindings(prepared, output);
5829
5770
  if (arguments_.output === "-") {
5830
5771
  if (contents !== undefined) {
5831
5772
  await writeCliOutput(output, Buffer.from(contents));
@@ -5853,12 +5794,7 @@ async function chooseInteractiveAuthentication(options, errorOutput, dependencie
5853
5794
  const authentication = scanAuthentication(dependencies.environment, auth, provider);
5854
5795
  if (authentication.method !== "api_key")
5855
5796
  return auth;
5856
- const prompt = dependencies.scanAuthenticationPrompt ??
5857
- createBulkScanDiscoveryDependencies({
5858
- output: errorOutput,
5859
- now: dependencies.now,
5860
- currentDirectory: dependencies.currentDirectory,
5861
- }).prompt;
5797
+ const prompt = dependencies.scanAuthenticationPrompt ?? createTerminalPrompt(errorOutput);
5862
5798
  const hasStoredSignIn = dependencies.hasStoredChatGPTSignIn;
5863
5799
  if (!prompt.isInteractive() ||
5864
5800
  hasStoredSignIn === undefined ||
@@ -5932,11 +5868,12 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5932
5868
  const diagnostic = (event, fields = {}) => {
5933
5869
  if (!verbose)
5934
5870
  return;
5935
- const attributes = Object.entries(fields).flatMap(([name, value]) => value === undefined
5936
- ? []
5937
- : [
5938
- `${name}=${JSON.stringify(typeof value === "string" ? diagnosticValue(value) : value)}`,
5939
- ]);
5871
+ const attributes = Object.entries(fields).flatMap(([name, value]) => {
5872
+ if (value === undefined)
5873
+ return [];
5874
+ const displayed = typeof value === "string" ? diagnosticValue(value) : value;
5875
+ return [`${name}=${JSON.stringify(displayed)}`];
5876
+ });
5940
5877
  writeAboveProgress(() => {
5941
5878
  errorOutput.write(`codex-security: debug: ${event}${attributes.length === 0 ? "" : ` ${attributes.join(" ")}`}\n`);
5942
5879
  });
@@ -5981,11 +5918,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5981
5918
  const onInterrupt = signalListener("SIGINT");
5982
5919
  const onTerminate = signalListener("SIGTERM");
5983
5920
  const removeSignalListeners = () => {
5984
- dependencies.removeSignalListener("SIGINT", onInterrupt);
5985
- dependencies.removeSignalListener("SIGTERM", onTerminate);
5921
+ signalHandlers(dependencies, "remove", onInterrupt, onTerminate);
5986
5922
  };
5987
- dependencies.addSignalListener("SIGINT", onInterrupt);
5988
- dependencies.addSignalListener("SIGTERM", onTerminate);
5923
+ signalHandlers(dependencies, "add", onInterrupt, onTerminate);
5989
5924
  let security = null;
5990
5925
  let result = null;
5991
5926
  let preflight = null;
@@ -5994,6 +5929,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
5994
5929
  let providerOptions = { provider: "openai" };
5995
5930
  let auth = arguments_.auth;
5996
5931
  let patchAnalyticsOverride;
5932
+ let patchServiceTier;
5997
5933
  let selectedAuthentication = null;
5998
5934
  let repository = "";
5999
5935
  let failed = false;
@@ -6015,11 +5951,11 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6015
5951
  };
6016
5952
  ({ model: effectiveModel, reasoningEffort: effectiveReasoningEffort } =
6017
5953
  scanModelConfiguration(effectiveConfiguration));
5954
+ patchServiceTier =
5955
+ resolveCodexProfile(effectiveConfiguration)["service_tier"] ?? "default";
6018
5956
  const provider = scanModelProvider(effectiveConfiguration);
6019
5957
  const analytics = effectiveConfiguration["analytics"];
6020
- if (analytics !== undefined &&
6021
- isJsonObject(analytics) &&
6022
- analytics["enabled"] !== undefined) {
5958
+ if (isJsonObject(analytics) && analytics["enabled"] !== undefined) {
6023
5959
  patchAnalyticsOverride = `analytics.enabled=${JSON.stringify(analytics["enabled"])}`;
6024
5960
  }
6025
5961
  auth =
@@ -6081,7 +6017,6 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6081
6017
  : { maxCostUsd: arguments_.maxCostUsd }),
6082
6018
  clock: dependencies,
6083
6019
  color: dependencies.environment["NO_COLOR"] === undefined,
6084
- sanitize: safeErrorMessage,
6085
6020
  input: scanInput,
6086
6021
  onInterrupt,
6087
6022
  });
@@ -6189,6 +6124,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6189
6124
  },
6190
6125
  onAuthentication: (authentication) => {
6191
6126
  selectedAuthentication = authentication;
6127
+ const bedrock = providerOptions.provider === "amazon-bedrock" ||
6128
+ authentication.method === "aws_credentials";
6192
6129
  diagnostic("authentication.selected", {
6193
6130
  requested: auth ?? DEFAULT_SCAN_AUTH,
6194
6131
  method: authentication.method,
@@ -6203,6 +6140,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6203
6140
  : authentication.method === "command"
6204
6141
  ? "Using native Codex command authentication"
6205
6142
  : "Using stored Codex credentials");
6143
+ if (bedrock) {
6144
+ dashboard.note("Amazon Bedrock uses AWS authentication; OpenAI sign-in is not required for model access or local results.");
6145
+ }
6206
6146
  return;
6207
6147
  }
6208
6148
  progress?.stopTimer();
@@ -6219,6 +6159,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6219
6159
  else {
6220
6160
  progress?.stage("Authentication: stored Codex credentials.");
6221
6161
  }
6162
+ if (bedrock) {
6163
+ progress?.stage("Amazon Bedrock uses AWS authentication; OpenAI sign-in is not required for model access or local results.");
6164
+ }
6222
6165
  progress?.startTimer("Preparing scan");
6223
6166
  },
6224
6167
  onTrustedAccessStatus: (status) => {
@@ -6400,7 +6343,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6400
6343
  const costLimitFailure = failure instanceof ScanCostLimitExceededError ? failure : undefined;
6401
6344
  const message = failure instanceof OutputInsideProtectedRootError
6402
6345
  ? errorMessage(protectedRootErrorMessage(failure))
6403
- : scanFailureMessage(failure, selectedAuthentication);
6346
+ : scanFailureMessage(failure, selectedAuthentication, providerOptions.provider);
6404
6347
  diagnostic("scan.failed", {
6405
6348
  classification: costLimitFailure !== undefined
6406
6349
  ? "cost_limit_exceeded"
@@ -6519,11 +6462,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6519
6462
  (dependencies.patchEditor !== undefined || process.stdin.isTTY === true)) {
6520
6463
  const confirmed = arguments_.patch ||
6521
6464
  (await (dependencies.confirmPatchReview ??
6522
- createBulkScanDiscoveryDependencies({
6523
- output: errorOutput,
6524
- now: dependencies.now,
6525
- currentDirectory: dependencies.currentDirectory,
6526
- }).prompt.confirm)("Review and patch these findings?"));
6465
+ createTerminalPrompt(errorOutput).confirm)("Review and patch these findings?"));
6527
6466
  if (confirmed) {
6528
6467
  const selectPatches = dependencies.patchEditor ??
6529
6468
  (async (target, candidates) => {
@@ -6548,13 +6487,17 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6548
6487
  patchSelection.occurrenceIds.includes(finding.occurrenceId))),
6549
6488
  };
6550
6489
  try {
6551
- patches = await runFindingPatches(selected, [
6552
- `model=${JSON.stringify(effectiveModel)}`,
6553
- ...(patchAnalyticsOverride === undefined
6554
- ? []
6555
- : [patchAnalyticsOverride]),
6556
- ], effectiveReasoningEffort, errorOutput, dependencies, {
6490
+ patches = await runFindingPatches(selected, {
6491
+ codex: [
6492
+ `model=${JSON.stringify(effectiveModel)}`,
6493
+ `model_reasoning_effort=${JSON.stringify(effectiveReasoningEffort)}`,
6494
+ ...(patchAnalyticsOverride === undefined
6495
+ ? []
6496
+ : [patchAnalyticsOverride]),
6497
+ ],
6498
+ }, errorOutput, dependencies, {
6557
6499
  ...providerOptions,
6500
+ serviceTier: patchServiceTier,
6558
6501
  safetyIdentifier: arguments_.safetyIdentifier,
6559
6502
  auth,
6560
6503
  findingInstructions: patchSelection?.instructions,
@@ -6569,7 +6512,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
6569
6512
  }
6570
6513
  }
6571
6514
  catch (error) {
6572
- errorOutput.write(`codex-security: ${safeErrorMessage(error)}\n`);
6515
+ errorOutput.write(`codex-security: ${diagnosticValue(error)}\n`);
6573
6516
  scanData = { ...scanData, patches };
6574
6517
  return completedScan(2);
6575
6518
  }
@@ -6634,10 +6577,9 @@ function authenticationFailureMessage(authentication) {
6634
6577
  "Sign in again with 'codex-security login --with-api-key' or provide a valid API key.");
6635
6578
  }
6636
6579
  if (authentication?.method === "api_key") {
6637
- const openAiKey = authentication.source === "OPENAI_API_KEY" ||
6638
- authentication.source === "CODEX_API_KEY";
6639
6580
  return (`Authentication failed using ${authentication.source}. ` +
6640
- (openAiKey
6581
+ (authentication.source === "OPENAI_API_KEY" ||
6582
+ authentication.source === "CODEX_API_KEY"
6641
6583
  ? "Retry with '--auth chatgpt' or provide a valid API key."
6642
6584
  : `Provide a valid ${authentication.source} for the selected provider.`));
6643
6585
  }
@@ -6650,17 +6592,41 @@ function authenticationFailureMessage(authentication) {
6650
6592
  }
6651
6593
  return "Authentication failed. Check the selected provider's credentials and retry.";
6652
6594
  }
6653
- function scanFailureMessage(error, authentication) {
6595
+ function scanFailureMessage(error, authentication, provider) {
6654
6596
  // A local failure keeps its own message. Classification matches bare words
6655
6597
  // such as "permission denied" anywhere in the text, so an EACCES from a
6656
6598
  // read-only TMPDIR would otherwise be reported as a credential problem.
6657
- //
6658
- // The advice branches below still replace the underlying text rather than
6659
- // appending it. That is deliberate: upstream authentication and authorization
6660
- // errors can name the organization or project, which must not reach stderr or
6661
- // the JSON error field.
6662
6599
  if (isLocalScanFailure(error))
6663
6600
  return diagnosticValue(error);
6601
+ const classification = classifyConnectionFailure(error);
6602
+ if (provider === "amazon-bedrock" ||
6603
+ authentication?.method === "aws_credentials") {
6604
+ const detail = diagnosticValue(error);
6605
+ switch (classification) {
6606
+ case "unauthorized":
6607
+ if (authentication?.method === "command") {
6608
+ return `${detail}\n${authenticationFailureMessage(authentication)}`;
6609
+ }
6610
+ if (authentication?.method === "aws_credentials") {
6611
+ return (`${detail}\n${authenticationFailureMessage(authentication)} ` +
6612
+ (authentication.source === "AWS_BEARER_TOKEN_BEDROCK"
6613
+ ? "Refresh AWS_BEARER_TOKEN_BEDROCK in the environment running this command."
6614
+ : "Refresh the selected AWS credentials in the environment running this command. Temporary access-key credentials also require AWS_SESSION_TOKEN."));
6615
+ }
6616
+ return `${detail}\nAmazon Bedrock authentication failed. Check the credentials configured for the selected provider.`;
6617
+ case "forbidden":
6618
+ if (authentication?.method === "command") {
6619
+ return (`${detail}\nThe configured provider auth command's credentials cannot access the Amazon Bedrock model. ` +
6620
+ "Check the configured provider auth command, AWS identity and Bedrock model permissions, configured AWS region, and model ID.");
6621
+ }
6622
+ return (`${detail}\nThe AWS credentials${authentication?.method === "aws_credentials" ? ` from ${authentication.source}` : ""} cannot access the configured Amazon Bedrock model. ` +
6623
+ "Check your AWS identity and Bedrock model permissions, configured AWS region, and model ID.");
6624
+ case "rate_limited":
6625
+ return `${detail}\nAmazon Bedrock throttled the request. Check the model quota in the configured AWS region and retry.`;
6626
+ default:
6627
+ return detail;
6628
+ }
6629
+ }
6664
6630
  const message = errorMessage(error);
6665
6631
  const nativeRefreshRecovery = message.match(/\b(?:your access token could not be refreshed because you have since logged out or signed in to another account\. Please sign in again\.|your authentication session could not be refreshed automatically\. Please log out and sign in again\.)/iu)?.[0];
6666
6632
  if (nativeRefreshRecovery !== undefined)
@@ -6671,17 +6637,13 @@ function scanFailureMessage(error, authentication) {
6671
6637
  "If the sign-in recently changed, check 'npx @openai/codex-security login status' and retry. " +
6672
6638
  "Otherwise run 'npx @openai/codex-security logout', then 'npx @openai/codex-security login'.");
6673
6639
  }
6674
- switch (classifyConnectionFailure(error)) {
6640
+ switch (classification) {
6675
6641
  case "unauthorized":
6676
6642
  return authenticationFailureMessage(authentication);
6677
6643
  case "forbidden":
6678
6644
  if (authentication?.method === "command") {
6679
6645
  return "The configured Codex provider denied access. Check the command credentials and provider permissions.";
6680
6646
  }
6681
- if (authentication?.method === "aws_credentials") {
6682
- return (`The AWS credentials from ${authentication.source} cannot access the configured Amazon Bedrock model. ` +
6683
- "Check your AWS identity and Bedrock model permissions.");
6684
- }
6685
6647
  return authentication?.method === "api_key"
6686
6648
  ? `The API key from ${authentication.source} cannot access the configured model. ` +
6687
6649
  "Retry with '--auth chatgpt' or use an API key with model access."
@@ -6743,9 +6705,8 @@ async function readDeepScanStop(result, maxCostUsd, runWorkbench) {
6743
6705
  return undefined;
6744
6706
  const { maxDiscoveryRuns, maxTimeHours } = state.config;
6745
6707
  if (state.dispatchedCount >= maxDiscoveryRuns) {
6746
- const stillFindingIssues = state.completionSequence > 0 && state.noNewStreak === 0;
6747
6708
  return {
6748
- reason: `Reached the limit of ${maxDiscoveryRuns} review rounds. ${stillFindingIssues ? "The latest review still found new issues." : "More issues may remain."}`,
6709
+ reason: `Reached the limit of ${maxDiscoveryRuns} review rounds. ${state.completionSequence > 0 && state.noNewStreak === 0 ? "The latest review still found new issues." : "More issues may remain."}`,
6749
6710
  nextStep: `To scan further, rerun with --max-discovery-runs greater than ${maxDiscoveryRuns}.`,
6750
6711
  };
6751
6712
  }
@@ -6770,12 +6731,7 @@ function printScanSummary(result, progress, errorOutput, color, showCost, deepSc
6770
6731
  for (const finding of findings) {
6771
6732
  severities.set(finding.severity.level, (severities.get(finding.severity.level) ?? 0) + 1);
6772
6733
  }
6773
- const severitySummary = DISPLAY_SEVERITIES.map((severity) => {
6774
- const count = severities.get(severity);
6775
- return count === undefined ? null : `${count} ${severity}`;
6776
- })
6777
- .filter((value) => value !== null)
6778
- .join(", ");
6734
+ const severitySummary = SCAN_SEVERITIES.flatMap((severity) => severities.has(severity) ? `${severities.get(severity)} ${severity}` : []).join(", ");
6779
6735
  const started = Date.parse(result.manifest.scan.startedAt);
6780
6736
  const completed = Date.parse(result.manifest.scan.completedAt);
6781
6737
  const elapsed = Number.isFinite(started) &&
@@ -6799,8 +6755,12 @@ function printScanSummary(result, progress, errorOutput, color, showCost, deepSc
6799
6755
  : severities.has("medium")
6800
6756
  ? 33
6801
6757
  : 36;
6802
- errorOutput.write(`\n ${paint("REPORT", "1;36")} ${paint(errorMessage(result.reportPath), 4)}\n\n` +
6803
- ` ${paint("FINDINGS", 1)} ${paint(`${findingCount}${findingSummary === "" ? "" : ` (${findingSummary})`}`, findingColor)}\n` +
6758
+ const threatModelPath = result.threatModelPath;
6759
+ errorOutput.write(`\n ${paint("REPORT", "1;36")} ${paint(errorMessage(result.reportPath), 4)}\n` +
6760
+ (threatModelPath === null
6761
+ ? ""
6762
+ : ` ${paint("THREAT MODEL", "1;36")} ${paint(errorMessage(threatModelPath), 4)}\n`) +
6763
+ `\n ${paint("FINDINGS", 1)} ${paint(`${findingCount}${findingSummary === "" ? "" : ` (${findingSummary})`}`, findingColor)}\n` +
6804
6764
  ` ${paint("COVERAGE", 1)} ${result.coverage.completeness}\n` +
6805
6765
  (deepScanStop === undefined
6806
6766
  ? ""
@@ -6841,19 +6801,18 @@ function protectedRootErrorMessage(error) {
6841
6801
  ? "Scan artifacts cannot be written inside the protected scan root."
6842
6802
  : "Temporary and runtime files cannot be created inside the protected scan root.";
6843
6803
  const suggestion = suggestedOutputDirectory(error.protectedRoot);
6844
- const recovery = error.pathKind === "output"
6845
- ? suggestion === undefined
6846
- ? "Choose a private output directory outside the protected root."
6847
- : `Re-run with --output-dir ${quoteCliPath(suggestion)}.`
6848
- : suggestion === undefined
6849
- ? "Set TMPDIR (or TEMP on Windows) to a writable directory outside the protected root."
6850
- : `Set TMPDIR (or TEMP on Windows) to ${quoteCliPath(suggestion)} after creating that directory.`;
6851
6804
  return [
6852
6805
  `${description} must be outside the scanned directory and any enclosing Git worktree.`,
6853
6806
  ` Resolved path: ${error.outputDirectory}`,
6854
6807
  ` Protected root: ${error.protectedRoot}`,
6855
6808
  ` Reason: ${reason}`,
6856
- recovery,
6809
+ error.pathKind === "output"
6810
+ ? suggestion === undefined
6811
+ ? "Choose a private output directory outside the protected root."
6812
+ : `Re-run with --output-dir ${quoteCliPath(suggestion)}.`
6813
+ : suggestion === undefined
6814
+ ? "Set TMPDIR (or TEMP on Windows) to a writable directory outside the protected root."
6815
+ : `Set TMPDIR (or TEMP on Windows) to ${quoteCliPath(suggestion)} after creating that directory.`,
6857
6816
  ].join("\n");
6858
6817
  }
6859
6818
  function suggestedOutputDirectory(protectedRoot) {
@@ -6968,12 +6927,12 @@ export function parseCodexOverrides(values, model, effort, provider, defaults) {
6968
6927
  }
6969
6928
  for (const value of values) {
6970
6929
  const separator = value.indexOf("=");
6971
- const key = separator < 0 ? "" : value.slice(0, separator);
6930
+ const key = separator < 0 ? "" : value.slice(0, separator).trim();
6972
6931
  const literal = separator < 0 ? "" : value.slice(separator + 1);
6973
6932
  if (key.length === 0 || literal.length === 0) {
6974
6933
  throw new CodexSecurityError("--codex expects KEY=VALUE");
6975
6934
  }
6976
- const parts = key.split(".");
6935
+ const parts = key.split(".").map((part) => part.trim());
6977
6936
  if (parts.some((part) => part.length === 0 ||
6978
6937
  part === "__proto__" ||
6979
6938
  part === "prototype" ||
@@ -7150,9 +7109,7 @@ export class Progress {
7150
7109
  }
7151
7110
  #line(message) {
7152
7111
  const elapsedSeconds = this.elapsedSeconds;
7153
- const minutes = Math.floor(elapsedSeconds / 60);
7154
- const seconds = elapsedSeconds % 60;
7155
- return `[${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}] ${message}`;
7112
+ return `[${String(Math.floor(elapsedSeconds / 60)).padStart(2, "0")}:${String(elapsedSeconds % 60).padStart(2, "0")}] ${message}`;
7156
7113
  }
7157
7114
  #observeStreamErrors() {
7158
7115
  this.#streamErrorsActive = true;
@@ -7189,9 +7146,6 @@ function interruptedExit(signal, scanDir, errorOutput) {
7189
7146
  : `codex-security: Partial output was kept at ${errorMessage(scanDir)}.\n`);
7190
7147
  return ctrlC ? 130 : 143;
7191
7148
  }
7192
- function isJsonObject(value) {
7193
- return typeof value === "object" && value !== null && !Array.isArray(value);
7194
- }
7195
7149
  function invokedAsMain() {
7196
7150
  const entrypoint = process.argv[1];
7197
7151
  if (entrypoint === undefined)
@@ -7205,6 +7159,11 @@ function invokedAsMain() {
7205
7159
  return false;
7206
7160
  }
7207
7161
  }
7162
+ const interruptedExitCode = (signal) => signal.reason === "SIGINT"
7163
+ ? 130
7164
+ : signal.reason === "SIGTERM"
7165
+ ? 143
7166
+ : undefined;
7208
7167
  if (invokedAsMain()) {
7209
7168
  void main().then((exitCode) => {
7210
7169
  process.exitCode = exitCode;
@@ -7213,4 +7172,17 @@ if (invokedAsMain()) {
7213
7172
  process.exitCode = 2;
7214
7173
  });
7215
7174
  }
7175
+ function listenForAbort(dependencies, controller) {
7176
+ const onInterrupt = () => controller.abort("SIGINT");
7177
+ const onTerminate = () => controller.abort("SIGTERM");
7178
+ dependencies.addSignalListener("SIGINT", onInterrupt);
7179
+ dependencies.addSignalListener("SIGTERM", onTerminate);
7180
+ return () => {
7181
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
7182
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
7183
+ };
7184
+ }
7185
+ function withoutLinearCredentials(environment) {
7186
+ return Object.fromEntries(Object.entries(environment).filter(([name]) => !/^(?:CODEX_SECURITY_)?LINEAR_(?:API_KEY|ACCESS_TOKEN)$/iu.test(name)));
7187
+ }
7216
7188
  //# sourceMappingURL=cli.js.map