@openai/codex-security 0.4.0 → 0.5.1

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 (290) hide show
  1. package/README.md +52 -9
  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/win32-arm64/windows.node +0 -0
  5. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  6. package/_bundled_plugin/mcp/permission-profile-preflight.mjs +60 -9
  7. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  8. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  9. package/_bundled_plugin/references/core-scan.md +2 -0
  10. package/_bundled_plugin/references/final-report.md +5 -1
  11. package/_bundled_plugin/references/investigation-time-budget.md +11 -0
  12. package/_bundled_plugin/references/sarif-adapter.md +1 -0
  13. package/_bundled_plugin/references/scan-prologue.md +2 -6
  14. package/_bundled_plugin/references/scan-runtime.md +15 -0
  15. package/_bundled_plugin/references/threat-model.md +2 -0
  16. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +6 -2
  17. package/_bundled_plugin/scripts/deep_scan_workbench.py +7 -0
  18. package/_bundled_plugin/scripts/finalize_scan_contract.py +92 -44
  19. package/_bundled_plugin/scripts/finding_preview.py +5 -3
  20. package/_bundled_plugin/scripts/generate_in_scope_files.py +6 -6
  21. package/_bundled_plugin/scripts/generate_rank_input.py +13 -6
  22. package/_bundled_plugin/scripts/launch_codex_security_mcp +39 -4
  23. package/_bundled_plugin/scripts/report_projection.py +2 -1
  24. package/_bundled_plugin/scripts/snapshot_sqlite.py +7 -0
  25. package/_bundled_plugin/scripts/threat_model_projection.py +1 -3
  26. package/_bundled_plugin/scripts/windows_scan_local_files.py +43 -1
  27. package/_bundled_plugin/scripts/workbench/saved_coverage.py +234 -0
  28. package/_bundled_plugin/scripts/workbench_cli.py +5 -10
  29. package/_bundled_plugin/scripts/workbench_constants.py +4 -0
  30. package/_bundled_plugin/scripts/workbench_db.py +68 -39
  31. package/_bundled_plugin/scripts/workbench_native_indexes.py +10 -7
  32. package/_bundled_plugin/scripts/workbench_progress.py +0 -50
  33. package/_bundled_plugin/scripts/workbench_publication.py +4 -3
  34. package/_bundled_plugin/scripts/workbench_remediation.py +5 -1
  35. package/_bundled_plugin/scripts/workbench_saved_results.py +542 -148
  36. package/_bundled_plugin/scripts/workbench_scan_history.py +82 -80
  37. package/_bundled_plugin/scripts/workbench_scan_start.py +12 -4
  38. package/_bundled_plugin/scripts/workbench_scan_usage.py +246 -38
  39. package/_bundled_plugin/scripts/workbench_schema.py +1 -1
  40. package/_bundled_plugin/scripts/workbench_source_excerpt.py +74 -51
  41. package/_bundled_plugin/scripts/workbench_source_scopes.py +388 -0
  42. package/_bundled_plugin/scripts/workbench_target.py +28 -12
  43. package/_bundled_plugin/scripts/workbench_validation.py +52 -13
  44. package/_bundled_plugin/shared/workbench-history-repairs.json +19 -0
  45. package/_bundled_plugin/shared/workbench-migrations.json +15 -0
  46. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +1 -1
  47. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +4 -2
  48. package/_bundled_plugin/skills/security-scan/SKILL.md +3 -1
  49. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +2 -2
  50. package/dist/api.d.ts +4 -3
  51. package/dist/api.d.ts.map +1 -1
  52. package/dist/api.js +215 -93
  53. package/dist/api.js.map +1 -1
  54. package/dist/artifact-export.d.ts +2 -1
  55. package/dist/artifact-export.d.ts.map +1 -1
  56. package/dist/artifact-export.js +38 -23
  57. package/dist/artifact-export.js.map +1 -1
  58. package/dist/classify-scan-severity.d.ts.map +1 -1
  59. package/dist/classify-scan-severity.js +16 -18
  60. package/dist/classify-scan-severity.js.map +1 -1
  61. package/dist/classify-severity-records.d.ts +76 -0
  62. package/dist/classify-severity-records.d.ts.map +1 -0
  63. package/dist/classify-severity-records.js +141 -0
  64. package/dist/classify-severity-records.js.map +1 -0
  65. package/dist/classify-severity.d.ts +1 -23
  66. package/dist/classify-severity.d.ts.map +1 -1
  67. package/dist/classify-severity.js +3 -24
  68. package/dist/classify-severity.js.map +1 -1
  69. package/dist/cli-daybreak.d.ts +5 -0
  70. package/dist/cli-daybreak.d.ts.map +1 -0
  71. package/dist/cli-daybreak.js +89 -0
  72. package/dist/cli-daybreak.js.map +1 -0
  73. package/dist/cli-help.d.ts.map +1 -1
  74. package/dist/cli-help.js +2 -0
  75. package/dist/cli-help.js.map +1 -1
  76. package/dist/cli.d.ts +9 -3
  77. package/dist/cli.d.ts.map +1 -1
  78. package/dist/cli.js +957 -738
  79. package/dist/cli.js.map +1 -1
  80. package/dist/cloud-publish.js +1 -1
  81. package/dist/cloud-publish.js.map +1 -1
  82. package/dist/codeowners.js +2 -2
  83. package/dist/codeowners.js.map +1 -1
  84. package/dist/codex-sdk-environment.js +1 -1
  85. package/dist/codex-sdk-environment.js.map +1 -1
  86. package/dist/component-plan.d.ts.map +1 -1
  87. package/dist/component-plan.js +3 -2
  88. package/dist/component-plan.js.map +1 -1
  89. package/dist/component-scan.js +2 -2
  90. package/dist/component-scan.js.map +1 -1
  91. package/dist/config.d.ts +12 -0
  92. package/dist/config.d.ts.map +1 -1
  93. package/dist/config.js +15 -5
  94. package/dist/config.js.map +1 -1
  95. package/dist/contract.d.ts +5 -0
  96. package/dist/contract.d.ts.map +1 -1
  97. package/dist/contract.js +65 -17
  98. package/dist/contract.js.map +1 -1
  99. package/dist/cost-model.d.ts.map +1 -1
  100. package/dist/cost-model.js +7 -2
  101. package/dist/cost-model.js.map +1 -1
  102. package/dist/cost.d.ts +2 -1
  103. package/dist/cost.d.ts.map +1 -1
  104. package/dist/cost.js +17 -8
  105. package/dist/cost.js.map +1 -1
  106. package/dist/custom-validation-prompt.js +3 -3
  107. package/dist/custom-validation-prompt.js.map +1 -1
  108. package/dist/custom-validation.d.ts.map +1 -1
  109. package/dist/custom-validation.js +2 -5
  110. package/dist/custom-validation.js.map +1 -1
  111. package/dist/deduplication/codex-review.d.ts.map +1 -1
  112. package/dist/deduplication/codex-review.js +8 -6
  113. package/dist/deduplication/codex-review.js.map +1 -1
  114. package/dist/deduplication/deduplication-prompts.d.ts +1 -1
  115. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  116. package/dist/deduplication/deduplication-prompts.js +2 -2
  117. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  118. package/dist/deduplication/local.d.ts.map +1 -1
  119. package/dist/deduplication/local.js +5 -2
  120. package/dist/deduplication/local.js.map +1 -1
  121. package/dist/deduplication/records.js +1 -1
  122. package/dist/deduplication/records.js.map +1 -1
  123. package/dist/deduplication/retry.d.ts.map +1 -1
  124. package/dist/deduplication/retry.js +5 -0
  125. package/dist/deduplication/retry.js.map +1 -1
  126. package/dist/deduplication/scan.d.ts.map +1 -1
  127. package/dist/deduplication/scan.js +15 -10
  128. package/dist/deduplication/scan.js.map +1 -1
  129. package/dist/deep-config.d.ts +4 -1
  130. package/dist/deep-config.d.ts.map +1 -1
  131. package/dist/deep-config.js +21 -1
  132. package/dist/deep-config.js.map +1 -1
  133. package/dist/deep-scan.d.ts +6 -0
  134. package/dist/deep-scan.d.ts.map +1 -1
  135. package/dist/deep-scan.js +8 -6
  136. package/dist/deep-scan.js.map +1 -1
  137. package/dist/findings-import.d.ts +1 -1
  138. package/dist/findings-import.d.ts.map +1 -1
  139. package/dist/findings-import.js +26 -6
  140. package/dist/findings-import.js.map +1 -1
  141. package/dist/git-remote.d.ts +10 -0
  142. package/dist/git-remote.d.ts.map +1 -0
  143. package/dist/git-remote.js +24 -0
  144. package/dist/git-remote.js.map +1 -0
  145. package/dist/github.d.ts.map +1 -1
  146. package/dist/github.js +5 -7
  147. package/dist/github.js.map +1 -1
  148. package/dist/host-protocol.d.ts +1 -0
  149. package/dist/host-protocol.d.ts.map +1 -1
  150. package/dist/host-protocol.js +2 -2
  151. package/dist/host-protocol.js.map +1 -1
  152. package/dist/host-records-protocol.d.ts +15 -0
  153. package/dist/host-records-protocol.d.ts.map +1 -0
  154. package/dist/host-records-protocol.js +15 -0
  155. package/dist/host-records-protocol.js.map +1 -0
  156. package/dist/hosted-remediation-protocol.d.ts +5 -0
  157. package/dist/hosted-remediation-protocol.d.ts.map +1 -0
  158. package/dist/hosted-remediation-protocol.js +26 -0
  159. package/dist/hosted-remediation-protocol.js.map +1 -0
  160. package/dist/hosted-remediation.d.ts +89 -0
  161. package/dist/hosted-remediation.d.ts.map +1 -0
  162. package/dist/hosted-remediation.js +122 -0
  163. package/dist/hosted-remediation.js.map +1 -0
  164. package/dist/hosted-scan.d.ts +1 -6
  165. package/dist/hosted-scan.d.ts.map +1 -1
  166. package/dist/hosted-scan.js +2 -2
  167. package/dist/hosted-scan.js.map +1 -1
  168. package/dist/import-scan.d.ts +1 -0
  169. package/dist/import-scan.d.ts.map +1 -1
  170. package/dist/import-scan.js +5 -1
  171. package/dist/import-scan.js.map +1 -1
  172. package/dist/index.d.ts +9 -1
  173. package/dist/index.d.ts.map +1 -1
  174. package/dist/index.js +4 -0
  175. package/dist/index.js.map +1 -1
  176. package/dist/knowledge-base.d.ts.map +1 -1
  177. package/dist/knowledge-base.js +87 -7
  178. package/dist/knowledge-base.js.map +1 -1
  179. package/dist/multiscan.d.ts.map +1 -1
  180. package/dist/multiscan.js +65 -29
  181. package/dist/multiscan.js.map +1 -1
  182. package/dist/patch-publication.d.ts +26 -0
  183. package/dist/patch-publication.d.ts.map +1 -0
  184. package/dist/patch-publication.js +105 -0
  185. package/dist/patch-publication.js.map +1 -0
  186. package/dist/patch-tui.d.ts.map +1 -1
  187. package/dist/patch-tui.js +4 -1
  188. package/dist/patch-tui.js.map +1 -1
  189. package/dist/project-config-schema.d.ts +2 -0
  190. package/dist/project-config-schema.d.ts.map +1 -1
  191. package/dist/project-config-schema.js +1 -0
  192. package/dist/project-config-schema.js.map +1 -1
  193. package/dist/project-config.d.ts +1 -0
  194. package/dist/project-config.d.ts.map +1 -1
  195. package/dist/project-config.js +29 -15
  196. package/dist/project-config.js.map +1 -1
  197. package/dist/publication.d.ts.map +1 -1
  198. package/dist/publication.js +135 -19
  199. package/dist/publication.js.map +1 -1
  200. package/dist/publish.d.ts +2 -0
  201. package/dist/publish.d.ts.map +1 -1
  202. package/dist/publish.js +48 -25
  203. package/dist/publish.js.map +1 -1
  204. package/dist/remediation.d.ts +63 -0
  205. package/dist/remediation.d.ts.map +1 -0
  206. package/dist/remediation.js +110 -0
  207. package/dist/remediation.js.map +1 -0
  208. package/dist/request-metadata.d.ts +17 -7
  209. package/dist/request-metadata.d.ts.map +1 -1
  210. package/dist/request-metadata.js +43 -8
  211. package/dist/request-metadata.js.map +1 -1
  212. package/dist/runtime.d.ts.map +1 -1
  213. package/dist/runtime.js +104 -36
  214. package/dist/runtime.js.map +1 -1
  215. package/dist/saved-scan-bootstrap.d.ts +1 -0
  216. package/dist/saved-scan-bootstrap.d.ts.map +1 -1
  217. package/dist/saved-scan-bootstrap.js +16 -4
  218. package/dist/saved-scan-bootstrap.js.map +1 -1
  219. package/dist/scan-activity.js +8 -8
  220. package/dist/scan-activity.js.map +1 -1
  221. package/dist/scan-comparison.d.ts.map +1 -1
  222. package/dist/scan-comparison.js +15 -9
  223. package/dist/scan-comparison.js.map +1 -1
  224. package/dist/scan-dashboard.d.ts.map +1 -1
  225. package/dist/scan-dashboard.js +12 -6
  226. package/dist/scan-dashboard.js.map +1 -1
  227. package/dist/scan-executor.d.ts +5 -1
  228. package/dist/scan-executor.d.ts.map +1 -1
  229. package/dist/scan-executor.js +9 -8
  230. package/dist/scan-executor.js.map +1 -1
  231. package/dist/{deep-progress.d.ts → scan-progress.d.ts} +15 -7
  232. package/dist/scan-progress.d.ts.map +1 -0
  233. package/dist/scan-progress.js +138 -0
  234. package/dist/scan-progress.js.map +1 -0
  235. package/dist/scan-settings.d.ts +1 -0
  236. package/dist/scan-settings.d.ts.map +1 -1
  237. package/dist/scan-settings.js +7 -1
  238. package/dist/scan-settings.js.map +1 -1
  239. package/dist/scan-time-budget.d.ts +9 -0
  240. package/dist/scan-time-budget.d.ts.map +1 -0
  241. package/dist/scan-time-budget.js +16 -0
  242. package/dist/scan-time-budget.js.map +1 -0
  243. package/dist/security-policy.js +1 -1
  244. package/dist/security-policy.js.map +1 -1
  245. package/dist/server/embeddings.d.ts.map +1 -1
  246. package/dist/server/embeddings.js +4 -0
  247. package/dist/server/embeddings.js.map +1 -1
  248. package/dist/server/sqlite-store.d.ts.map +1 -1
  249. package/dist/server/sqlite-store.js +14 -2
  250. package/dist/server/sqlite-store.js.map +1 -1
  251. package/dist/severity-review.d.ts +29 -0
  252. package/dist/severity-review.d.ts.map +1 -0
  253. package/dist/severity-review.js +47 -0
  254. package/dist/severity-review.js.map +1 -0
  255. package/dist/severity-store.js +4 -1
  256. package/dist/severity-store.js.map +1 -1
  257. package/dist/timestamps.d.ts +3 -0
  258. package/dist/timestamps.d.ts.map +1 -0
  259. package/dist/timestamps.js +14 -0
  260. package/dist/timestamps.js.map +1 -0
  261. package/dist/validation-records.d.ts +38 -0
  262. package/dist/validation-records.d.ts.map +1 -0
  263. package/dist/validation-records.js +76 -0
  264. package/dist/validation-records.js.map +1 -0
  265. package/dist/version.d.ts +1 -1
  266. package/dist/version.d.ts.map +1 -1
  267. package/dist/version.js +17 -4
  268. package/dist/version.js.map +1 -1
  269. package/dist/workbench-arguments.d.ts.map +1 -1
  270. package/dist/workbench-arguments.js +9 -3
  271. package/dist/workbench-arguments.js.map +1 -1
  272. package/dist/worker-progress.d.ts +13 -7
  273. package/dist/worker-progress.d.ts.map +1 -1
  274. package/dist/worker-progress.js +12 -44
  275. package/dist/worker-progress.js.map +1 -1
  276. package/docs/classify-severity-records.md +89 -0
  277. package/docs/cli.md +352 -45
  278. package/docs/findings-service.md +7 -2
  279. package/docs/hosted-remediation.md +117 -0
  280. package/docs/hosted-scans.md +8 -3
  281. package/docs/validate-records.md +69 -0
  282. package/package.json +13 -10
  283. package/schemas/project-config.schema.json +7 -1
  284. package/_bundled_plugin/preflight/capability-profiles.toml +0 -76
  285. package/_bundled_plugin/references/config-preflight.md +0 -93
  286. package/_bundled_plugin/references/desktop-config-preflight.md +0 -11
  287. package/_bundled_plugin/scripts/config_preflight.py +0 -911
  288. package/dist/deep-progress.d.ts.map +0 -1
  289. package/dist/deep-progress.js +0 -92
  290. package/dist/deep-progress.js.map +0 -1
package/dist/api.js CHANGED
@@ -26,12 +26,13 @@ import { CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, accountStatus, configur
26
26
  import { jsonForPrompt, pluginPythonCommand, shellEnvironmentReference, } from "./codex-prompt.js";
27
27
  import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, inlineToml, isExternalModelProvider, hasCommandAuth, mergedCodexConfig, resolveCodexProfile, resolveCommandAuthConfig, scanApprovalPolicy, scanCyberAccessConfig, scanModelConfiguration, scanModelProvider, structuredCodexConfig, writeCodexConfig, } from "./config.js";
28
28
  import { estimateScanCost, ScanCostTracker, } from "./cost.js";
29
- import { DeepScanProgressTracker, } from "./deep-progress.js";
29
+ import { ScanProgressTracker } from "./scan-progress.js";
30
30
  import { findScanSession } from "./scan-logs.js";
31
- import { runDeepScan } from "./deep-scan.js";
31
+ import { DIRECT_DEEP_SCAN_CONTROL_USAGE, runDeepScan } from "./deep-scan.js";
32
32
  import { deepScanOptions, resolveDeepScanConfig, writeDeepScanConfig, } from "./deep-config.js";
33
33
  import { DEFAULT_SCAN_AUTH, DEFAULT_SCAN_MODE, SCAN_AUTH_MODES, ScanSettingsSchema, } from "./scan-settings.js";
34
34
  import { resolveScanPrompts } from "./prompt-files.js";
35
+ import { readScanTimeBudgetPolicy, renderScanTimeBudgetPolicy, scanTimeBudget, } from "./scan-time-budget.js";
35
36
  import { standaloneValidationPrompt } from "./standalone-validation-prompt.js";
36
37
  export { SCAN_AUTH_MODES } from "./scan-settings.js";
37
38
  import { loadContract, readScanFile, requireScanFile, } from "./contract.js";
@@ -46,9 +47,9 @@ import { formatSecurityPolicyText, inspectSecurityPolicySources, readSecurityPol
46
47
  import { writeMockScanDraft } from "./mock-scan.js";
47
48
  import { scanActivitiesFromEvent } from "./scan-activity.js";
48
49
  import { matchCompletedScan, matchScanFindingsInternal, } from "./scan-comparison.js";
49
- import { scanProgressUpdatesFromEvent, workerStatusFromEvent, } from "./worker-progress.js";
50
+ import { scanProgressUpdatesFromEvent, scanPhaseSchema, workerStatusFromEvent, } from "./worker-progress.js";
50
51
  import { CODEX_SECURITY_THREAD_SOURCES } from "./thread-source.js";
51
- import { codexSecurityRequestMetadata } from "./request-metadata.js";
52
+ import { codexSecurityRequestContext } from "./request-metadata.js";
52
53
  import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";
53
54
  import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";
54
55
  import { canonicalConfigPath, acquireCodexSecurityCredentialHomeLock, withCredentialHomeLock, bootstrapPlugin, bundledPluginRoot, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, codexExecutableReadPaths, createIsolatedHome, executablePathForSpawn, expandHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, environmentWithGit, pluginMetadata, planOutputArchive, prepareScanArtifactRestorer, prepareOutputDir, prepareScanRegistrationOutput, preparePersistentOutputRoot, probeCodexSandbox, requireModelSafeOutputDir, requireOutputOutsideRepositories, requireOutputOutsideRepository, requirePrivateCredentialHome, requirePrivatePolicyOutputDirectory, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
@@ -293,7 +294,7 @@ export class CodexSecurity {
293
294
  VALIDATION_PERMISSION_PROFILE;
294
295
  session.sessionConfig["web_search"] = "disabled";
295
296
  session.sessionConfig["approval_policy"] = "never";
296
- const { codex } = await this.#createSessionCodex(session, "validate", {
297
+ const { codex } = await this.#createSessionCodex(session, { command: "validate" }, {
297
298
  CODEX_SECURITY_REPOSITORY: inputs.repository,
298
299
  CODEX_SECURITY_PLUGIN_ROOT: runtime.plugin.pluginRoot,
299
300
  CODEX_SECURITY_SURFACE: this.#surface,
@@ -378,7 +379,7 @@ export class CodexSecurity {
378
379
  ...session.sessionConfig["features"],
379
380
  plugins: false,
380
381
  };
381
- const { codex } = await this.#createSessionCodex(session, "patch", {
382
+ const { codex } = await this.#createSessionCodex(session, { command: "patch" }, {
382
383
  CODEX_SECURITY_REPOSITORY: repository,
383
384
  CODEX_SECURITY_PLUGIN_ROOT: session.runtime.plugin.pluginRoot,
384
385
  CODEX_SECURITY_SURFACE: this.#surface,
@@ -399,7 +400,10 @@ export class CodexSecurity {
399
400
  : notifyObserver(options, "onSessionEvent"),
400
401
  onCost: options.onCost === undefined
401
402
  ? undefined
402
- : notifyObserver(options, "onCost"),
403
+ : (cost, complete) => {
404
+ if (complete)
405
+ notifyObserver(options, "onCost")(cost);
406
+ },
403
407
  onError: reportTrackingError,
404
408
  });
405
409
  const thread = codex.startThread({
@@ -509,12 +513,19 @@ export class CodexSecurity {
509
513
  : {}),
510
514
  outputDir: inputs.outputDir,
511
515
  ...(archiveDir === null ? {} : { archiveDir }),
512
- authentication: scanAuthentication(this.#dependencies.environment, options.auth, modelProvider, hasCommandAuth(configuration)),
516
+ authentication: scanAuthentication(this.#dependencies.environment, options.auth, modelProvider, hasCommandAuth(configuration), true),
513
517
  ...model,
514
518
  ...(typeof modelProvider === "string" ? { modelProvider } : {}),
515
519
  ...(options.maxCostUsd === undefined
516
520
  ? {}
517
521
  : { maxCostUsd: options.maxCostUsd }),
522
+ ...(inputs.deepScanConfiguration !== undefined
523
+ ? {
524
+ maxTimeMinutes: inputs.deepScanConfiguration.settings.maxTimeHours * 60,
525
+ }
526
+ : options.maxTimeMinutes === undefined
527
+ ? {}
528
+ : { maxTimeMinutes: options.maxTimeMinutes }),
518
529
  };
519
530
  }
520
531
  async preflightPolicy(repository, options = {}) {
@@ -605,8 +616,27 @@ export class CodexSecurity {
605
616
  runtime.plugin.pluginRoot,
606
617
  ...(knowledgeBase === null ? [] : [knowledgeBase.path]),
607
618
  ].filter((path, index, roots) => roots.indexOf(path) === index);
608
- const policyFilesystem = policyFilesystemPermissions(inputs.gitMetadataPaths, await codexExecutableReadPaths(this.#codexCommand().command));
609
- const { codex } = await this.#createSessionCodex(session, "policy", {
619
+ const ambientHome = process.platform === "win32"
620
+ ? await canonicalConfigPath(scanCodexHome(this.#dependencies.environment))
621
+ : undefined;
622
+ const ambientCredentials = ambientHome === undefined
623
+ ? []
624
+ : await Promise.all(["auth.json", "config.toml"].map((name) => realpath(join(ambientHome, name)).catch((error) => {
625
+ if (error.code === "ENOENT")
626
+ return null;
627
+ throw error;
628
+ })));
629
+ const policyFilesystem = policyFilesystemPermissions([
630
+ session.runtimeHome,
631
+ ...ambientCredentials.filter((path) => path !== null),
632
+ ...(runtime.configPath === undefined ? [] : [runtime.configPath]),
633
+ ...(runtime.deepScanConfigPath === undefined ||
634
+ runtime.deepScanConfigDirectory !== undefined
635
+ ? []
636
+ : [runtime.deepScanConfigPath]),
637
+ ...inputs.gitMetadataPaths,
638
+ ], await codexExecutableReadPaths(this.#codexCommand().command), ambientHome);
639
+ const { codex } = await this.#createSessionCodex(session, { command: "policy" }, {
610
640
  CODEX_SECURITY_REPOSITORY: target.repository,
611
641
  CODEX_SECURITY_PLUGIN_ROOT: runtime.plugin.pluginRoot,
612
642
  CODEX_SECURITY_STATE_DIR: inputs.stateDirectory,
@@ -618,9 +648,9 @@ export class CodexSecurity {
618
648
  // CLI override keys split on dots, so keep paths inside the TOML value.
619
649
  `permissions.${POLICY_PERMISSION_PROFILE}.filesystem=${inlineToml(policyFilesystem)}`,
620
650
  ]);
621
- const reportCost = (current) => {
651
+ const reportCost = (current, complete = true) => {
622
652
  const total = addScanCosts(accumulatedCost, current);
623
- if (completeCost)
653
+ if (completeCost && complete)
624
654
  notifyObserver(options, "onCost")(total);
625
655
  if (options.maxCostUsd !== undefined &&
626
656
  total.estimatedUsd > options.maxCostUsd) {
@@ -769,12 +799,13 @@ export class CodexSecurity {
769
799
  ]);
770
800
  let maxCostUsd = options.maxCostUsd;
771
801
  let latestCost = null;
802
+ let latestCostComplete = false;
772
803
  let notifiedLimit;
773
804
  let scanDir = "";
774
805
  let targetPathsFile = null;
775
806
  let knowledgeBase = null;
776
807
  let costTracker = null;
777
- let deepProgressTracker = null;
808
+ let scanProgressTracker = null;
778
809
  let artifactRestorationFailure = null;
779
810
  let customValidationComplete = false;
780
811
  let completionCost = null;
@@ -899,14 +930,18 @@ export class CodexSecurity {
899
930
  }),
900
931
  };
901
932
  const { environment: workerEnvironment, ...workerRuntimeConfig } = selectedWorkerRuntimeConfig(effectiveConfig, modelProvider, scanDir, workerProviderEnvironment);
933
+ const sqliteHome = workerRuntimeConfig["sqlite_home"];
934
+ const sqliteEnvironment = mode === "deep" && typeof sqliteHome === "string"
935
+ ? { CODEX_SQLITE_HOME: sqliteHome }
936
+ : {};
902
937
  const workerSnapshot = {
903
938
  ...workerRuntimeConfig,
904
- responses_api_metadata: {
905
- ...(isRecord(workerRuntimeConfig["responses_api_metadata"])
906
- ? workerRuntimeConfig["responses_api_metadata"]
907
- : {}),
908
- ...codexSecurityRequestMetadata(this.#surface, "scan", runtime.plugin.version),
909
- },
939
+ responses_api_metadata: codexSecurityRequestContext(effectiveConfig, {
940
+ surface: this.#surface,
941
+ command: "scan",
942
+ pluginVersion: runtime.plugin.version,
943
+ mode,
944
+ }).metadata,
910
945
  ...(workerEnvironment === undefined
911
946
  ? {}
912
947
  : { environment: workerEnvironment }),
@@ -972,6 +1007,8 @@ export class CodexSecurity {
972
1007
  }
973
1008
  let scopeFileCount = null;
974
1009
  let reviewedFileCount = 0;
1010
+ let latestPhase = "preflight";
1011
+ let reviewItems;
975
1012
  const reportProgress = (progress) => {
976
1013
  if (scopeFileCount === null ||
977
1014
  progress.filesTotal > scopeFileCount ||
@@ -979,7 +1016,29 @@ export class CodexSecurity {
979
1016
  return;
980
1017
  }
981
1018
  reviewedFileCount = progress.filesCompleted;
982
- notifyObserver(options, "onProgress")({ ...progress, filesTotal: scopeFileCount });
1019
+ if (mode === "deep" ||
1020
+ scanPhaseSchema.options.indexOf(progress.phase) >
1021
+ scanPhaseSchema.options.indexOf(latestPhase)) {
1022
+ latestPhase = progress.phase;
1023
+ }
1024
+ notifyObserver(options, "onProgress")({
1025
+ ...progress,
1026
+ phase: latestPhase,
1027
+ filesTotal: scopeFileCount,
1028
+ ...(reviewItems === undefined ? {} : { reviewItems }),
1029
+ });
1030
+ };
1031
+ const reportWorkerStatus = (status) => {
1032
+ if (mode !== "deep") {
1033
+ const phase = status.phase === "ranking" || status.phase === "file_review"
1034
+ ? "discovery"
1035
+ : status.phase;
1036
+ if (scanPhaseSchema.options.indexOf(phase) <
1037
+ scanPhaseSchema.options.indexOf(latestPhase))
1038
+ return;
1039
+ latestPhase = phase;
1040
+ }
1041
+ notifyObserver(options, "onWorkerStatus")(status);
983
1042
  };
984
1043
  const reportedInaccessibleSessionLogs = new Set();
985
1044
  const reportTrackingError = (error) => {
@@ -1016,12 +1075,20 @@ export class CodexSecurity {
1016
1075
  onSessionEvent: options.onSessionEvent === undefined
1017
1076
  ? undefined
1018
1077
  : (event) => notifyObserver(options, "onSessionEvent")(event),
1019
- onProgress: options.onProgress === undefined ? undefined : reportProgress,
1078
+ onProgress: options.onProgress === undefined
1079
+ ? undefined
1080
+ : (progress) => reportProgress({
1081
+ ...progress,
1082
+ // Worker counts belong to the parent scan's current phase.
1083
+ phase: mode === "deep" ? progress.phase : latestPhase,
1084
+ }),
1020
1085
  onCost: options.onCost === undefined && options.maxCostUsd === undefined
1021
1086
  ? undefined
1022
- : (cost) => {
1087
+ : (cost, complete) => {
1023
1088
  latestCost = cost;
1024
- notifyObserver(options, "onCost")(cost, maxCostUsd);
1089
+ latestCostComplete = complete;
1090
+ if (complete)
1091
+ notifyObserver(options, "onCost")(cost, maxCostUsd);
1025
1092
  if (maxCostUsd !== undefined &&
1026
1093
  cost.estimatedUsd > maxCostUsd) {
1027
1094
  costAbortController.abort(new ScanCostLimitExceededError(maxCostUsd, cost, scanDir));
@@ -1060,7 +1127,8 @@ export class CodexSecurity {
1060
1127
  if (budgetSignal.aborted)
1061
1128
  return;
1062
1129
  maxCostUsd = next;
1063
- notifyObserver(options, "onCost")(latestCost, maxCostUsd);
1130
+ if (latestCostComplete)
1131
+ notifyObserver(options, "onCost")(latestCost, maxCostUsd);
1064
1132
  })
1065
1133
  .catch((error) => {
1066
1134
  if (!budgetSignal.aborted) {
@@ -1083,6 +1151,7 @@ export class CodexSecurity {
1083
1151
  knowledgeBasePaths: knowledgeBase?.sources,
1084
1152
  maxCostUsd: options.maxCostUsd,
1085
1153
  deepScan: deepScanConfiguration?.settings,
1154
+ maxTimeMinutes: options.maxTimeMinutes,
1086
1155
  auth: options.auth,
1087
1156
  cyberAccessProgram: options.cyberAccessProgram,
1088
1157
  });
@@ -1100,6 +1169,7 @@ export class CodexSecurity {
1100
1169
  pluginRoot: runtime.plugin.pluginRoot,
1101
1170
  environment: {
1102
1171
  ...environmentWithGit(git.environment, git),
1172
+ ...sqliteEnvironment,
1103
1173
  CODEX_SECURITY_STATE_DIR: stateDirectory,
1104
1174
  },
1105
1175
  signal,
@@ -1224,28 +1294,48 @@ export class CodexSecurity {
1224
1294
  notifyObserver(options, "onOutputDirReady")(scanDir);
1225
1295
  }
1226
1296
  throwIfAborted(signal, scanDir);
1227
- if (mode === "deep" && options.onDeepProgress !== undefined) {
1297
+ if (this.#dependencies.hostedScan === undefined &&
1298
+ ((mode !== "deep" && options.onProgress !== undefined) ||
1299
+ (mode === "deep" && options.onDeepProgress !== undefined))) {
1228
1300
  let progressWarningReported = false;
1229
- deepProgressTracker = new DeepScanProgressTracker({
1301
+ scanProgressTracker = new ScanProgressTracker({
1230
1302
  read: (progressSignal) => workbench({
1231
1303
  ...workbenchOptions,
1232
1304
  signal: AbortSignal.any([signal, progressSignal]),
1233
1305
  }, workbenchArgs("get-scan", { scanId })),
1234
- onProgress: (progress) => notifyObserver(options, "onDeepProgress")(progress),
1306
+ onProgress: mode === "deep"
1307
+ ? undefined
1308
+ : (progress) => {
1309
+ reviewItems = progress.reviewItems;
1310
+ if (scopeFileCount === null && progress.filesTotal !== null) {
1311
+ scopeFileCount = progress.filesTotal;
1312
+ tracker.setExpectedFilesTotal(scopeFileCount);
1313
+ }
1314
+ if (scopeFileCount === null)
1315
+ return;
1316
+ reportProgress({
1317
+ phase: progress.phase,
1318
+ filesCompleted: reviewedFileCount,
1319
+ filesTotal: scopeFileCount,
1320
+ });
1321
+ },
1322
+ onDeepProgress: mode === "deep"
1323
+ ? (progress) => notifyObserver(options, "onDeepProgress")(progress)
1324
+ : undefined,
1235
1325
  onError: (error) => {
1236
1326
  if (progressWarningReported)
1237
1327
  return;
1238
1328
  progressWarningReported = true;
1239
- notifyObserver(options, "onWarning")(`Could not track Deep Scan progress: ${errorMessage(error)}`);
1329
+ notifyObserver(options, "onWarning")(`Could not track ${mode === "deep" ? "Deep Scan" : "scan"} progress: ${errorMessage(error)}`);
1240
1330
  },
1241
1331
  });
1242
- deepProgressTracker.start();
1332
+ scanProgressTracker.start();
1243
1333
  }
1244
1334
  if (options.validationPrompt !== undefined) {
1245
1335
  await writeCustomValidationStatus(scanDir, { scanId, status: "pending" }, signal);
1246
1336
  }
1247
1337
  checkOpen();
1248
- const basePrompt = scanPrompt(normalized, mode, skillName, scanId, runtime.configPath !== undefined, knowledgeBase !== null, options.resumeScanId !== undefined &&
1338
+ const basePrompt = scanPrompt(normalized, mode, skillName, scanId, knowledgeBase !== null, options.resumeScanId !== undefined &&
1249
1339
  typeof registration["userContext"] === "string"
1250
1340
  ? registration["userContext"]
1251
1341
  : options.scanPrompt, options.maxCostUsd !== undefined, discoveryPrompt, modelProvider);
@@ -1289,6 +1379,7 @@ export class CodexSecurity {
1289
1379
  ? join(dirname(runtime.codexHome), `codex-security-target-paths-${randomUUID()}.json`)
1290
1380
  : null;
1291
1381
  const runtimePaths = {
1382
+ ...sqliteEnvironment,
1292
1383
  PYTHON: python,
1293
1384
  CODEX_SECURITY_STARTED_AT: options.resumeScanId !== undefined &&
1294
1385
  typeof registration["startedAt"] === "string"
@@ -1324,7 +1415,7 @@ export class CodexSecurity {
1324
1415
  ? {}
1325
1416
  : { CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile }),
1326
1417
  };
1327
- const { codex, environment, codexOptions } = await this.#createSessionCodex(session, "scan", runtimePaths, options.auth, git);
1418
+ const { codex, environment, codexOptions } = await this.#createSessionCodex(session, { command: "scan", mode }, runtimePaths, options.auth, git);
1328
1419
  const threadOptions = {
1329
1420
  threadSource: CODEX_SECURITY_THREAD_SOURCES.scan,
1330
1421
  workingDirectory: scanDir,
@@ -1365,6 +1456,11 @@ export class CodexSecurity {
1365
1456
  if (postScanPrompt?.trim()) {
1366
1457
  runPostScan = () => thread.runStreamed(postScanPrompt, turnOptions);
1367
1458
  }
1459
+ if (mode === "standard" && options.maxTimeMinutes !== undefined) {
1460
+ const timePolicy = await readScanTimeBudgetPolicy(runtime.plugin.pluginRoot);
1461
+ checkOpen();
1462
+ prompt += `\n\n${renderScanTimeBudgetPolicy(timePolicy, scanTimeBudget(options.maxTimeMinutes, (this.#dependencies.now ?? Date.now)()))}`;
1463
+ }
1368
1464
  const events = directDeepScan
1369
1465
  ? (this.#dependencies.runDeepScan ?? runDeepScan)({
1370
1466
  codexOptions,
@@ -1414,6 +1510,8 @@ export class CodexSecurity {
1414
1510
  }
1415
1511
  if (budgetRecovery !== null)
1416
1512
  budgetRecovery.threadId = threadId;
1513
+ if (directDeepScan)
1514
+ tracker.recordUsage(DIRECT_DEEP_SCAN_CONTROL_USAGE, threadId);
1417
1515
  tracker.start(threadId);
1418
1516
  try {
1419
1517
  await workbench(workbenchOptions, workbenchArgs("set-scan-thread", { scanId, threadId }));
@@ -1437,6 +1535,9 @@ export class CodexSecurity {
1437
1535
  falsePositives: falsePositiveExamples,
1438
1536
  signal,
1439
1537
  run: async (validationPrompt, outputSchema) => {
1538
+ // This turn follows the primary scan's reporting phase.
1539
+ scanProgressTracker?.stop();
1540
+ latestPhase = "validation";
1440
1541
  if (scopeFileCount !== null)
1441
1542
  reportProgress({
1442
1543
  phase: "validation",
@@ -1522,7 +1623,7 @@ export class CodexSecurity {
1522
1623
  }
1523
1624
  reportProgress(progress);
1524
1625
  },
1525
- onWorkerStatus: options.onWorkerStatus,
1626
+ onWorkerStatus: reportWorkerStatus,
1526
1627
  onWarning: options.onWarning,
1527
1628
  onObserverError: options.onObserverError,
1528
1629
  });
@@ -1562,6 +1663,7 @@ export class CodexSecurity {
1562
1663
  }
1563
1664
  }
1564
1665
  }
1666
+ scanProgressTracker?.stop();
1565
1667
  if (runPostScan !== null) {
1566
1668
  const followUp = runPostScan;
1567
1669
  runPostScan = null;
@@ -1634,7 +1736,10 @@ export class CodexSecurity {
1634
1736
  const runWorkbench = (args, input) => workbench(workbenchOptions, args, input);
1635
1737
  const previousFindings = await listRepositoryFindings(runWorkbench, targetId, "all");
1636
1738
  if (previousFindings !== undefined) {
1637
- const matchingRuntimeConfig = structuredClone(workerRuntimeConfig);
1739
+ const matchingRuntimeConfig = {
1740
+ ...structuredClone(workerRuntimeConfig),
1741
+ responses_api_metadata: workerSnapshot["responses_api_metadata"],
1742
+ };
1638
1743
  const matchingFeatures = matchingRuntimeConfig["features"];
1639
1744
  if (isRecord(matchingFeatures))
1640
1745
  delete matchingFeatures["plugins"];
@@ -1772,6 +1877,7 @@ export class CodexSecurity {
1772
1877
  catch { }
1773
1878
  }
1774
1879
  if (runPostScan !== null && !signal.aborted) {
1880
+ scanProgressTracker?.stop();
1775
1881
  try {
1776
1882
  for await (const event of (await runPostScan()).events) {
1777
1883
  if (event.type === "turn.failed") {
@@ -1794,7 +1900,7 @@ export class CodexSecurity {
1794
1900
  }
1795
1901
  finally {
1796
1902
  budgetAbortController.abort();
1797
- deepProgressTracker?.stop();
1903
+ scanProgressTracker?.stop();
1798
1904
  // Temporary-input cleanup must not replace the scan's outcome.
1799
1905
  try {
1800
1906
  for (const cleanup of await Promise.allSettled([
@@ -1873,7 +1979,10 @@ export class CodexSecurity {
1873
1979
  if (this.#closePromise !== null)
1874
1980
  return await this.#closePromise;
1875
1981
  this.#closed = true;
1876
- this.#closePromise = this.#finishClose();
1982
+ const completion = Promise.withResolvers();
1983
+ // Abort listeners can reenter close before finishClose reaches its first await.
1984
+ this.#closePromise = completion.promise;
1985
+ void this.#finishClose().then(completion.resolve, completion.reject);
1877
1986
  await this.#closePromise;
1878
1987
  }
1879
1988
  async #finishClose() {
@@ -1940,18 +2049,19 @@ export class CodexSecurity {
1940
2049
  if (this.#activeOperation !== null) {
1941
2050
  throw new CodexSecurityError("A Codex Security operation is already in progress.");
1942
2051
  }
1943
- const activeOperation = operation();
1944
- this.#activeOperation = activeOperation;
2052
+ const activeOperation = Promise.withResolvers();
2053
+ this.#activeOperation = activeOperation.promise;
1945
2054
  try {
1946
- return await activeOperation;
2055
+ return await operation();
1947
2056
  }
1948
2057
  finally {
1949
- if (this.#activeOperation === activeOperation) {
2058
+ if (this.#activeOperation === activeOperation.promise) {
1950
2059
  this.#activeOperation = null;
1951
2060
  }
2061
+ activeOperation.resolve();
1952
2062
  }
1953
2063
  }
1954
- async #createSessionCodex(session, command, runtimePaths, auth = "auto", git, config, configOverrides = []) {
2064
+ async #createSessionCodex(session, { command, mode }, runtimePaths, auth = "auto", git, config, configOverrides = []) {
1955
2065
  const hosted = this.#dependencies.hostedScan;
1956
2066
  if (hosted !== undefined) {
1957
2067
  const environment = {
@@ -2066,9 +2176,13 @@ export class CodexSecurity {
2066
2176
  ...configOverrides,
2067
2177
  ];
2068
2178
  }
2069
- const configuredResponsesMetadata = isRecord(sdkCodexConfig["responses_api_metadata"])
2070
- ? sdkCodexConfig["responses_api_metadata"]
2071
- : {};
2179
+ const requestContext = codexSecurityRequestContext(config ?? sessionConfig, {
2180
+ surface: this.#surface,
2181
+ command,
2182
+ pluginVersion: runtime.plugin.version,
2183
+ mode,
2184
+ });
2185
+ delete sdkCodexConfig["responses_api_metadata"];
2072
2186
  const configuredCodexPath = environmentValue(this.#dependencies.environment, "CODEX_CLI_PATH");
2073
2187
  let codexPathOverride = configuredCodexPath === undefined
2074
2188
  ? undefined
@@ -2088,19 +2202,9 @@ export class CodexSecurity {
2088
2202
  ...(runtime.providerProfile === undefined
2089
2203
  ? {}
2090
2204
  : { nativeProfile: runtime.providerProfile.name }),
2091
- ...(configOverrides.length > 0
2092
- ? {
2093
- configOverrides,
2094
- }
2095
- : {}),
2205
+ configOverrides: [...configOverrides, requestContext.configOverride],
2096
2206
  env: sdkEnvironment,
2097
- config: {
2098
- ...sdkCodexConfig,
2099
- responses_api_metadata: {
2100
- ...configuredResponsesMetadata,
2101
- ...codexSecurityRequestMetadata(this.#surface, command, runtime.plugin.version),
2102
- },
2103
- },
2207
+ config: sdkCodexConfig,
2104
2208
  };
2105
2209
  const codex = await this.#dependencies.createCodex(codexOptions);
2106
2210
  return { codex, environment, codexOptions };
@@ -2424,6 +2528,7 @@ export class CodexSecurity {
2424
2528
  failOnSeverity: options.failureSeverity,
2425
2529
  knowledgeBasePaths: options.knowledgeBasePaths,
2426
2530
  maxCostUsd: options.maxCostUsd,
2531
+ maxTimeMinutes: options.maxTimeMinutes,
2427
2532
  auth: options.auth,
2428
2533
  cyberAccessProgram: options.cyberAccessProgram,
2429
2534
  }),
@@ -2606,7 +2711,10 @@ export class CodexSecurity {
2606
2711
  let deepScanConfigDirectory;
2607
2712
  try {
2608
2713
  throwIfAborted(signal);
2609
- bootstrapWorkspace = await createIsolatedHome(temporaryRoot, validateLocation);
2714
+ bootstrapWorkspace = await createIsolatedHome(
2715
+ // Windows sandboxes can grant replacement rights on TEMP. Keep private
2716
+ // staging beside the validated home, outside it so ZIP plugins are readable.
2717
+ process.platform === "win32" ? dirname(codexHome) : temporaryRoot, validateLocation);
2610
2718
  await requirePrivateCredentialHome(await lstat(bootstrapWorkspace), bootstrapWorkspace);
2611
2719
  const pluginRoot = await resolvePluginPath(this.config.pluginPath, bootstrapWorkspace, signal);
2612
2720
  const ambientHome = scanCodexHome(processEnvironment);
@@ -2801,7 +2909,9 @@ export async function runScanEvents(options) {
2801
2909
  }
2802
2910
  // Managed scans reconcile saved checkpoints before admitting canonical artifacts.
2803
2911
  if (options.workbenchValidated && options.onFinalize !== undefined) {
2804
- usage = (await options.onFinalize(usage)) ?? usage;
2912
+ const finalizedUsage = await options.onFinalize(usage);
2913
+ if (finalizedUsage !== undefined)
2914
+ usage = finalizedUsage;
2805
2915
  }
2806
2916
  options.signal.throwIfAborted();
2807
2917
  await requireScanArtifacts(options.scanDir, ["scan-manifest.json", "findings.json", "coverage.json"], options.signal);
@@ -2818,7 +2928,9 @@ export async function runScanEvents(options) {
2818
2928
  throw new IncompleteScanError("Codex Security produced only an unfinished audit checkpoint.");
2819
2929
  }
2820
2930
  if (!options.workbenchValidated && options.onFinalize !== undefined) {
2821
- usage = (await options.onFinalize(usage)) ?? usage;
2931
+ const finalizedUsage = await options.onFinalize(usage);
2932
+ if (finalizedUsage !== undefined)
2933
+ usage = finalizedUsage;
2822
2934
  }
2823
2935
  const result = await collectResult({
2824
2936
  status,
@@ -2925,7 +3037,7 @@ function trustedAccessWarning(status, authentication) {
2925
3037
  : "your Trusted Access for Cyber status";
2926
3038
  return `Some cybersecurity requests or findings may be refused because ${access} could not be verified. Check ${apiOrganization ? "your organization's access" : "your access"} or apply at ${applicationUrl}.`;
2927
3039
  }
2928
- function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasKnowledgeBase = false, additionalPrompt, enforceCostLimit = false, discoveryPrompt, modelProvider) {
3040
+ function scanPrompt(target, mode, skillName, scanId, hasKnowledgeBase = false, additionalPrompt, enforceCostLimit = false, discoveryPrompt, modelProvider) {
2929
3041
  const python = pluginPythonCommand();
2930
3042
  const customValidation = discoveryPrompt !== undefined;
2931
3043
  return [
@@ -2978,11 +3090,6 @@ function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasK
2978
3090
  'After the file inventory, after each fully reviewed file batch, and when entering each later phase, emit one standalone CODEX_SECURITY_SCAN_PROGRESS {"phase":"discovery","filesCompleted":3,"filesTotal":8} line in a completed command output or agent message. Use the actual phase and file counts. Never count unread or partially reviewed files.',
2979
3091
  'Every delegated review assignment must say: After each completed batch, emit CODEX_SECURITY_SCAN_PROGRESS {"phase":"discovery","filesCompleted":3,"filesTotal":8} on its own line using your worker-local reviewed and assigned file counts.',
2980
3092
  ]),
2981
- ...(hasConfigPath
2982
- ? [
2983
- `For normal config-preflight helper calls, append --config ${shellEnvironmentReference("CODEX_SECURITY_CONFIG_PATH")} so preflight reads the sanitized active runtime config. Preserve the documented runtime and --effective-config arguments for session-only values.`,
2984
- ]
2985
- : []),
2986
3093
  ...(hasKnowledgeBase
2987
3094
  ? [
2988
3095
  `The ${shellEnvironmentReference("CODEX_SECURITY_KNOWLEDGE_BASE")} environment variable contains primary documents about the project and its organization, including their architecture, threat model, and policies. These documents are a source of truth and override conflicting SECURITY.md guidance, generated threat models, and other sources, except explicit user instructions.`,
@@ -3034,7 +3141,7 @@ function targetInstruction(target, python) {
3034
3141
  }
3035
3142
  return `Scan target: staged and unstaged working-tree changes against ${target.base}.`;
3036
3143
  }
3037
- function scanRecipe({ repository, target, mode, repositoryRevision, pluginVersion, config, failOnSeverity, knowledgeBasePaths, maxCostUsd, deepScan, auth, cyberAccessProgram, }) {
3144
+ function scanRecipe({ repository, target, mode, repositoryRevision, pluginVersion, config, failOnSeverity, knowledgeBasePaths, maxCostUsd, maxTimeMinutes, deepScan, auth, cyberAccessProgram, }) {
3038
3145
  return {
3039
3146
  repository,
3040
3147
  target: { ...target, paths: [...target.paths] },
@@ -3047,6 +3154,7 @@ function scanRecipe({ repository, target, mode, repositoryRevision, pluginVersio
3047
3154
  ...(failOnSeverity === undefined ? {} : { failOnSeverity }),
3048
3155
  ...(knowledgeBasePaths === undefined ? {} : { knowledgeBasePaths }),
3049
3156
  ...(maxCostUsd === undefined ? {} : { maxCostUsd }),
3157
+ ...(maxTimeMinutes === undefined ? {} : { maxTimeMinutes }),
3050
3158
  ...(deepScan === undefined
3051
3159
  ? {}
3052
3160
  : { deepScan: { ...deepScan }, deepScanResolved: true }),
@@ -3144,7 +3252,7 @@ async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectat
3144
3252
  }),
3145
3253
  });
3146
3254
  }
3147
- export function scanAuthentication(environment, auth = DEFAULT_SCAN_AUTH, modelProvider, commandAuth = false) {
3255
+ export function scanAuthentication(environment, auth = DEFAULT_SCAN_AUTH, modelProvider, commandAuth = false, preflight = false) {
3148
3256
  if (!SCAN_AUTH_MODES.includes(auth)) {
3149
3257
  throw new TypeError("Scan authentication mode must be auto, chatgpt, or api-key.");
3150
3258
  }
@@ -3172,6 +3280,9 @@ export function scanAuthentication(environment, auth = DEFAULT_SCAN_AUTH, modelP
3172
3280
  const key = environmentApiKeyEntry(environment, modelProvider);
3173
3281
  if (key === null && isExternalModelProvider(modelProvider)) {
3174
3282
  const provider = EXTERNAL_CODEX_PROVIDERS[modelProvider];
3283
+ if (preflight && auth === "auto") {
3284
+ return { method: "api_key", source: provider.env_key, verified: false };
3285
+ }
3175
3286
  throw new AuthenticationRequiredError(`Set ${provider.env_key} to run a scan through ${provider.name}.`);
3176
3287
  }
3177
3288
  if (auth === "api-key" &&
@@ -3230,7 +3341,9 @@ export function selectedScanEnvironment(environment, auth = "auto", modelProvide
3230
3341
  }
3231
3342
  return Object.fromEntries(Object.entries(withoutOpenAiApiKeys(environment)).filter(([name]) => {
3232
3343
  const key = name.toUpperCase();
3233
- if (key === "OPENROUTER_API_KEY" || key === "FIREWORKS_API_KEY") {
3344
+ if (key === "OPENROUTER_API_KEY" ||
3345
+ key === "FIREWORKS_API_KEY" ||
3346
+ key === "CHEAPER_INFERENCE_API_KEY") {
3234
3347
  return (!bedrockProvider &&
3235
3348
  (selectedProviderKey === null || key === selectedProviderKey));
3236
3349
  }
@@ -3364,21 +3477,30 @@ export function scanRuntimeCodexConfig(config, protectedCredentialHome) {
3364
3477
  },
3365
3478
  },
3366
3479
  [POLICY_PERMISSION_PROFILE]: {
3367
- filesystem: policyFilesystemPermissions(),
3480
+ filesystem: policyFilesystemPermissions(protectedCredentialHome === undefined
3481
+ ? []
3482
+ : [protectedCredentialHome]),
3368
3483
  network: { enabled: false },
3369
3484
  },
3370
3485
  },
3371
3486
  };
3372
3487
  }
3373
- function policyFilesystemPermissions(gitMetadataPaths = [], codexPaths = []) {
3374
- return {
3375
- ":minimal": "read",
3488
+ function policyFilesystemPermissions(deniedPaths = [], codexPaths = [], ambientHome) {
3489
+ const filesystem = {
3490
+ // Windows' elevated sandbox requires root read access.
3491
+ [process.platform === "win32" ? ":root" : ":minimal"]: "read",
3376
3492
  ":workspace_roots": "read",
3377
3493
  // Linux's sandbox re-executes Codex, including installations outside /usr.
3378
3494
  ...Object.fromEntries(codexPaths.map((path) => [path, { ".": "read" }])),
3379
3495
  // A scoped "." keeps native permission paths literal, including glob characters.
3380
- ...Object.fromEntries(gitMetadataPaths.map((path) => [path, { ".": "deny" }])),
3496
+ ...Object.fromEntries(deniedPaths.map((path) => [path, { ".": "deny" }])),
3381
3497
  };
3498
+ if (process.platform === "win32" && ambientHome !== undefined) {
3499
+ // A glob avoids materializing absent credentials as directories on Windows.
3500
+ // Absolute patterns also support literal metacharacters in the home path.
3501
+ filesystem[join(ambientHome.replace(/[*?[\]{}]/gu, "[$&]"), "{auth.json,config.toml,*.config.toml,.*.config.toml.tmp}")] = "deny";
3502
+ }
3503
+ return filesystem;
3382
3504
  }
3383
3505
  function rethrowPolicyOutputError(error) {
3384
3506
  if (error instanceof OutputDirectoryNotEmptyError)
@@ -3448,6 +3570,7 @@ export function scanPreflightCodexConfig(config) {
3448
3570
  "goals",
3449
3571
  "multi_agent",
3450
3572
  "enable_fanout",
3573
+ "cli_daybreak",
3451
3574
  "api_key_cyber_access_programs",
3452
3575
  "api_key_model_discovery",
3453
3576
  ]) {
@@ -3475,6 +3598,9 @@ export function scanPreflightCodexConfig(config) {
3475
3598
  };
3476
3599
  const executionConfig = (source) => {
3477
3600
  const result = {};
3601
+ if (typeof source["daybreak"] === "boolean") {
3602
+ result["daybreak"] = source["daybreak"];
3603
+ }
3478
3604
  for (const key of [
3479
3605
  "model",
3480
3606
  "model_reasoning_effort",
@@ -3526,8 +3652,12 @@ export function scanPreflightCodexConfig(config) {
3526
3652
  if (safeString(value))
3527
3653
  result[key] = value;
3528
3654
  }
3655
+ if (typeof resolved["daybreak"] === "boolean") {
3656
+ result["daybreak"] = resolved["daybreak"];
3657
+ }
3529
3658
  const resolvedFeatures = capabilityFeatures(resolved["features"]);
3530
3659
  for (const key of [
3660
+ "cli_daybreak",
3531
3661
  "api_key_cyber_access_programs",
3532
3662
  "api_key_model_discovery",
3533
3663
  ]) {
@@ -3565,7 +3695,7 @@ export function scanPreflightCodexConfig(config) {
3565
3695
  };
3566
3696
  }
3567
3697
  else if (modelProvider === "amazon-bedrock") {
3568
- const providers = config["model_providers"];
3698
+ const providers = resolved["model_providers"];
3569
3699
  const provider = isRecord(providers) ? providers[modelProvider] : undefined;
3570
3700
  const aws = isRecord(provider) ? provider["aws"] : undefined;
3571
3701
  if (isRecord(aws)) {
@@ -3640,28 +3770,20 @@ function selectedWorkerRuntimeConfig(config, selectedProvider, workingDirectory,
3640
3770
  const value = key === undefined ? undefined : environment[key];
3641
3771
  return value === undefined ? [] : [[name, value]];
3642
3772
  }));
3643
- const instructionsFile = resolved["model_instructions_file"];
3644
- if (typeof instructionsFile === "string") {
3645
- resolved["model_instructions_file"] = resolve(workingDirectory, expandHome(instructionsFile, environment));
3773
+ // Workers use separate directories; preserve the parent scan's native paths.
3774
+ for (const key of [
3775
+ "model_instructions_file",
3776
+ "experimental_compact_prompt_file",
3777
+ "model_catalog_json",
3778
+ "sqlite_home",
3779
+ ]) {
3780
+ const file = resolved[key];
3781
+ if (typeof file === "string") {
3782
+ resolved[key] = resolve(workingDirectory, expandHome(file, environment));
3783
+ }
3646
3784
  }
3647
3785
  return {
3648
- ...Object.fromEntries([
3649
- ...CODEX_AUTH_CONFIG_KEYS,
3650
- "analytics",
3651
- "responses_api_metadata",
3652
- "openai_base_url",
3653
- "features",
3654
- "model_auto_compact_token_limit",
3655
- "model_context_window",
3656
- "model_instructions_file",
3657
- "model_verbosity",
3658
- "shell_environment_policy",
3659
- "skills",
3660
- "web_search",
3661
- "windows",
3662
- ]
3663
- .filter((key) => resolved[key] !== undefined)
3664
- .map((key) => [key, resolved[key]])),
3786
+ ...structuredCodexConfig(resolved),
3665
3787
  ...(provider === undefined ? {} : { model_provider: provider }),
3666
3788
  ...(Object.keys(providerEnvironment).length === 0
3667
3789
  ? {}