@openai/codex-security 0.3.0 → 0.5.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 (244) hide show
  1. package/README.md +45 -9
  2. package/_bundled_plugin/.codex-plugin/plugin.json +5 -5
  3. package/_bundled_plugin/.mcp.json +1 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  5. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  6. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  7. package/_bundled_plugin/mcp/permission-profile-preflight.mjs +13 -20
  8. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  9. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  10. package/_bundled_plugin/references/core-scan.md +2 -0
  11. package/_bundled_plugin/references/final-report.md +5 -1
  12. package/_bundled_plugin/references/investigation-time-budget.md +11 -0
  13. package/_bundled_plugin/references/sarif-adapter.md +1 -0
  14. package/_bundled_plugin/references/scan-prologue.md +2 -6
  15. package/_bundled_plugin/references/scan-runtime.md +15 -0
  16. package/_bundled_plugin/references/threat-model.md +2 -0
  17. package/_bundled_plugin/schemas/coverage.schema.json +45 -126
  18. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +5 -1
  19. package/_bundled_plugin/schemas/findings.schema.json +140 -427
  20. package/_bundled_plugin/schemas/patch-risk-assessment.schema.json +106 -119
  21. package/_bundled_plugin/schemas/scan-manifest.schema.json +73 -188
  22. package/_bundled_plugin/scripts/deep_scan_workbench.py +7 -0
  23. package/_bundled_plugin/scripts/finalize_scan_contract.py +87 -49
  24. package/_bundled_plugin/scripts/finding_preview.py +5 -3
  25. package/_bundled_plugin/scripts/generate_rank_input.py +26 -106
  26. package/_bundled_plugin/scripts/launch_codex_security_mcp +39 -4
  27. package/_bundled_plugin/scripts/report_projection.py +35 -13
  28. package/_bundled_plugin/scripts/snapshot_sqlite.py +7 -0
  29. package/_bundled_plugin/scripts/windows_scan_local_files.py +43 -1
  30. package/_bundled_plugin/scripts/workbench_cli.py +9 -9
  31. package/_bundled_plugin/scripts/workbench_constants.py +4 -0
  32. package/_bundled_plugin/scripts/workbench_db.py +103 -45
  33. package/_bundled_plugin/scripts/workbench_progress.py +0 -50
  34. package/_bundled_plugin/scripts/workbench_publication.py +216 -247
  35. package/_bundled_plugin/scripts/workbench_scan_history.py +3 -2
  36. package/_bundled_plugin/scripts/workbench_scan_start.py +12 -4
  37. package/_bundled_plugin/scripts/workbench_scan_usage.py +360 -37
  38. package/_bundled_plugin/scripts/workbench_schema.py +1 -1
  39. package/_bundled_plugin/scripts/workbench_source_excerpt.py +74 -51
  40. package/_bundled_plugin/scripts/workbench_source_scopes.py +388 -0
  41. package/_bundled_plugin/scripts/workbench_target.py +7 -5
  42. package/_bundled_plugin/scripts/workbench_validation.py +52 -2
  43. package/_bundled_plugin/shared/workbench-history-repairs.json +19 -0
  44. package/_bundled_plugin/shared/workbench-migrations.json +22 -0
  45. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +1 -1
  46. package/_bundled_plugin/skills/deep-security-scan/agents/openai.yaml +1 -1
  47. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +4 -2
  48. package/_bundled_plugin/skills/security-diff-scan/agents/openai.yaml +1 -1
  49. package/_bundled_plugin/skills/security-scan/SKILL.md +4 -2
  50. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +1 -1
  51. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +3 -3
  52. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +2 -0
  53. package/_bundled_plugin/skills/track-findings/SKILL.md +8 -4
  54. package/_bundled_plugin/skills/track-findings/agents/openai.yaml +1 -1
  55. package/_bundled_plugin/skills/track-findings/references/github-security-advisories.md +1 -1
  56. package/dist/api.d.ts +6 -2
  57. package/dist/api.d.ts.map +1 -1
  58. package/dist/api.js +266 -39
  59. package/dist/api.js.map +1 -1
  60. package/dist/artifact-export.d.ts +2 -1
  61. package/dist/artifact-export.d.ts.map +1 -1
  62. package/dist/artifact-export.js +38 -23
  63. package/dist/artifact-export.js.map +1 -1
  64. package/dist/classify-severity-records.d.ts +76 -0
  65. package/dist/classify-severity-records.d.ts.map +1 -0
  66. package/dist/classify-severity-records.js +141 -0
  67. package/dist/classify-severity-records.js.map +1 -0
  68. package/dist/classify-severity.d.ts +1 -23
  69. package/dist/classify-severity.d.ts.map +1 -1
  70. package/dist/classify-severity.js +3 -24
  71. package/dist/classify-severity.js.map +1 -1
  72. package/dist/cli-help.d.ts.map +1 -1
  73. package/dist/cli-help.js +2 -0
  74. package/dist/cli-help.js.map +1 -1
  75. package/dist/cli.d.ts +4 -2
  76. package/dist/cli.d.ts.map +1 -1
  77. package/dist/cli.js +148 -149
  78. package/dist/cli.js.map +1 -1
  79. package/dist/cloud-publish.js +1 -1
  80. package/dist/cloud-publish.js.map +1 -1
  81. package/dist/codex-sdk-environment.js +1 -1
  82. package/dist/codex-sdk-environment.js.map +1 -1
  83. package/dist/component-plan.js +1 -1
  84. package/dist/component-plan.js.map +1 -1
  85. package/dist/component-scan.d.ts.map +1 -1
  86. package/dist/component-scan.js +5 -4
  87. package/dist/component-scan.js.map +1 -1
  88. package/dist/config.d.ts +12 -0
  89. package/dist/config.d.ts.map +1 -1
  90. package/dist/config.js +10 -4
  91. package/dist/config.js.map +1 -1
  92. package/dist/contract.d.ts +6 -0
  93. package/dist/contract.d.ts.map +1 -1
  94. package/dist/contract.js +69 -20
  95. package/dist/contract.js.map +1 -1
  96. package/dist/cost-model.d.ts.map +1 -1
  97. package/dist/cost-model.js +7 -2
  98. package/dist/cost-model.js.map +1 -1
  99. package/dist/custom-validation-prompt.js +3 -3
  100. package/dist/custom-validation-prompt.js.map +1 -1
  101. package/dist/deduplication/codex-review.d.ts +1 -5
  102. package/dist/deduplication/codex-review.d.ts.map +1 -1
  103. package/dist/deduplication/codex-review.js +2 -2
  104. package/dist/deduplication/codex-review.js.map +1 -1
  105. package/dist/deduplication/deduplication-prompts.d.ts +1 -1
  106. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  107. package/dist/deduplication/deduplication-prompts.js +2 -2
  108. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  109. package/dist/deduplication/deduplication-reviewer.d.ts +1 -1
  110. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  111. package/dist/deduplication/deduplication-reviewer.js +1 -1
  112. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  113. package/dist/deduplication/records-protocol.d.ts +3 -8
  114. package/dist/deduplication/records-protocol.d.ts.map +1 -1
  115. package/dist/deduplication/records-protocol.js +11 -171
  116. package/dist/deduplication/records-protocol.js.map +1 -1
  117. package/dist/deduplication/records.js +1 -1
  118. package/dist/deduplication/records.js.map +1 -1
  119. package/dist/deduplication/scan.d.ts.map +1 -1
  120. package/dist/deduplication/scan.js +10 -9
  121. package/dist/deduplication/scan.js.map +1 -1
  122. package/dist/deep-config.d.ts +4 -1
  123. package/dist/deep-config.d.ts.map +1 -1
  124. package/dist/deep-config.js +21 -1
  125. package/dist/deep-config.js.map +1 -1
  126. package/dist/deep-progress.d.ts +15 -1
  127. package/dist/deep-progress.d.ts.map +1 -1
  128. package/dist/deep-progress.js +15 -16
  129. package/dist/deep-progress.js.map +1 -1
  130. package/dist/executable-path.d.ts +2 -0
  131. package/dist/executable-path.d.ts.map +1 -0
  132. package/dist/executable-path.js +12 -0
  133. package/dist/executable-path.js.map +1 -0
  134. package/dist/feedback.d.ts +1 -4
  135. package/dist/feedback.d.ts.map +1 -1
  136. package/dist/feedback.js +1 -1
  137. package/dist/feedback.js.map +1 -1
  138. package/dist/findings-import.d.ts +1 -1
  139. package/dist/findings-import.d.ts.map +1 -1
  140. package/dist/findings-import.js +3 -3
  141. package/dist/findings-import.js.map +1 -1
  142. package/dist/git-remote.d.ts +10 -0
  143. package/dist/git-remote.d.ts.map +1 -0
  144. package/dist/git-remote.js +24 -0
  145. package/dist/git-remote.js.map +1 -0
  146. package/dist/github.d.ts.map +1 -1
  147. package/dist/github.js +5 -7
  148. package/dist/github.js.map +1 -1
  149. package/dist/host-protocol.d.ts +19 -0
  150. package/dist/host-protocol.d.ts.map +1 -0
  151. package/dist/host-protocol.js +270 -0
  152. package/dist/host-protocol.js.map +1 -0
  153. package/dist/host-records-protocol.d.ts +15 -0
  154. package/dist/host-records-protocol.d.ts.map +1 -0
  155. package/dist/host-records-protocol.js +15 -0
  156. package/dist/host-records-protocol.js.map +1 -0
  157. package/dist/hosted-scan-protocol.d.ts +4 -0
  158. package/dist/hosted-scan-protocol.d.ts.map +1 -0
  159. package/dist/hosted-scan-protocol.js +25 -0
  160. package/dist/hosted-scan-protocol.js.map +1 -0
  161. package/dist/hosted-scan.d.ts +112 -0
  162. package/dist/hosted-scan.d.ts.map +1 -0
  163. package/dist/hosted-scan.js +260 -0
  164. package/dist/hosted-scan.js.map +1 -0
  165. package/dist/index.d.ts +7 -0
  166. package/dist/index.d.ts.map +1 -1
  167. package/dist/index.js +3 -0
  168. package/dist/index.js.map +1 -1
  169. package/dist/knowledge-base.d.ts.map +1 -1
  170. package/dist/knowledge-base.js +87 -7
  171. package/dist/knowledge-base.js.map +1 -1
  172. package/dist/multiscan.d.ts.map +1 -1
  173. package/dist/multiscan.js +108 -36
  174. package/dist/multiscan.js.map +1 -1
  175. package/dist/patch-publication.d.ts +26 -0
  176. package/dist/patch-publication.d.ts.map +1 -0
  177. package/dist/patch-publication.js +105 -0
  178. package/dist/patch-publication.js.map +1 -0
  179. package/dist/patch-tui.d.ts.map +1 -1
  180. package/dist/patch-tui.js +4 -1
  181. package/dist/patch-tui.js.map +1 -1
  182. package/dist/project-config-schema.d.ts +2 -0
  183. package/dist/project-config-schema.d.ts.map +1 -1
  184. package/dist/project-config-schema.js +1 -0
  185. package/dist/project-config-schema.js.map +1 -1
  186. package/dist/project-config.d.ts +1 -0
  187. package/dist/project-config.d.ts.map +1 -1
  188. package/dist/project-config.js +16 -6
  189. package/dist/project-config.js.map +1 -1
  190. package/dist/publication-store.d.ts.map +1 -1
  191. package/dist/publication-store.js +73 -63
  192. package/dist/publication-store.js.map +1 -1
  193. package/dist/publication.d.ts +0 -2
  194. package/dist/publication.d.ts.map +1 -1
  195. package/dist/publication.js +135 -24
  196. package/dist/publication.js.map +1 -1
  197. package/dist/publish.d.ts.map +1 -1
  198. package/dist/publish.js +39 -25
  199. package/dist/publish.js.map +1 -1
  200. package/dist/runtime.d.ts +5 -2
  201. package/dist/runtime.d.ts.map +1 -1
  202. package/dist/runtime.js +86 -58
  203. package/dist/runtime.js.map +1 -1
  204. package/dist/scan-executor.d.ts +104 -0
  205. package/dist/scan-executor.d.ts.map +1 -0
  206. package/dist/scan-executor.js +62 -0
  207. package/dist/scan-executor.js.map +1 -0
  208. package/dist/scan-settings.d.ts +1 -0
  209. package/dist/scan-settings.d.ts.map +1 -1
  210. package/dist/scan-settings.js +7 -1
  211. package/dist/scan-settings.js.map +1 -1
  212. package/dist/scan-time-budget.d.ts +9 -0
  213. package/dist/scan-time-budget.d.ts.map +1 -0
  214. package/dist/scan-time-budget.js +16 -0
  215. package/dist/scan-time-budget.js.map +1 -0
  216. package/dist/severity-review.d.ts +29 -0
  217. package/dist/severity-review.d.ts.map +1 -0
  218. package/dist/severity-review.js +47 -0
  219. package/dist/severity-review.js.map +1 -0
  220. package/dist/targets.d.ts.map +1 -1
  221. package/dist/targets.js +17 -25
  222. package/dist/targets.js.map +1 -1
  223. package/dist/validation-records.d.ts +38 -0
  224. package/dist/validation-records.d.ts.map +1 -0
  225. package/dist/validation-records.js +76 -0
  226. package/dist/validation-records.js.map +1 -0
  227. package/dist/version.d.ts.map +1 -1
  228. package/dist/version.js +4 -2
  229. package/dist/version.js.map +1 -1
  230. package/dist/worker-progress.d.ts +43 -15
  231. package/dist/worker-progress.d.ts.map +1 -1
  232. package/dist/worker-progress.js +22 -80
  233. package/dist/worker-progress.js.map +1 -1
  234. package/docs/classify-severity-records.md +89 -0
  235. package/docs/cli.md +281 -35
  236. package/docs/hosted-scans.md +242 -0
  237. package/docs/validate-records.md +69 -0
  238. package/package.json +18 -14
  239. package/schemas/hosted-scan-v2.fixture.json +145 -0
  240. package/schemas/project-config.schema.json +7 -1
  241. package/_bundled_plugin/preflight/capability-profiles.toml +0 -76
  242. package/_bundled_plugin/references/config-preflight.md +0 -93
  243. package/_bundled_plugin/references/desktop-config-preflight.md +0 -11
  244. package/_bundled_plugin/scripts/config_preflight.py +0 -911
package/dist/api.js CHANGED
@@ -9,6 +9,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
9
9
  /// <reference lib="esnext.disposable" preserve="true" />
10
10
  import { workbenchArgs } from "./workbench-arguments.js";
11
11
  import { isSafeNonNegativeInteger as safeInteger } from "./value.js";
12
+ import { ScanExecutionError, ScanExecutionResultSchema, } from "./scan-executor.js";
12
13
  import { chmod, lstat, mkdir, mkdtemp, readFile, realpath, rm, writeFile, } from "node:fs/promises";
13
14
  import { randomUUID } from "node:crypto";
14
15
  import { tmpdir } from "node:os";
@@ -31,6 +32,7 @@ import { runDeepScan } from "./deep-scan.js";
31
32
  import { deepScanOptions, resolveDeepScanConfig, writeDeepScanConfig, } from "./deep-config.js";
32
33
  import { DEFAULT_SCAN_AUTH, DEFAULT_SCAN_MODE, SCAN_AUTH_MODES, ScanSettingsSchema, } from "./scan-settings.js";
33
34
  import { resolveScanPrompts } from "./prompt-files.js";
35
+ import { readScanTimeBudgetPolicy, renderScanTimeBudgetPolicy, scanTimeBudget, } from "./scan-time-budget.js";
34
36
  import { standaloneValidationPrompt } from "./standalone-validation-prompt.js";
35
37
  export { SCAN_AUTH_MODES } from "./scan-settings.js";
36
38
  import { loadContract, readScanFile, requireScanFile, } from "./contract.js";
@@ -113,7 +115,8 @@ function patchOutcomeFromResponse(response) {
113
115
  };
114
116
  }
115
117
  }
116
- const DEFAULT_DEPENDENCIES = {
118
+ /** @internal */
119
+ export const DEFAULT_DEPENDENCIES = {
117
120
  createCodex: ({ nativeProfile, ...options }) => nativeProfile === undefined
118
121
  ? new Codex(options)
119
122
  : createProfileCodex(options, nativeProfile),
@@ -148,6 +151,9 @@ export class CodexSecurity {
148
151
  this.#surface = runtimeOptions.surface;
149
152
  }
150
153
  async run(repository, options = {}) {
154
+ // Reject the removed experimental option rather than starting local inference.
155
+ if ("hosted" in options)
156
+ throw new CodexSecurityError("Use runHostedScan with an executor for hosted execution.");
151
157
  return await this.#trackOperation(() => options.workflowId === undefined
152
158
  ? this.#run(repository, { ...options })
153
159
  : this.#runWorkflow(repository, { ...options }, options.workflowId));
@@ -504,12 +510,19 @@ export class CodexSecurity {
504
510
  : {}),
505
511
  outputDir: inputs.outputDir,
506
512
  ...(archiveDir === null ? {} : { archiveDir }),
507
- authentication: scanAuthentication(this.#dependencies.environment, options.auth, modelProvider, hasCommandAuth(configuration)),
513
+ authentication: scanAuthentication(this.#dependencies.environment, options.auth, modelProvider, hasCommandAuth(configuration), true),
508
514
  ...model,
509
515
  ...(typeof modelProvider === "string" ? { modelProvider } : {}),
510
516
  ...(options.maxCostUsd === undefined
511
517
  ? {}
512
518
  : { maxCostUsd: options.maxCostUsd }),
519
+ ...(inputs.deepScanConfiguration !== undefined
520
+ ? {
521
+ maxTimeMinutes: inputs.deepScanConfiguration.settings.maxTimeHours * 60,
522
+ }
523
+ : options.maxTimeMinutes === undefined
524
+ ? {}
525
+ : { maxTimeMinutes: options.maxTimeMinutes }),
513
526
  };
514
527
  }
515
528
  async preflightPolicy(repository, options = {}) {
@@ -773,6 +786,7 @@ export class CodexSecurity {
773
786
  let artifactRestorationFailure = null;
774
787
  let customValidationComplete = false;
775
788
  let completionCost = null;
789
+ let scanTurnStatus = null;
776
790
  let budgetRecovery = null;
777
791
  let preparedTargetWarnings = [];
778
792
  let runPostScan = null;
@@ -780,6 +794,35 @@ export class CodexSecurity {
780
794
  const prepareArtifactRestorer = this.#dependencies.prepareScanArtifactRestorer ??
781
795
  prepareScanArtifactRestorer;
782
796
  const workbench = this.#dependencies.runWorkbench ?? runWorkbench;
797
+ const terminalScanTurnStatus = () => scanTurnStatus === "completed" || scanTurnStatus === "failed"
798
+ ? scanTurnStatus
799
+ : signal.aborted
800
+ ? "interrupted"
801
+ : null;
802
+ const finalizeScanUsage = async (scanId, workbenchOptions, completedScan, turnStatus) => {
803
+ const measuredUsage = isRecord(completedScan)
804
+ ? completedScan["usage"]
805
+ : undefined;
806
+ const usageCompletion = isRecord(measuredUsage)
807
+ ? measuredUsage["completion"]
808
+ : undefined;
809
+ if (isRecord(usageCompletion) &&
810
+ usageCompletion["finalized"] === false &&
811
+ typeof usageCompletion["threadId"] === "string" &&
812
+ typeof usageCompletion["turnId"] === "string") {
813
+ try {
814
+ await workbench({ ...workbenchOptions, signal: undefined }, workbenchArgs("finalize-scan-usage", {
815
+ scanId,
816
+ threadId: usageCompletion["threadId"],
817
+ turnId: usageCompletion["turnId"],
818
+ turnStatus,
819
+ }));
820
+ }
821
+ catch (error) {
822
+ notifyObserver(options, "onWarning")(`Could not finalize scan token usage: ${errorMessage(error)}`);
823
+ }
824
+ }
825
+ };
783
826
  try {
784
827
  const checkOpen = () => {
785
828
  this.#requireOpen();
@@ -827,6 +870,14 @@ export class CodexSecurity {
827
870
  ...(knowledgeBase?.protectedRoots ?? []),
828
871
  ]) {
829
872
  git = await inspectTrustedExecutable("git", git.environment, root);
873
+ if (this.#dependencies.hostedScan !== undefined) {
874
+ // Match the hosted MCP launchers' PATH-based tool lookups.
875
+ for (const command of process.platform === "win32"
876
+ ? ["node"]
877
+ : ["dirname", "node"]) {
878
+ git.environment = (await inspectTrustedExecutable(command, git.environment, root)).environment;
879
+ }
880
+ }
830
881
  }
831
882
  checkOpen();
832
883
  const scanOutputRoot = requestedOutput === null &&
@@ -856,6 +907,10 @@ export class CodexSecurity {
856
907
  }),
857
908
  };
858
909
  const { environment: workerEnvironment, ...workerRuntimeConfig } = selectedWorkerRuntimeConfig(effectiveConfig, modelProvider, scanDir, workerProviderEnvironment);
910
+ const sqliteHome = workerRuntimeConfig["sqlite_home"];
911
+ const sqliteEnvironment = mode === "deep" && typeof sqliteHome === "string"
912
+ ? { CODEX_SQLITE_HOME: sqliteHome }
913
+ : {};
859
914
  const workerSnapshot = {
860
915
  ...workerRuntimeConfig,
861
916
  responses_api_metadata: {
@@ -1040,6 +1095,7 @@ export class CodexSecurity {
1040
1095
  knowledgeBasePaths: knowledgeBase?.sources,
1041
1096
  maxCostUsd: options.maxCostUsd,
1042
1097
  deepScan: deepScanConfiguration?.settings,
1098
+ maxTimeMinutes: options.maxTimeMinutes,
1043
1099
  auth: options.auth,
1044
1100
  cyberAccessProgram: options.cyberAccessProgram,
1045
1101
  });
@@ -1057,6 +1113,7 @@ export class CodexSecurity {
1057
1113
  pluginRoot: runtime.plugin.pluginRoot,
1058
1114
  environment: {
1059
1115
  ...environmentWithGit(git.environment, git),
1116
+ ...sqliteEnvironment,
1060
1117
  CODEX_SECURITY_STATE_DIR: stateDirectory,
1061
1118
  },
1062
1119
  signal,
@@ -1202,7 +1259,7 @@ export class CodexSecurity {
1202
1259
  await writeCustomValidationStatus(scanDir, { scanId, status: "pending" }, signal);
1203
1260
  }
1204
1261
  checkOpen();
1205
- const basePrompt = scanPrompt(normalized, mode, skillName, scanId, runtime.configPath !== undefined, knowledgeBase !== null, options.resumeScanId !== undefined &&
1262
+ const basePrompt = scanPrompt(normalized, mode, skillName, scanId, knowledgeBase !== null, options.resumeScanId !== undefined &&
1206
1263
  typeof registration["userContext"] === "string"
1207
1264
  ? registration["userContext"]
1208
1265
  : options.scanPrompt, options.maxCostUsd !== undefined, discoveryPrompt, modelProvider);
@@ -1246,6 +1303,7 @@ export class CodexSecurity {
1246
1303
  ? join(dirname(runtime.codexHome), `codex-security-target-paths-${randomUUID()}.json`)
1247
1304
  : null;
1248
1305
  const runtimePaths = {
1306
+ ...sqliteEnvironment,
1249
1307
  PYTHON: python,
1250
1308
  CODEX_SECURITY_STARTED_AT: options.resumeScanId !== undefined &&
1251
1309
  typeof registration["startedAt"] === "string"
@@ -1322,6 +1380,11 @@ export class CodexSecurity {
1322
1380
  if (postScanPrompt?.trim()) {
1323
1381
  runPostScan = () => thread.runStreamed(postScanPrompt, turnOptions);
1324
1382
  }
1383
+ if (mode === "standard" && options.maxTimeMinutes !== undefined) {
1384
+ const timePolicy = await readScanTimeBudgetPolicy(runtime.plugin.pluginRoot);
1385
+ checkOpen();
1386
+ prompt += `\n\n${renderScanTimeBudgetPolicy(timePolicy, scanTimeBudget(options.maxTimeMinutes, (this.#dependencies.now ?? Date.now)()))}`;
1387
+ }
1325
1388
  const events = directDeepScan
1326
1389
  ? (this.#dependencies.runDeepScan ?? runDeepScan)({
1327
1390
  codexOptions,
@@ -1334,6 +1397,7 @@ export class CodexSecurity {
1334
1397
  signal,
1335
1398
  })
1336
1399
  : (await thread.runStreamed(prompt, turnOptions)).events;
1400
+ scanTurnStatus = "in_progress";
1337
1401
  checkOpen();
1338
1402
  let result = await runScanEvents({
1339
1403
  thread,
@@ -1349,6 +1413,9 @@ export class CodexSecurity {
1349
1413
  modelProvider,
1350
1414
  workbenchValidated: true,
1351
1415
  model,
1416
+ onTurnStatus: (status) => {
1417
+ scanTurnStatus = status;
1418
+ },
1352
1419
  onThreadStarted: async (threadId) => {
1353
1420
  if (resumeThreadId !== undefined && threadId !== resumeThreadId) {
1354
1421
  throw new CodexSecurityError("Codex did not resume the original scan session.");
@@ -1489,6 +1556,8 @@ export class CodexSecurity {
1489
1556
  : ["--cost-json", JSON.stringify(completionCost)]),
1490
1557
  ]);
1491
1558
  activeScan = null;
1559
+ const completedScan = completion["scan"];
1560
+ await finalizeScanUsage(scanId, workbenchOptions, completedScan, "completed");
1492
1561
  if (directDeepScan) {
1493
1562
  result = new ScanResult({
1494
1563
  ...result,
@@ -1498,7 +1567,6 @@ export class CodexSecurity {
1498
1567
  },
1499
1568
  });
1500
1569
  }
1501
- const completedScan = completion["scan"];
1502
1570
  if (isRecord(completedScan) && Array.isArray(completedScan["warnings"])) {
1503
1571
  const targetWarnings = new Set([
1504
1572
  ...preparedTargetWarnings,
@@ -1580,6 +1648,8 @@ export class CodexSecurity {
1580
1648
  notifyObserver(options, "onWarning")(`Could not run post-scan instructions: ${errorMessage(error)}`);
1581
1649
  }
1582
1650
  }
1651
+ if (this.#dependencies.hostedScan !== undefined)
1652
+ return result;
1583
1653
  try {
1584
1654
  const runWorkbench = (args, input) => workbench(workbenchOptions, args, input);
1585
1655
  const previousFindings = await listRepositoryFindings(runWorkbench, targetId, "all");
@@ -1624,6 +1694,7 @@ export class CodexSecurity {
1624
1694
  const snapshot = await costTracker?.stop().catch(() => null);
1625
1695
  if (artifactRestorationFailure !== null)
1626
1696
  throw artifactRestorationFailure;
1697
+ const terminalTurnStatus = terminalScanTurnStatus();
1627
1698
  let failure = signal.reason instanceof ScanCostLimitExceededError
1628
1699
  ? signal.reason
1629
1700
  : error;
@@ -1647,6 +1718,8 @@ export class CodexSecurity {
1647
1718
  JSON.stringify(snapshot?.cost ?? failure.cost),
1648
1719
  `--message=${failure.message.slice(0, 2400)}`,
1649
1720
  ]);
1721
+ if (terminalTurnStatus !== null)
1722
+ await finalizeScanUsage(activeScan.id, activeScan.options, completion["scan"], terminalTurnStatus);
1650
1723
  activeScan = null;
1651
1724
  runPostScan = null;
1652
1725
  const result = await collectResult({
@@ -1675,6 +1748,25 @@ export class CodexSecurity {
1675
1748
  }
1676
1749
  catch { }
1677
1750
  }
1751
+ if (activeScan !== null && scanTurnStatus !== null) {
1752
+ try {
1753
+ const cleanupOptions = { ...activeScan.options, signal: undefined };
1754
+ const saved = await workbench(cleanupOptions, workbenchArgs("get-scan", { scanId: activeScan.id }));
1755
+ const completedScan = saved["scan"];
1756
+ const progress = isRecord(completedScan)
1757
+ ? completedScan["progress"]
1758
+ : undefined;
1759
+ if (isRecord(progress) && progress["status"] === "complete") {
1760
+ const scanId = activeScan.id;
1761
+ activeScan = null;
1762
+ if (terminalTurnStatus !== null)
1763
+ await finalizeScanUsage(scanId, cleanupOptions, completedScan, terminalTurnStatus);
1764
+ }
1765
+ }
1766
+ catch (cleanupError) {
1767
+ notifyObserver(options, "onWarning")(`Could not finalize scan token usage: ${errorMessage(cleanupError)}`);
1768
+ }
1769
+ }
1678
1770
  // A failed attachment must not turn a resumable coordinator into a terminal failure.
1679
1771
  // Deep Scan orchestration persists its own terminal failures and cancellations.
1680
1772
  if (activeScan !== null && options.resumeScanId === undefined) {
@@ -1713,7 +1805,9 @@ export class CodexSecurity {
1713
1805
  }
1714
1806
  if (this.#closed)
1715
1807
  this.#requireOpen();
1716
- if (signal.aborted && !(failure instanceof ScanInterruptedError)) {
1808
+ if (signal.aborted &&
1809
+ !(failure instanceof ScanInterruptedError) &&
1810
+ !(failure instanceof ScanExecutionError)) {
1717
1811
  throwIfAborted(signal, scanDir);
1718
1812
  }
1719
1813
  throw failure;
@@ -1799,7 +1893,10 @@ export class CodexSecurity {
1799
1893
  if (this.#closePromise !== null)
1800
1894
  return await this.#closePromise;
1801
1895
  this.#closed = true;
1802
- this.#closePromise = this.#finishClose();
1896
+ const completion = Promise.withResolvers();
1897
+ // Abort listeners can reenter close before finishClose reaches its first await.
1898
+ this.#closePromise = completion.promise;
1899
+ void this.#finishClose().then(completion.resolve, completion.reject);
1803
1900
  await this.#closePromise;
1804
1901
  }
1805
1902
  async #finishClose() {
@@ -1866,18 +1963,99 @@ export class CodexSecurity {
1866
1963
  if (this.#activeOperation !== null) {
1867
1964
  throw new CodexSecurityError("A Codex Security operation is already in progress.");
1868
1965
  }
1869
- const activeOperation = operation();
1870
- this.#activeOperation = activeOperation;
1966
+ const activeOperation = Promise.withResolvers();
1967
+ this.#activeOperation = activeOperation.promise;
1871
1968
  try {
1872
- return await activeOperation;
1969
+ return await operation();
1873
1970
  }
1874
1971
  finally {
1875
- if (this.#activeOperation === activeOperation) {
1972
+ if (this.#activeOperation === activeOperation.promise) {
1876
1973
  this.#activeOperation = null;
1877
1974
  }
1975
+ activeOperation.resolve();
1878
1976
  }
1879
1977
  }
1880
1978
  async #createSessionCodex(session, command, runtimePaths, auth = "auto", git, config, configOverrides = []) {
1979
+ const hosted = this.#dependencies.hostedScan;
1980
+ if (hosted !== undefined) {
1981
+ const environment = {
1982
+ ...definedEnvironment(environmentWithGit(session.runtime.environment, git)),
1983
+ ...runtimePaths,
1984
+ };
1985
+ const model = scanModelConfiguration(session.effectiveConfig);
1986
+ return {
1987
+ environment,
1988
+ // Hosted Standard scans do not launch a local Codex process.
1989
+ codexOptions: {},
1990
+ codex: {
1991
+ startThread: () => {
1992
+ let id = null;
1993
+ return {
1994
+ get id() {
1995
+ return id;
1996
+ },
1997
+ async runStreamed(prompt, { signal }) {
1998
+ const request = {
1999
+ version: 2,
2000
+ requestId: randomUUID(),
2001
+ ...hosted.context,
2002
+ scanId: runtimePaths["CODEX_SECURITY_SCAN_ID"],
2003
+ prompt,
2004
+ ...model,
2005
+ runtime: {
2006
+ pluginRoot: session.runtime.plugin.pluginRoot,
2007
+ pluginVersion: session.runtime.plugin.version,
2008
+ stateDirectory: runtimePaths["CODEX_SECURITY_STATE_DIR"],
2009
+ outputDirectory: runtimePaths["CODEX_SECURITY_SCAN_DIR"],
2010
+ environment,
2011
+ },
2012
+ };
2013
+ // A transport failure is terminal; only the host can reconcile
2014
+ // whether remote execution was accepted.
2015
+ let result;
2016
+ try {
2017
+ result = ScanExecutionResultSchema.parse(await hosted.executor.run(request, {
2018
+ signal: signal ?? new AbortController().signal,
2019
+ onEvent: hosted.onEvent,
2020
+ }));
2021
+ }
2022
+ catch (error) {
2023
+ // Transport failure does not prove non-acceptance. Never resubmit.
2024
+ throw new ScanExecutionError({
2025
+ requestId: request.requestId,
2026
+ status: "acceptance_unknown",
2027
+ message: errorMessage(error),
2028
+ });
2029
+ }
2030
+ if (result.requestId !== request.requestId)
2031
+ throw new ScanExecutionError({
2032
+ ...result,
2033
+ requestId: request.requestId,
2034
+ status: "acceptance_unknown",
2035
+ message: "Execution response does not match the active request.",
2036
+ });
2037
+ if (result.status !== "completed")
2038
+ throw new ScanExecutionError(result);
2039
+ id = result.sessionId;
2040
+ return {
2041
+ events: (async function* () {
2042
+ yield { type: "thread.started", thread_id: id };
2043
+ yield {
2044
+ type: "item.completed",
2045
+ item: {
2046
+ type: "agent_message",
2047
+ text: result.finalResponse ?? "",
2048
+ },
2049
+ };
2050
+ yield { type: "turn.completed", usage: result.usage };
2051
+ })(),
2052
+ };
2053
+ },
2054
+ };
2055
+ },
2056
+ },
2057
+ };
2058
+ }
1881
2059
  const { runtime, runtimeHome, python, modelProvider, externalProvider, apiKey, sessionConfig, } = session;
1882
2060
  const commandAuth = hasCommandAuth(sessionConfig);
1883
2061
  const environment = {
@@ -1952,6 +2130,57 @@ export class CodexSecurity {
1952
2130
  return { codex, environment, codexOptions };
1953
2131
  }
1954
2132
  async #prepareSession({ protectedRoot, protectedRoots = [protectedRoot], }, options, signal, temporaryRoot, deepScan = false) {
2133
+ if (this.#dependencies.hostedScan !== undefined) {
2134
+ // Hosted scans use only the explicitly selected bundle and configuration.
2135
+ // No local auth, Codex subprocess, provider profile, or ambient config.
2136
+ const environment = this.#dependencies.environment;
2137
+ const pluginRoot = await bundledPluginRoot();
2138
+ const metadata = await pluginMetadata(pluginRoot);
2139
+ const effectiveConfig = {
2140
+ // The executor supplies its actual tools and capacity. Local Codex
2141
+ // defaults must not masquerade as hosted runtime capabilities.
2142
+ approval_policy: "never",
2143
+ ...this.config.codexOverrides,
2144
+ };
2145
+ const preflightConfig = scanPreflightCodexConfig(effectiveConfig);
2146
+ const runtimeHome = await createIsolatedHome(temporaryRoot, (path) => requireOutputOutsideRepositories(protectedRoots, path, "runtime"));
2147
+ const configPath = join(runtimeHome, "config-preflight.toml");
2148
+ const runtime = {
2149
+ codexHome: runtimeHome,
2150
+ bootstrapWorkspace: runtimeHome,
2151
+ configPath,
2152
+ credentialsAvailable: false,
2153
+ environment: definedEnvironment(environment),
2154
+ plugin: {
2155
+ ...metadata,
2156
+ pluginRoot,
2157
+ installedRoot: pluginRoot,
2158
+ marketplaceRoot: pluginRoot,
2159
+ marketplaceName: "codex-security-sdk",
2160
+ },
2161
+ };
2162
+ this.#runtime = runtime;
2163
+ await writeCodexConfig(configPath, preflightConfig);
2164
+ const python = await resolvePluginPython({
2165
+ environment,
2166
+ protectedRoot,
2167
+ signal,
2168
+ });
2169
+ return {
2170
+ runtime,
2171
+ runtimeHome,
2172
+ effectiveConfig,
2173
+ preflightConfig,
2174
+ sessionConfig: preflightConfig,
2175
+ modelProvider: "host",
2176
+ externalProvider: null,
2177
+ apiKey: null,
2178
+ scanEnvironment: environment,
2179
+ authentication: { method: "host", verified: false },
2180
+ approvalPolicy: "never",
2181
+ python,
2182
+ };
2183
+ }
1955
2184
  let releaseCredentialHome = null;
1956
2185
  const checkOpen = () => {
1957
2186
  this.#requireOpen();
@@ -2219,6 +2448,7 @@ export class CodexSecurity {
2219
2448
  failOnSeverity: options.failureSeverity,
2220
2449
  knowledgeBasePaths: options.knowledgeBasePaths,
2221
2450
  maxCostUsd: options.maxCostUsd,
2451
+ maxTimeMinutes: options.maxTimeMinutes,
2222
2452
  auth: options.auth,
2223
2453
  cyberAccessProgram: options.cyberAccessProgram,
2224
2454
  }),
@@ -2541,6 +2771,10 @@ export async function runScanEvents(options) {
2541
2771
  thread: options.thread,
2542
2772
  events: options.events,
2543
2773
  onEvent: async (event) => {
2774
+ if (event.type === "turn.completed")
2775
+ options.onTurnStatus?.("completed");
2776
+ if (event.type === "turn.failed")
2777
+ options.onTurnStatus?.("failed");
2544
2778
  if (!tacStatusReported &&
2545
2779
  options.modelProvider !== "amazon-bedrock" &&
2546
2780
  options.authentication?.method !== "aws_credentials") {
@@ -2716,7 +2950,7 @@ function trustedAccessWarning(status, authentication) {
2716
2950
  : "your Trusted Access for Cyber status";
2717
2951
  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}.`;
2718
2952
  }
2719
- function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasKnowledgeBase = false, additionalPrompt, enforceCostLimit = false, discoveryPrompt, modelProvider) {
2953
+ function scanPrompt(target, mode, skillName, scanId, hasKnowledgeBase = false, additionalPrompt, enforceCostLimit = false, discoveryPrompt, modelProvider) {
2720
2954
  const python = pluginPythonCommand();
2721
2955
  const customValidation = discoveryPrompt !== undefined;
2722
2956
  return [
@@ -2769,11 +3003,6 @@ function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasK
2769
3003
  '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.',
2770
3004
  '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.',
2771
3005
  ]),
2772
- ...(hasConfigPath
2773
- ? [
2774
- `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.`,
2775
- ]
2776
- : []),
2777
3006
  ...(hasKnowledgeBase
2778
3007
  ? [
2779
3008
  `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.`,
@@ -2825,7 +3054,7 @@ function targetInstruction(target, python) {
2825
3054
  }
2826
3055
  return `Scan target: staged and unstaged working-tree changes against ${target.base}.`;
2827
3056
  }
2828
- function scanRecipe({ repository, target, mode, repositoryRevision, pluginVersion, config, failOnSeverity, knowledgeBasePaths, maxCostUsd, deepScan, auth, cyberAccessProgram, }) {
3057
+ function scanRecipe({ repository, target, mode, repositoryRevision, pluginVersion, config, failOnSeverity, knowledgeBasePaths, maxCostUsd, maxTimeMinutes, deepScan, auth, cyberAccessProgram, }) {
2829
3058
  return {
2830
3059
  repository,
2831
3060
  target: { ...target, paths: [...target.paths] },
@@ -2838,6 +3067,7 @@ function scanRecipe({ repository, target, mode, repositoryRevision, pluginVersio
2838
3067
  ...(failOnSeverity === undefined ? {} : { failOnSeverity }),
2839
3068
  ...(knowledgeBasePaths === undefined ? {} : { knowledgeBasePaths }),
2840
3069
  ...(maxCostUsd === undefined ? {} : { maxCostUsd }),
3070
+ ...(maxTimeMinutes === undefined ? {} : { maxTimeMinutes }),
2841
3071
  ...(deepScan === undefined
2842
3072
  ? {}
2843
3073
  : { deepScan: { ...deepScan }, deepScanResolved: true }),
@@ -2935,7 +3165,7 @@ async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectat
2935
3165
  }),
2936
3166
  });
2937
3167
  }
2938
- export function scanAuthentication(environment, auth = DEFAULT_SCAN_AUTH, modelProvider, commandAuth = false) {
3168
+ export function scanAuthentication(environment, auth = DEFAULT_SCAN_AUTH, modelProvider, commandAuth = false, preflight = false) {
2939
3169
  if (!SCAN_AUTH_MODES.includes(auth)) {
2940
3170
  throw new TypeError("Scan authentication mode must be auto, chatgpt, or api-key.");
2941
3171
  }
@@ -2963,6 +3193,9 @@ export function scanAuthentication(environment, auth = DEFAULT_SCAN_AUTH, modelP
2963
3193
  const key = environmentApiKeyEntry(environment, modelProvider);
2964
3194
  if (key === null && isExternalModelProvider(modelProvider)) {
2965
3195
  const provider = EXTERNAL_CODEX_PROVIDERS[modelProvider];
3196
+ if (preflight && auth === "auto") {
3197
+ return { method: "api_key", source: provider.env_key, verified: false };
3198
+ }
2966
3199
  throw new AuthenticationRequiredError(`Set ${provider.env_key} to run a scan through ${provider.name}.`);
2967
3200
  }
2968
3201
  if (auth === "api-key" &&
@@ -3021,7 +3254,9 @@ export function selectedScanEnvironment(environment, auth = "auto", modelProvide
3021
3254
  }
3022
3255
  return Object.fromEntries(Object.entries(withoutOpenAiApiKeys(environment)).filter(([name]) => {
3023
3256
  const key = name.toUpperCase();
3024
- if (key === "OPENROUTER_API_KEY" || key === "FIREWORKS_API_KEY") {
3257
+ if (key === "OPENROUTER_API_KEY" ||
3258
+ key === "FIREWORKS_API_KEY" ||
3259
+ key === "CHEAPER_INFERENCE_API_KEY") {
3025
3260
  return (!bedrockProvider &&
3026
3261
  (selectedProviderKey === null || key === selectedProviderKey));
3027
3262
  }
@@ -3431,28 +3666,20 @@ function selectedWorkerRuntimeConfig(config, selectedProvider, workingDirectory,
3431
3666
  const value = key === undefined ? undefined : environment[key];
3432
3667
  return value === undefined ? [] : [[name, value]];
3433
3668
  }));
3434
- const instructionsFile = resolved["model_instructions_file"];
3435
- if (typeof instructionsFile === "string") {
3436
- resolved["model_instructions_file"] = resolve(workingDirectory, expandHome(instructionsFile, environment));
3669
+ // Workers use separate directories; preserve the parent scan's native paths.
3670
+ for (const key of [
3671
+ "model_instructions_file",
3672
+ "experimental_compact_prompt_file",
3673
+ "model_catalog_json",
3674
+ "sqlite_home",
3675
+ ]) {
3676
+ const file = resolved[key];
3677
+ if (typeof file === "string") {
3678
+ resolved[key] = resolve(workingDirectory, expandHome(file, environment));
3679
+ }
3437
3680
  }
3438
3681
  return {
3439
- ...Object.fromEntries([
3440
- ...CODEX_AUTH_CONFIG_KEYS,
3441
- "analytics",
3442
- "responses_api_metadata",
3443
- "openai_base_url",
3444
- "features",
3445
- "model_auto_compact_token_limit",
3446
- "model_context_window",
3447
- "model_instructions_file",
3448
- "model_verbosity",
3449
- "shell_environment_policy",
3450
- "skills",
3451
- "web_search",
3452
- "windows",
3453
- ]
3454
- .filter((key) => resolved[key] !== undefined)
3455
- .map((key) => [key, resolved[key]])),
3682
+ ...structuredCodexConfig(resolved),
3456
3683
  ...(provider === undefined ? {} : { model_provider: provider }),
3457
3684
  ...(Object.keys(providerEnvironment).length === 0
3458
3685
  ? {}