@openai/codex-security 0.1.26 → 0.1.28

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 (253) hide show
  1. package/README.md +637 -74
  2. package/_bundled_plugin/.mcp.json +1 -0
  3. package/_bundled_plugin/mcp/helpers.mjs +24 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  5. package/_bundled_plugin/mcp/native/COPYRIGHT-library.html +5556 -0
  6. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +5989 -0
  7. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  8. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  9. package/_bundled_plugin/mcp/native/licenses/Apache-2.0.txt +73 -0
  10. package/_bundled_plugin/mcp/native/licenses/BSD-2-Clause.txt +9 -0
  11. package/_bundled_plugin/mcp/native/licenses/MIT.txt +9 -0
  12. package/_bundled_plugin/mcp/native/licenses/Unicode-3.0.txt +39 -0
  13. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  14. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  15. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  16. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  17. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  18. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  19. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  20. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  21. package/_bundled_plugin/references/artifact-storage.md +56 -0
  22. package/_bundled_plugin/references/config-preflight.md +9 -1
  23. package/_bundled_plugin/references/core-scan.md +1 -1
  24. package/_bundled_plugin/references/final-report.md +2 -0
  25. package/_bundled_plugin/references/scan-artifacts.md +6 -14
  26. package/_bundled_plugin/references/scan-contract.md +35 -35
  27. package/_bundled_plugin/references/scan-prologue.md +2 -0
  28. package/_bundled_plugin/references/security-guidance.md +9 -1
  29. package/_bundled_plugin/scripts/deep_scan_config.py +10 -8
  30. package/_bundled_plugin/scripts/deep_scan_defaults.json +8 -0
  31. package/_bundled_plugin/scripts/generate_in_scope_files.py +2 -2
  32. package/_bundled_plugin/scripts/generate_rank_input.py +8 -1
  33. package/_bundled_plugin/scripts/launch_codex_security_mcp +6 -0
  34. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +43 -9
  35. package/_bundled_plugin/scripts/rank_preview.py +4 -1
  36. package/_bundled_plugin/scripts/reserved_artifact_paths.json +6 -0
  37. package/_bundled_plugin/scripts/windows_scan_local_files.py +1 -3
  38. package/_bundled_plugin/scripts/workbench/storage.py +18 -0
  39. package/_bundled_plugin/scripts/workbench_cli.py +17 -0
  40. package/_bundled_plugin/scripts/workbench_db.py +46 -42
  41. package/_bundled_plugin/scripts/workbench_saved_results.py +72 -1
  42. package/_bundled_plugin/scripts/workbench_scan_history.py +117 -2
  43. package/_bundled_plugin/scripts/workbench_scan_usage.py +23 -10
  44. package/_bundled_plugin/scripts/workbench_validation.py +4 -0
  45. package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +2 -0
  46. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +2 -0
  47. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +5 -1
  48. package/_bundled_plugin/skills/define-security-policy/SKILL.md +3 -3
  49. package/_bundled_plugin/skills/finding-discovery/SKILL.md +2 -0
  50. package/_bundled_plugin/skills/fix-finding/SKILL.md +3 -1
  51. package/_bundled_plugin/skills/fix-finding/agents/openai.yaml +1 -1
  52. package/_bundled_plugin/skills/propose-security-hardening/SKILL.md +2 -0
  53. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +5 -1
  54. package/_bundled_plugin/skills/threat-model/SKILL.md +2 -0
  55. package/_bundled_plugin/skills/validation/SKILL.md +2 -0
  56. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +2 -0
  57. package/dist/api.d.ts +14 -24
  58. package/dist/api.d.ts.map +1 -1
  59. package/dist/api.js +585 -168
  60. package/dist/api.js.map +1 -1
  61. package/dist/auth.d.ts.map +1 -1
  62. package/dist/auth.js +10 -0
  63. package/dist/auth.js.map +1 -1
  64. package/dist/bulk-scan-discovery.d.ts +1 -1
  65. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  66. package/dist/bulk-scan-discovery.js +2 -2
  67. package/dist/bulk-scan-discovery.js.map +1 -1
  68. package/dist/classify-scan-severity.js.map +1 -1
  69. package/dist/classify-severity.d.ts.map +1 -1
  70. package/dist/classify-severity.js.map +1 -1
  71. package/dist/cli.d.ts +24 -4
  72. package/dist/cli.d.ts.map +1 -1
  73. package/dist/cli.js +1577 -610
  74. package/dist/cli.js.map +1 -1
  75. package/dist/cloud-publish.d.ts.map +1 -1
  76. package/dist/cloud-publish.js +2 -207
  77. package/dist/cloud-publish.js.map +1 -1
  78. package/dist/component-plan.d.ts.map +1 -1
  79. package/dist/component-plan.js +116 -32
  80. package/dist/component-plan.js.map +1 -1
  81. package/dist/component-scan.d.ts +4 -2
  82. package/dist/component-scan.d.ts.map +1 -1
  83. package/dist/component-scan.js +7 -1
  84. package/dist/component-scan.js.map +1 -1
  85. package/dist/config-path.d.ts +6 -0
  86. package/dist/config-path.d.ts.map +1 -0
  87. package/dist/config-path.js +6 -0
  88. package/dist/config-path.js.map +1 -0
  89. package/dist/config.d.ts +3 -0
  90. package/dist/config.d.ts.map +1 -1
  91. package/dist/config.js +30 -5
  92. package/dist/config.js.map +1 -1
  93. package/dist/contract.d.ts +5 -10
  94. package/dist/contract.d.ts.map +1 -1
  95. package/dist/contract.js.map +1 -1
  96. package/dist/cost-model.d.ts +30 -0
  97. package/dist/cost-model.d.ts.map +1 -1
  98. package/dist/cost-model.js +123 -4
  99. package/dist/cost-model.js.map +1 -1
  100. package/dist/cost.d.ts.map +1 -1
  101. package/dist/cost.js +18 -3
  102. package/dist/cost.js.map +1 -1
  103. package/dist/custom-publish.js.map +1 -1
  104. package/dist/custom-validation-prompt.js +1 -1
  105. package/dist/custom-validation-prompt.js.map +1 -1
  106. package/dist/deduplication/checkpointed-review.d.ts.map +1 -1
  107. package/dist/deduplication/checkpointed-review.js.map +1 -1
  108. package/dist/deduplication/codex-review.d.ts +6 -1
  109. package/dist/deduplication/codex-review.d.ts.map +1 -1
  110. package/dist/deduplication/codex-review.js +72 -17
  111. package/dist/deduplication/codex-review.js.map +1 -1
  112. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  113. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  114. package/dist/deduplication/deduplication.d.ts +2 -0
  115. package/dist/deduplication/deduplication.d.ts.map +1 -1
  116. package/dist/deduplication/deduplication.js +99 -26
  117. package/dist/deduplication/deduplication.js.map +1 -1
  118. package/dist/deduplication/retry.d.ts +3 -0
  119. package/dist/deduplication/retry.d.ts.map +1 -0
  120. package/dist/deduplication/retry.js +15 -0
  121. package/dist/deduplication/retry.js.map +1 -0
  122. package/dist/deduplication/scan.d.ts +2 -0
  123. package/dist/deduplication/scan.d.ts.map +1 -1
  124. package/dist/deduplication/scan.js +4 -2
  125. package/dist/deduplication/scan.js.map +1 -1
  126. package/dist/deep-config.d.ts +17 -0
  127. package/dist/deep-config.d.ts.map +1 -0
  128. package/dist/deep-config.js +145 -0
  129. package/dist/deep-config.js.map +1 -0
  130. package/dist/deep-progress.d.ts.map +1 -1
  131. package/dist/deep-scan-defaults.d.ts +9 -0
  132. package/dist/deep-scan-defaults.d.ts.map +1 -0
  133. package/dist/deep-scan-defaults.js +10 -0
  134. package/dist/deep-scan-defaults.js.map +1 -0
  135. package/dist/errors.d.ts.map +1 -1
  136. package/dist/errors.js +2 -2
  137. package/dist/errors.js.map +1 -1
  138. package/dist/feedback.d.ts +20 -0
  139. package/dist/feedback.d.ts.map +1 -0
  140. package/dist/feedback.js +135 -0
  141. package/dist/feedback.js.map +1 -0
  142. package/dist/finding-catalogue.js.map +1 -1
  143. package/dist/finding-workflow.d.ts.map +1 -1
  144. package/dist/finding-workflow.js.map +1 -1
  145. package/dist/findings-client.d.ts +7 -1
  146. package/dist/findings-client.d.ts.map +1 -1
  147. package/dist/findings-client.js +55 -10
  148. package/dist/findings-client.js.map +1 -1
  149. package/dist/findings-import.d.ts +44 -0
  150. package/dist/findings-import.d.ts.map +1 -0
  151. package/dist/findings-import.js +302 -0
  152. package/dist/findings-import.js.map +1 -0
  153. package/dist/github.d.ts +625 -7
  154. package/dist/github.d.ts.map +1 -1
  155. package/dist/github.js.map +1 -1
  156. package/dist/import-scan.d.ts +27 -0
  157. package/dist/import-scan.d.ts.map +1 -0
  158. package/dist/import-scan.js +236 -0
  159. package/dist/import-scan.js.map +1 -0
  160. package/dist/index.d.ts +7 -0
  161. package/dist/index.d.ts.map +1 -1
  162. package/dist/index.js +2 -0
  163. package/dist/index.js.map +1 -1
  164. package/dist/knowledge-base.d.ts +1 -1
  165. package/dist/knowledge-base.d.ts.map +1 -1
  166. package/dist/knowledge-base.js +19 -8
  167. package/dist/knowledge-base.js.map +1 -1
  168. package/dist/models.d.ts.map +1 -1
  169. package/dist/models.js.map +1 -1
  170. package/dist/multiscan.d.ts +7 -5
  171. package/dist/multiscan.d.ts.map +1 -1
  172. package/dist/multiscan.js +212 -55
  173. package/dist/multiscan.js.map +1 -1
  174. package/dist/patch-tui.d.ts.map +1 -1
  175. package/dist/patch-tui.js.map +1 -1
  176. package/dist/project-config-schema.d.ts +191 -0
  177. package/dist/project-config-schema.d.ts.map +1 -0
  178. package/dist/project-config-schema.js +85 -0
  179. package/dist/project-config-schema.js.map +1 -0
  180. package/dist/project-config.d.ts +50 -0
  181. package/dist/project-config.d.ts.map +1 -0
  182. package/dist/project-config.js +220 -0
  183. package/dist/project-config.js.map +1 -0
  184. package/dist/prompt-files.d.ts +13 -0
  185. package/dist/prompt-files.d.ts.map +1 -0
  186. package/dist/prompt-files.js +74 -0
  187. package/dist/prompt-files.js.map +1 -0
  188. package/dist/publication-events.d.ts.map +1 -1
  189. package/dist/publication-events.js +7 -2
  190. package/dist/publication-events.js.map +1 -1
  191. package/dist/publish.d.ts.map +1 -1
  192. package/dist/publish.js +1 -1
  193. package/dist/publish.js.map +1 -1
  194. package/dist/result.d.ts +2 -1
  195. package/dist/result.d.ts.map +1 -1
  196. package/dist/result.js +5 -0
  197. package/dist/result.js.map +1 -1
  198. package/dist/runtime.d.ts +5 -1
  199. package/dist/runtime.d.ts.map +1 -1
  200. package/dist/runtime.js +12 -6
  201. package/dist/runtime.js.map +1 -1
  202. package/dist/scan-comparison.d.ts.map +1 -1
  203. package/dist/scan-comparison.js.map +1 -1
  204. package/dist/scan-dashboard.d.ts +1 -0
  205. package/dist/scan-dashboard.d.ts.map +1 -1
  206. package/dist/scan-dashboard.js +45 -20
  207. package/dist/scan-dashboard.js.map +1 -1
  208. package/dist/scan-history-renderer.d.ts.map +1 -1
  209. package/dist/scan-history-renderer.js.map +1 -1
  210. package/dist/scan-logs.d.ts +39 -3
  211. package/dist/scan-logs.d.ts.map +1 -1
  212. package/dist/scan-logs.js +77 -15
  213. package/dist/scan-logs.js.map +1 -1
  214. package/dist/scan-modes.d.ts +3 -0
  215. package/dist/scan-modes.d.ts.map +1 -0
  216. package/dist/scan-modes.js +2 -0
  217. package/dist/scan-modes.js.map +1 -0
  218. package/dist/scan-settings.d.ts +81 -0
  219. package/dist/scan-settings.d.ts.map +1 -0
  220. package/dist/scan-settings.js +123 -0
  221. package/dist/scan-settings.js.map +1 -0
  222. package/dist/security-policy-cli.d.ts +39 -0
  223. package/dist/security-policy-cli.d.ts.map +1 -0
  224. package/dist/security-policy-cli.js +193 -0
  225. package/dist/security-policy-cli.js.map +1 -0
  226. package/dist/security-policy.d.ts +80 -0
  227. package/dist/security-policy.d.ts.map +1 -0
  228. package/dist/security-policy.js +672 -0
  229. package/dist/security-policy.js.map +1 -0
  230. package/dist/server/dashboard/THIRD_PARTY_NOTICES.txt +2 -2
  231. package/dist/server/dashboard/app.js +2 -2
  232. package/dist/server/dashboard.js.map +1 -1
  233. package/dist/server/embeddings.d.ts.map +1 -1
  234. package/dist/server/embeddings.js.map +1 -1
  235. package/dist/server/errors.d.ts.map +1 -1
  236. package/dist/server/errors.js.map +1 -1
  237. package/dist/server/findings-service.d.ts.map +1 -1
  238. package/dist/server/findings-service.js.map +1 -1
  239. package/dist/server/serve.js.map +1 -1
  240. package/dist/server/sqlite-store.d.ts.map +1 -1
  241. package/dist/server/sqlite-store.js.map +1 -1
  242. package/dist/severity-store.js.map +1 -1
  243. package/dist/targets.d.ts +10 -2
  244. package/dist/targets.d.ts.map +1 -1
  245. package/dist/targets.js +243 -14
  246. package/dist/targets.js.map +1 -1
  247. package/dist/thread-source.d.ts.map +1 -1
  248. package/dist/version.js.map +1 -1
  249. package/dist/worker-progress.d.ts.map +1 -1
  250. package/dist/worker-progress.js.map +1 -1
  251. package/package.json +36 -29
  252. package/schemas/project-config.schema.json +211 -0
  253. package/_bundled_plugin/scripts/resolve_security_md.py +0 -158
package/dist/api.js CHANGED
@@ -5,28 +5,33 @@ import { randomUUID } from "node:crypto";
5
5
  import { homedir, tmpdir } from "node:os";
6
6
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep, } from "node:path";
7
7
  import { Codex, } from "@openai/codex-sdk";
8
- import { parse as parseToml, stringify as stringifyToml, } from "smol-toml";
9
8
  import { z } from "incur";
10
- import { accountStatus, configuredCodexHome, CodexLoginHandle, loginApiKey as persistApiKey, logout as codexLogout, } from "./auth.js";
9
+ import { CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, accountStatus, configuredCodexHome, CodexLoginHandle, loginApiKey as persistApiKey, logout as codexLogout, } from "./auth.js";
11
10
  import { jsonForPrompt, pluginPythonCommand, shellEnvironmentReference, } from "./codex-prompt.js";
12
- import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, hasCommandAuth, mergedCodexConfig, modelProviderConfigOverride, resolveCommandAuthConfig, scanApprovalPolicy, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
11
+ import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, inlineToml, isExternalModelProvider, hasCommandAuth, mergedCodexConfig, resolveCodexProfile, modelProviderConfigOverride, resolveCommandAuthConfig, scanApprovalPolicy, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
13
12
  import { estimateScanCost, ScanCostTracker, } from "./cost.js";
14
13
  import { DeepScanProgressTracker, } from "./deep-progress.js";
14
+ import { findScanSession } from "./scan-logs.js";
15
+ import { deepScanOptions, resolveDeepScanConfig, writeDeepScanConfig, } from "./deep-config.js";
16
+ import { DEFAULT_SCAN_AUTH, DEFAULT_SCAN_MODE, SCAN_AUTH_MODES, ScanSettingsSchema, } from "./scan-settings.js";
17
+ import { resolveScanPrompts } from "./prompt-files.js";
18
+ export { SCAN_AUTH_MODES } from "./scan-settings.js";
15
19
  import { loadContract, readScanFile, requireScanFile, } from "./contract.js";
16
20
  import { runCustomValidation, writeCustomValidationStatus, } from "./custom-validation.js";
17
21
  import { customDiscoveryPrompt, customValidationConfig, } from "./custom-validation-prompt.js";
18
- import { AuthenticationRequiredError, CodexSecurityError, ConfigurationError, IncompleteScanError, OutputDirectoryError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
22
+ import { AuthenticationRequiredError, CodexSecurityError, ConfigurationError, IncompleteScanError, OutputDirectoryError, OutputDirectoryNotEmptyError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
19
23
  import { prepareKnowledgeBase, } from "./knowledge-base.js";
20
24
  import { FindingWorkflow, workflowDigest } from "./finding-workflow.js";
21
25
  import { ScanResult, } from "./result.js";
26
+ import { formatSecurityPolicyText, inspectSecurityPolicySources, readSecurityPolicySnapshot, requireUnchangedSecurityPolicy, resolveSecurityPolicyGuidance, resolveSecurityPolicyTarget, runSecurityPolicyStages, parseSecurityPolicyStageResult, securityPolicyDiff, securityPolicyProtectedRoots, requireSecurityPolicyRepositoryBinding, securityPolicyStageOutputSchema, } from "./security-policy.js";
22
27
  import { writeMockScanDraft } from "./mock-scan.js";
23
28
  import { scanActivitiesFromEvent } from "./scan-activity.js";
24
29
  import { matchCompletedScan, matchScanFindingsInternal, } from "./scan-comparison.js";
25
30
  import { scanProgressUpdatesFromEvent, workerStatusFromEvent, } from "./worker-progress.js";
26
31
  import { CODEX_SECURITY_THREAD_SOURCES } from "./thread-source.js";
27
32
  import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";
28
- import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, bundledPluginRoot, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, executablePathForSpawn, expandHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, pluginMetadata, planOutputArchive, prepareScanArtifactRestorer, prepareOutputDir, preparePersistentOutputRoot, requireModelSafeOutputDir, requireOutputOutsideRepository, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
29
- import { enclosingGitWorktreeRoot, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateCommittedDiffCheckout, validateMode, } from "./targets.js";
33
+ import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, bundledPluginRoot, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, executablePathForSpawn, expandHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, pluginMetadata, planOutputArchive, prepareScanArtifactRestorer, prepareOutputDir, preparePersistentOutputRoot, requireModelSafeOutputDir, requireOutputOutsideRepositories, requireOutputOutsideRepository, requirePrivatePolicyOutputDirectory, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
34
+ import { enclosingGitWorktreeRoot, enclosingGitWorktreeRoots, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateCommittedDiffCheckout, validateMode, } from "./targets.js";
30
35
  const DEEP_SCAN_CONFIG_PATH_ENVIRONMENT = "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH";
31
36
  const VALIDATION_DISPOSITIONS = [
32
37
  "reportable",
@@ -40,22 +45,15 @@ const validationResponseSchema = z
40
45
  report: z.string().trim().min(1),
41
46
  })
42
47
  .strict();
43
- export const SCAN_AUTH_MODES = ["auto", "chatgpt", "api-key"];
44
48
  const DEFAULT_DEPENDENCIES = {
45
49
  createCodex: (options) => new Codex(options),
46
50
  environment: process.env,
47
51
  };
48
52
  const SCAN_PERMISSION_PROFILE = "codex_security_scan";
53
+ const POLICY_PERMISSION_PROFILE = "codex_security_policy";
49
54
  const SAFETY_IDENTIFIER_ENV = "CODEX_SAFETY_IDENTIFIER";
50
55
  const PERSONAL_TRUSTED_ACCESS_URL = "https://chatgpt.com/cyber";
51
56
  const ORGANIZATIONAL_TRUSTED_ACCESS_URL = "https://openai.com/form/enterprise-trusted-access-for-cyber/";
52
- const DEEP_SCAN_SETTINGS = [
53
- ["workers", "workers", 1],
54
- ["subagents", "subagents", 0],
55
- ["stopAfterNoNew", "stop_after_no_new", 1],
56
- ["maxDiscoveryRuns", "max_discovery_runs", 1],
57
- ["maxTimeHours", "max_time_hours", 0],
58
- ];
59
57
  export class CodexSecurity {
60
58
  config;
61
59
  metadata = {
@@ -90,7 +88,7 @@ export class CodexSecurity {
90
88
  this.#abortController.signal,
91
89
  ...(options.signal ? [options.signal] : []),
92
90
  ]);
93
- const local = await this.#validateLocalInputs(repository, { ...options, outputDir: undefined, archiveExisting: false }, signal);
91
+ const local = await this.#prepareLocalInputs(repository, { ...options, outputDir: undefined, archiveExisting: false }, signal);
94
92
  const workflow = new FindingWorkflow(workflowId, this.#dependencies.environment, this.#dependencies.runWorkbench, this.config.pythonPath);
95
93
  if (options.outputDir !== undefined)
96
94
  await workflow.protectArtifacts(options.outputDir);
@@ -100,8 +98,9 @@ export class CodexSecurity {
100
98
  config: this.config,
101
99
  options: {
102
100
  ...options,
101
+ ...local.prompts,
103
102
  target: options.target ?? "repository",
104
- mode: options.mode ?? "standard",
103
+ mode: options.mode ?? DEFAULT_SCAN_MODE,
105
104
  outputDir: options.outputDir === undefined
106
105
  ? undefined
107
106
  : resolve(expandHome(options.outputDir)),
@@ -145,7 +144,7 @@ export class CodexSecurity {
145
144
  }
146
145
  await workflow.begin("scan");
147
146
  try {
148
- const result = await this.#run(repository, options);
147
+ const result = await this.#run(repository, options, local);
149
148
  await workflow.protectArtifacts(result.scanDir);
150
149
  await workflow.bind({
151
150
  scanId: result.manifest.scan.id,
@@ -186,7 +185,7 @@ export class CodexSecurity {
186
185
  throw new CodexSecurityError("A finding must be nonempty text or a JSON object.");
187
186
  }
188
187
  const finding = jsonForPrompt(options.finding);
189
- const inputs = await this.#validateLocalInputs(options.repositoryPath, options, signal);
188
+ const inputs = await this.#prepareLocalInputs(options.repositoryPath, options, signal);
190
189
  const temporaryRoot = await realpath(tmpdir());
191
190
  requireOutputOutsideRepository(inputs.protectedRoot, temporaryRoot, "temporary");
192
191
  const session = await this.#prepareSession(inputs, options, signal, temporaryRoot);
@@ -253,11 +252,11 @@ export class CodexSecurity {
253
252
  }
254
253
  async preflight(repository, options = {}) {
255
254
  this.#requireOpen();
256
- const inputs = await this.#validateLocalInputs(repository, options, options.signal);
255
+ const inputs = await this.#prepareLocalInputs(repository, options, options.signal);
257
256
  return await this.#preflightInputs(inputs, options);
258
257
  }
259
258
  async #preflightInputs(inputs, options) {
260
- requireOutputOutsideRepository(inputs.protectedRoot, await realpath(tmpdir()), "temporary");
259
+ requireOutputOutsideRepositories(inputs.protectedRoots, await realpath(tmpdir()), "temporary");
261
260
  if (options.knowledgeBasePaths?.length) {
262
261
  const knowledgeBase = await prepareKnowledgeBase(options.knowledgeBasePaths, options.signal);
263
262
  await knowledgeBase.cleanup();
@@ -274,7 +273,10 @@ export class CodexSecurity {
274
273
  repository: inputs.repository,
275
274
  target: inputs.target,
276
275
  mode: inputs.mode,
277
- ...deepScanOptions(options),
276
+ ...inputs.deepScanConfiguration?.settings,
277
+ ...(inputs.deepScanConfiguration === undefined
278
+ ? {}
279
+ : { deepScanSources: inputs.deepScanConfiguration.sources }),
278
280
  ...(options.knowledgeBasePaths?.length
279
281
  ? { knowledgeBasePaths: options.knowledgeBasePaths }
280
282
  : {}),
@@ -288,7 +290,242 @@ export class CodexSecurity {
288
290
  : { maxCostUsd: options.maxCostUsd }),
289
291
  };
290
292
  }
291
- async #run(repository, options) {
293
+ async preflightPolicy(repository, options = {}) {
294
+ this.#requireOpen();
295
+ const target = await resolveSecurityPolicyTarget(repository, options.path, options.signal);
296
+ const inputs = await this.#validatePolicyInputs(target, options, options.signal).catch(rethrowPolicyOutputError);
297
+ await readSecurityPolicySnapshot(target, options.signal, inputs.gitMetadataPaths);
298
+ const preflight = await this.#preflightInputs(inputs, options);
299
+ return {
300
+ ...target,
301
+ outputDir: preflight.outputDir,
302
+ authentication: preflight.authentication,
303
+ model: preflight.model,
304
+ reasoningEffort: preflight.reasoningEffort,
305
+ ...(options.maxCostUsd === undefined
306
+ ? {}
307
+ : { maxCostUsd: options.maxCostUsd }),
308
+ };
309
+ }
310
+ async generatePolicy(repository, options = {}) {
311
+ return await this.#trackOperation(() => this.#generatePolicy(repository, options)).catch(rethrowPolicyOutputError);
312
+ }
313
+ async previewPolicy(draft, options = {}) {
314
+ return await this.#trackOperation(async () => {
315
+ const signal = AbortSignal.any([
316
+ this.#abortController.signal,
317
+ ...(options.signal === undefined ? [] : [options.signal]),
318
+ ]);
319
+ return formatSecurityPolicyText(await securityPolicyDiff(draft, async () => await (this.#dependencies.resolvePluginPython ?? resolvePluginPython)({
320
+ configuredPath: this.config.pythonPath,
321
+ environment: this.#dependencies.environment,
322
+ protectedRoot: (await enclosingGitWorktreeRoots(draft.repository, signal)).at(-1) ?? draft.repository,
323
+ signal,
324
+ }), signal), true);
325
+ });
326
+ }
327
+ async #generatePolicy(repository, options) {
328
+ const budgetController = new AbortController();
329
+ const signal = AbortSignal.any([
330
+ this.#abortController.signal,
331
+ budgetController.signal,
332
+ ...(options.signal === undefined ? [] : [options.signal]),
333
+ ]);
334
+ let outputDir = "";
335
+ let knowledgeBase = null;
336
+ let accumulatedCost = null;
337
+ let completeCost = true;
338
+ const warn = (message) => notifyObserver("onWarning", options.onWarning, options.onObserverError, message);
339
+ try {
340
+ const target = await resolveSecurityPolicyTarget(repository, options.path, signal);
341
+ const inputs = await this.#validatePolicyInputs(target, options, signal);
342
+ const snapshot = await readSecurityPolicySnapshot(target, signal, inputs.gitMetadataPaths);
343
+ const temporaryRoot = await realpath(tmpdir());
344
+ requireOutputOutsideRepositories(inputs.protectedRoots, temporaryRoot, "temporary");
345
+ const session = await this.#prepareSession(inputs, options, signal, temporaryRoot);
346
+ const { runtime, effectiveConfig } = session;
347
+ const model = scanModelConfiguration(effectiveConfig);
348
+ validateScanCostLimit(options.maxCostUsd, model.model);
349
+ for (const path of [
350
+ "references/threat-model.md",
351
+ "references/security-guidance.md",
352
+ "skills/define-security-policy/SKILL.md",
353
+ "mcp/helpers.mjs",
354
+ ]) {
355
+ const metadata = await lstat(join(runtime.plugin.pluginRoot, path)).catch(() => null);
356
+ if (metadata === null ||
357
+ !metadata.isFile() ||
358
+ metadata.isSymbolicLink()) {
359
+ throw new CodexSecurityError(`Installed plugin is missing policy-generation support: ${path}`);
360
+ }
361
+ }
362
+ const root = inputs.outputDir === null &&
363
+ this.#dependencies.prepareOutputDir === undefined
364
+ ? await preparePersistentOutputRoot(inputs.stateDirectory, "policies", basename(target.repository))
365
+ : temporaryRoot;
366
+ outputDir = await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(inputs.outputDir ?? undefined, `${basename(target.repository)}-policy`, root, (path) => requireOutputOutsideRepositories(inputs.protectedRoots, path));
367
+ requireOutputOutsideRepositories(inputs.protectedRoots, outputDir);
368
+ requireModelSafeOutputDir(outputDir);
369
+ await (this.#dependencies.requirePrivatePolicyOutputDirectory ??
370
+ requirePrivatePolicyOutputDirectory)(outputDir);
371
+ if (options.knowledgeBasePaths?.length) {
372
+ knowledgeBase = await prepareKnowledgeBase(options.knowledgeBasePaths, signal, outputDir);
373
+ }
374
+ notifyObserver("onOutputDirReady", options.onOutputDirReady, options.onObserverError, outputDir);
375
+ const guidance = await resolveSecurityPolicyGuidance(target, runtime.plugin.pluginRoot, session.scanEnvironment, signal, inputs.policyPaths, inputs.gitMetadataPaths);
376
+ await requireUnchangedSecurityPolicy(target, snapshot, signal, inputs.gitMetadataPaths);
377
+ await requireSecurityPolicyRepositoryBinding(target, signal);
378
+ const policyReadRoots = [
379
+ dirname(target.targetPath),
380
+ runtime.plugin.pluginRoot,
381
+ ...(knowledgeBase === null ? [] : [knowledgeBase.path]),
382
+ ].filter((path, index, roots) => roots.indexOf(path) === index);
383
+ const { codex } = this.#createSessionCodex(session, {
384
+ CODEX_SECURITY_REPOSITORY: target.repository,
385
+ CODEX_SECURITY_PLUGIN_ROOT: runtime.plugin.pluginRoot,
386
+ CODEX_SECURITY_STATE_DIR: inputs.stateDirectory,
387
+ CODEX_SECURITY_SURFACE: this.#surface,
388
+ ...(knowledgeBase === null
389
+ ? {}
390
+ : { CODEX_SECURITY_KNOWLEDGE_BASE: knowledgeBase.path }),
391
+ }, options.auth, policyCodexConfig(session.sessionConfig), inputs.gitMetadataPaths.length === 0
392
+ ? []
393
+ : [
394
+ // CLI override keys split on dots, so keep paths inside the TOML value.
395
+ `permissions.${POLICY_PERMISSION_PROFILE}.filesystem=${inlineToml(policyFilesystemPermissions(inputs.gitMetadataPaths))}`,
396
+ ]);
397
+ const reportCost = (current) => {
398
+ const total = addScanCosts(accumulatedCost, current);
399
+ if (completeCost)
400
+ notifyObserver("onCost", options.onCost, options.onObserverError, total);
401
+ if (options.maxCostUsd !== undefined &&
402
+ total.estimatedUsd > options.maxCostUsd) {
403
+ budgetController.abort(new CodexSecurityError(`Security-policy generation exceeded its $${options.maxCostUsd} cost limit; partial output remains at ${outputDir}.`));
404
+ }
405
+ };
406
+ const outputSchema = securityPolicyStageOutputSchema();
407
+ const run = async (stage, prompt) => {
408
+ const thread = codex.startThread({
409
+ workingDirectory: outputDir,
410
+ additionalDirectories: policyReadRoots,
411
+ skipGitRepoCheck: true,
412
+ approvalPolicy: "never",
413
+ networkAccessEnabled: false,
414
+ webSearchMode: "disabled",
415
+ });
416
+ const tracker = new ScanCostTracker({
417
+ codexHome: runtime.codexHome,
418
+ model: model.model,
419
+ repository: target.repository,
420
+ scanDirectory: outputDir,
421
+ maxCostUsd: options.maxCostUsd,
422
+ onCost: options.onCost === undefined && options.maxCostUsd === undefined
423
+ ? undefined
424
+ : reportCost,
425
+ onError: (error) => {
426
+ if (options.maxCostUsd !== undefined)
427
+ budgetController.abort(error);
428
+ else
429
+ warn(`Could not track policy-generation cost: ${safeErrorMessage(error)}`);
430
+ },
431
+ });
432
+ let stopped = false;
433
+ let usage = null;
434
+ try {
435
+ const { events } = await thread.runStreamed(prompt, {
436
+ signal,
437
+ outputSchema,
438
+ });
439
+ const turn = await readCodexTurn({
440
+ thread,
441
+ events,
442
+ onEvent: (event) => {
443
+ if (event.type === "thread.started" &&
444
+ typeof event["thread_id"] === "string") {
445
+ tracker.start(event["thread_id"]);
446
+ }
447
+ },
448
+ onReconnect: (message) => warn(safeErrorMessage(message)),
449
+ });
450
+ usage = turn.usage;
451
+ signal.throwIfAborted();
452
+ if (turn.status !== "completed")
453
+ throw new CodexSecurityError(turn.lastStreamError ??
454
+ `Security-policy ${stage} stage ended before the turn completed.`);
455
+ const snapshot = await tracker.stop(usage).catch((error) => {
456
+ if (options.maxCostUsd !== undefined)
457
+ throw error;
458
+ warn(`Could not track policy-generation cost: ${safeErrorMessage(error)}`);
459
+ const cost = estimateScanCost(model.model, usage);
460
+ if (cost !== null)
461
+ reportCost(cost);
462
+ return { usage, cost };
463
+ });
464
+ stopped = true;
465
+ if (snapshot.cost === null) {
466
+ completeCost = false;
467
+ if (options.maxCostUsd !== undefined)
468
+ throw new CodexSecurityError("Could not verify the requested policy-generation cost limit.");
469
+ }
470
+ else {
471
+ accumulatedCost = addScanCosts(accumulatedCost, snapshot.cost);
472
+ }
473
+ signal.throwIfAborted();
474
+ try {
475
+ return parseSecurityPolicyStageResult(JSON.parse(turn.finalResponse));
476
+ }
477
+ catch (error) {
478
+ throw new CodexSecurityError(`Security-policy ${stage} stage returned an invalid document response.`, { cause: error });
479
+ }
480
+ }
481
+ finally {
482
+ if (!stopped)
483
+ await tracker
484
+ .stop(usage)
485
+ .catch((error) => warn(safeErrorMessage(error)));
486
+ }
487
+ };
488
+ return await runSecurityPolicyStages({
489
+ target,
490
+ snapshot,
491
+ policyPaths: inputs.policyPaths,
492
+ gitMetadataPaths: inputs.gitMetadataPaths,
493
+ outputDir,
494
+ guidance,
495
+ pluginRoot: runtime.plugin.pluginRoot,
496
+ ...(this.config.pluginPath === undefined
497
+ ? {}
498
+ : { pluginPath: resolve(expandHome(this.config.pluginPath)) }),
499
+ ...(knowledgeBase === null
500
+ ? {}
501
+ : { knowledgeBasePath: knowledgeBase.path }),
502
+ revision: await (this.#dependencies.repositoryRevision ?? repositoryRevision)(target.repository, signal),
503
+ ...model,
504
+ pluginVersion: runtime.plugin.version,
505
+ signal,
506
+ onStage: (stage) => notifyObserver("onStage", options.onStage, options.onObserverError, stage),
507
+ answerQuestions: options.answerQuestions,
508
+ run,
509
+ cost: () => (completeCost ? accumulatedCost : null),
510
+ });
511
+ }
512
+ catch (error) {
513
+ if (budgetController.signal.aborted)
514
+ throw budgetController.signal.reason;
515
+ if (signal.aborted)
516
+ throw new CodexSecurityError(`Security-policy generation was interrupted${outputDir ? `; partial output remains at ${outputDir}` : ""}.`, { cause: error });
517
+ throw error;
518
+ }
519
+ finally {
520
+ try {
521
+ await knowledgeBase?.cleanup();
522
+ }
523
+ catch (error) {
524
+ warnCleanupFailed(options, error, "policy generation");
525
+ }
526
+ }
527
+ }
528
+ async #run(repository, options, preparedInputs) {
292
529
  this.#requireOpen();
293
530
  if (options.mock)
294
531
  return await this.#runMock(repository, options);
@@ -328,8 +565,16 @@ export class CodexSecurity {
328
565
  this.#requireOpen();
329
566
  throwIfAborted(signal, scanDir);
330
567
  };
331
- // Validate all local inputs before runtime initialization or plugin-Python discovery.
332
- const { repository: repo, target: normalized, mode, outputDir: requestedOutput, protectedRoot, stateDirectory, } = await this.#validateLocalInputs(repository, options, signal);
568
+ // Workflows reuse the prepared prompts and deep settings, but validate the
569
+ // output only when starting new work; a completed workflow may already own it.
570
+ const inputs = preparedInputs === undefined
571
+ ? await this.#prepareLocalInputs(repository, options, signal)
572
+ : {
573
+ ...preparedInputs,
574
+ outputDir: await prepareScanOutputDir(options, preparedInputs.protectedRoots),
575
+ };
576
+ const { repository: repo, target: normalized, mode, outputDir: requestedOutput, protectedRoot, stateDirectory, deepScanConfiguration, prompts, } = inputs;
577
+ options = { ...options, ...prompts };
333
578
  checkOpen();
334
579
  let temporaryRoot;
335
580
  if (requestedOutput === null ||
@@ -346,11 +591,12 @@ export class CodexSecurity {
346
591
  const { runtime, runtimeHome, effectiveConfig, preflightConfig, modelProvider, authentication, approvalPolicy, python, } = session;
347
592
  releaseCredentialHome = session.releaseCredentialHome;
348
593
  const deepScanConfigPath = mode === "deep"
349
- ? runtime.deepScanConfigPath ??
350
- join(runtimeHome, "codex-security", "config.toml")
594
+ ? (runtime.deepScanConfigPath ??
595
+ join(runtimeHome, "codex-security", "config.toml"))
351
596
  : undefined;
352
- if (deepScanConfigPath !== undefined) {
353
- await prepareDeepScanConfig(deepScanConfigPath, this.#dependencies.environment, options, signal);
597
+ if (deepScanConfigPath !== undefined &&
598
+ deepScanConfiguration !== undefined) {
599
+ await writeDeepScanConfig(deepScanConfigPath, deepScanConfiguration);
354
600
  }
355
601
  checkOpen();
356
602
  const scanOutputRoot = requestedOutput === null &&
@@ -360,10 +606,13 @@ export class CodexSecurity {
360
606
  if (scanOutputRoot !== undefined) {
361
607
  requireOutputOutsideRepository(protectedRoot, scanOutputRoot, scanOutputRoot === temporaryRoot ? "temporary" : "output");
362
608
  }
363
- scanDir = await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(requestedOutput ?? undefined, basename(repo), scanOutputRoot, (path) => requireOutputOutsideRepository(protectedRoot, path), options.archiveExisting, (archiveDir) => {
364
- archivedScanDir = archiveDir;
365
- notifyObserver("onOutputArchived", options.onOutputArchived, options.onObserverError, archiveDir);
366
- });
609
+ scanDir =
610
+ options.resumeScanId !== undefined
611
+ ? requestedOutput
612
+ : await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(requestedOutput ?? undefined, basename(repo), scanOutputRoot, (path) => requireOutputOutsideRepository(protectedRoot, path), options.archiveExisting, (archiveDir) => {
613
+ archivedScanDir = archiveDir;
614
+ notifyObserver("onOutputArchived", options.onOutputArchived, options.onObserverError, archiveDir);
615
+ });
367
616
  requireOutputOutsideRepository(protectedRoot, scanDir);
368
617
  requireModelSafeOutputDir(scanDir);
369
618
  notifyObserver("onOutputDirReady", options.onOutputDirReady, options.onObserverError, scanDir);
@@ -496,7 +745,25 @@ export class CodexSecurity {
496
745
  onError: reportTrackingError,
497
746
  });
498
747
  costTracker = tracker;
499
- const recipe = scanRecipe(repo, normalized, mode, expectation.repositoryRevision, runtime.plugin.version, { ...preflightConfig, approval_policy: approvalPolicy }, options.failureSeverity, knowledgeBase?.sources, options.maxCostUsd, deepScanOptions(options));
748
+ const recipe = scanRecipe({
749
+ repository: repo,
750
+ target: normalized,
751
+ mode,
752
+ repositoryRevision: expectation.repositoryRevision,
753
+ pluginVersion: runtime.plugin.version,
754
+ config: { ...preflightConfig, approval_policy: approvalPolicy },
755
+ failOnSeverity: options.failureSeverity,
756
+ knowledgeBasePaths: knowledgeBase?.sources,
757
+ maxCostUsd: options.maxCostUsd,
758
+ deepScan: deepScanConfiguration?.settings,
759
+ auth: options.auth,
760
+ });
761
+ if (options.scanPrompt?.trim())
762
+ recipe["requiresScanPrompt"] = true;
763
+ if (options.safetyIdentifier !== undefined)
764
+ recipe["safetyIdentifier"] = options.safetyIdentifier;
765
+ if (options.postScanPrompt !== undefined)
766
+ recipe["postScanPrompt"] = options.postScanPrompt;
500
767
  if (options.validationPrompt !== undefined)
501
768
  recipe["validationMode"] = "custom";
502
769
  const workbenchOptions = {
@@ -509,28 +776,59 @@ export class CodexSecurity {
509
776
  signal,
510
777
  failureMessage: "Could not save the Codex Security scan",
511
778
  };
512
- const registration = await workbench(workbenchOptions, [
513
- "register-cli-scan",
514
- "--repository",
515
- repo,
516
- "--scan-dir",
517
- scanDir,
518
- "--registration-json-stdin",
519
- ...(options.archiveExisting === true ? ["--archive-existing"] : []),
520
- ...(archivedScanDir === null
521
- ? []
522
- : ["--archived-scan-dir", archivedScanDir]),
523
- ...(options.parentScanId === undefined
524
- ? []
525
- : ["--parent-scan-id", options.parentScanId]),
526
- ], JSON.stringify({
527
- recipe,
528
- userContext: options.scanPrompt,
529
- ...(options.workflowId === undefined
530
- ? {}
531
- : { workflowId: options.workflowId }),
532
- }));
779
+ const registration = options.resumeScanId !== undefined
780
+ ? await workbench(workbenchOptions, [
781
+ "get-cli-scan-resume",
782
+ "--scan-id",
783
+ options.resumeScanId,
784
+ ])
785
+ : await workbench(workbenchOptions, [
786
+ "register-cli-scan",
787
+ "--repository",
788
+ repo,
789
+ "--scan-dir",
790
+ scanDir,
791
+ "--registration-json-stdin",
792
+ ...(options.archiveExisting === true
793
+ ? ["--archive-existing"]
794
+ : []),
795
+ ...(archivedScanDir === null
796
+ ? []
797
+ : ["--archived-scan-dir", archivedScanDir]),
798
+ ...(options.parentScanId === undefined
799
+ ? []
800
+ : ["--parent-scan-id", options.parentScanId]),
801
+ ], JSON.stringify({
802
+ recipe,
803
+ userContext: options.scanPrompt,
804
+ ...(options.workflowId === undefined
805
+ ? {}
806
+ : { workflowId: options.workflowId }),
807
+ }));
533
808
  const scanId = registration["scanId"];
809
+ const resumeThreadId = options.resumeScanId === undefined
810
+ ? undefined
811
+ : registration["threadId"];
812
+ if (options.resumeScanId !== undefined) {
813
+ const savedRecipe = registration["recipe"];
814
+ if (scanId !== options.resumeScanId ||
815
+ !isRecord(savedRecipe) ||
816
+ savedRecipe["repository"] !== repo ||
817
+ typeof resumeThreadId !== "string" ||
818
+ !resumeThreadId ||
819
+ JSON.stringify(savedRecipe["target"]) !==
820
+ JSON.stringify(recipe["target"])) {
821
+ throw new CodexSecurityError("The workbench returned mismatched scan resume context.");
822
+ }
823
+ const savedSession = await findScanSession(runtime.codexHome, resumeThreadId);
824
+ if (savedSession === null ||
825
+ savedSession.workingDirectory !== scanDir) {
826
+ throw new CodexSecurityError(`The original Codex session for scan ${scanId} is unavailable. Restore its session logs in the original Codex Security state directory before resuming.`);
827
+ }
828
+ if (typeof registration["sealedProducerVersion"] === "string") {
829
+ expectation.pluginVersion = registration["sealedProducerVersion"];
830
+ }
831
+ }
534
832
  const targetId = registration["targetId"];
535
833
  const contract = registration["contract"];
536
834
  const contractTarget = isRecord(contract)
@@ -606,7 +904,10 @@ export class CodexSecurity {
606
904
  await writeCustomValidationStatus(scanDir, { scanId, status: "pending" }, signal);
607
905
  }
608
906
  checkOpen();
609
- const basePrompt = scanPrompt(normalized, mode, skillName, scanId, runtime.configPath !== undefined, knowledgeBase !== null, options.scanPrompt, options.maxCostUsd !== undefined, discoveryPrompt);
907
+ const basePrompt = scanPrompt(normalized, mode, skillName, scanId, runtime.configPath !== undefined, knowledgeBase !== null, options.resumeScanId !== undefined &&
908
+ typeof registration["userContext"] === "string"
909
+ ? registration["userContext"]
910
+ : options.scanPrompt, options.maxCostUsd !== undefined, discoveryPrompt);
610
911
  checkOpen();
611
912
  const feedback = await workbench({
612
913
  ...workbenchOptions,
@@ -626,7 +927,12 @@ export class CodexSecurity {
626
927
  let prompt = scopeFileCount === null
627
928
  ? basePrompt
628
929
  : `${basePrompt}\nThe SDK's current in-scope file-count estimate is ${scopeFileCount}; use it for scan progress unless exact scoped-source enumeration establishes a different total before review begins.`;
629
- if (falsePositiveExamples.length > 0) {
930
+ if (options.resumeScanId !== undefined) {
931
+ prompt +=
932
+ "\nResume the existing Deep Scan through its coordinator. Preserve completed workers and saved artifacts; do not recreate the scan directory or restart completed analysis. If the coordinator already finished, continue with completion of this same scan.";
933
+ }
934
+ if (falsePositiveExamples.length > 0 &&
935
+ options.resumeScanId === undefined) {
630
936
  const feedbackPath = join(scanDir, "artifacts", "01_context", "false_positive_feedback.json");
631
937
  await mkdir(dirname(feedbackPath), { recursive: true, mode: 0o700 });
632
938
  await writeFile(feedbackPath, `${JSON.stringify(falsePositiveExamples)}\n`, { flag: "wx", mode: 0o600, signal });
@@ -643,7 +949,10 @@ export class CodexSecurity {
643
949
  : null;
644
950
  const runtimePaths = {
645
951
  PYTHON: python,
646
- CODEX_SECURITY_STARTED_AT: new Date().toISOString(),
952
+ CODEX_SECURITY_STARTED_AT: options.resumeScanId !== undefined &&
953
+ typeof registration["startedAt"] === "string"
954
+ ? registration["startedAt"]
955
+ : new Date().toISOString(),
647
956
  CODEX_SECURITY_REPOSITORY: repo,
648
957
  CODEX_SECURITY_SCAN_DIR: scanDir,
649
958
  CODEX_SECURITY_PLUGIN_ROOT: shellPluginRoot,
@@ -675,12 +984,27 @@ export class CodexSecurity {
675
984
  : { CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile }),
676
985
  };
677
986
  const { codex, environment } = this.#createSessionCodex(session, runtimePaths, options.auth);
678
- const thread = codex.startThread({
987
+ const threadOptions = {
679
988
  threadSource: CODEX_SECURITY_THREAD_SOURCES.scan,
680
989
  workingDirectory: scanDir,
681
990
  skipGitRepoCheck: true,
682
991
  approvalPolicy,
683
- });
992
+ };
993
+ let thread;
994
+ if (typeof resumeThreadId === "string") {
995
+ if (codex.resumeThread === undefined) {
996
+ throw new CodexSecurityError("The configured Codex client does not support resuming sessions.");
997
+ }
998
+ thread = codex.resumeThread(resumeThreadId, threadOptions);
999
+ tracker.start(resumeThreadId);
1000
+ if (budgetRecovery !== null)
1001
+ budgetRecovery.threadId = resumeThreadId;
1002
+ await tracker.refresh().catch(reportTrackingError);
1003
+ checkOpen();
1004
+ }
1005
+ else {
1006
+ thread = codex.startThread(threadOptions);
1007
+ }
684
1008
  const serializedPaths = normalized.kind === "paths" ? jsonForPrompt(normalized.paths) : null;
685
1009
  checkOpen();
686
1010
  if (serializedPaths !== null && targetPathsFile !== null) {
@@ -711,6 +1035,12 @@ export class CodexSecurity {
711
1035
  workbenchValidated: true,
712
1036
  model,
713
1037
  onThreadStarted: async (threadId) => {
1038
+ if (resumeThreadId !== undefined) {
1039
+ if (threadId !== resumeThreadId) {
1040
+ throw new CodexSecurityError("Codex did not resume the original scan session.");
1041
+ }
1042
+ return;
1043
+ }
714
1044
  if (budgetRecovery !== null)
715
1045
  budgetRecovery.threadId = threadId;
716
1046
  tracker.start(threadId);
@@ -1005,7 +1335,9 @@ export class CodexSecurity {
1005
1335
  }
1006
1336
  catch { }
1007
1337
  }
1008
- if (activeScan !== null) {
1338
+ // A failed attachment must not turn a resumable coordinator into a terminal failure.
1339
+ // Deep Scan orchestration persists its own terminal failures and cancellations.
1340
+ if (activeScan !== null && options.resumeScanId === undefined) {
1009
1341
  if (options.validationPrompt !== undefined &&
1010
1342
  !customValidationComplete) {
1011
1343
  await writeCustomValidationStatus(scanDir, {
@@ -1219,7 +1551,7 @@ export class CodexSecurity {
1219
1551
  }
1220
1552
  }
1221
1553
  }
1222
- #createSessionCodex(session, runtimePaths, auth = "auto") {
1554
+ #createSessionCodex(session, runtimePaths, auth = "auto", config, configOverrides = []) {
1223
1555
  const { runtime, python, modelProvider, externalProvider, apiKey, sessionConfig, } = session;
1224
1556
  const commandAuth = hasCommandAuth(sessionConfig);
1225
1557
  const environment = {
@@ -1239,7 +1571,7 @@ export class CodexSecurity {
1239
1571
  if (session.safetyIdentifier !== undefined) {
1240
1572
  environment[SAFETY_IDENTIFIER_ENV] = session.safetyIdentifier;
1241
1573
  }
1242
- const sdkCodexConfig = { ...sessionConfig };
1574
+ const sdkCodexConfig = { ...(config ?? sessionConfig) };
1243
1575
  // Projects and permissions already live in generated TOML files; the SDK
1244
1576
  // cannot safely encode their path and selector keys as dotted overrides.
1245
1577
  delete sdkCodexConfig["projects"];
@@ -1263,8 +1595,15 @@ export class CodexSecurity {
1263
1595
  ? {}
1264
1596
  : { codexPathOverride: executablePathForSpawn(codexPathOverride) }),
1265
1597
  ...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
1266
- ...(commandAuth
1267
- ? { configOverrides: modelProviderConfigOverride(sessionConfig) }
1598
+ ...(commandAuth || configOverrides.length > 0
1599
+ ? {
1600
+ configOverrides: [
1601
+ ...(commandAuth
1602
+ ? modelProviderConfigOverride(sessionConfig)
1603
+ : []),
1604
+ ...configOverrides,
1605
+ ],
1606
+ }
1268
1607
  : {}),
1269
1608
  env: sdkEnvironment,
1270
1609
  config: {
@@ -1277,7 +1616,7 @@ export class CodexSecurity {
1277
1616
  });
1278
1617
  return { codex, environment };
1279
1618
  }
1280
- async #prepareSession({ protectedRoot }, options, signal, temporaryRoot, keepCredentialLock = false) {
1619
+ async #prepareSession({ protectedRoot, protectedRoots = [protectedRoot], }, options, signal, temporaryRoot, keepCredentialLock = false) {
1281
1620
  let releaseCredentialHome = null;
1282
1621
  const checkOpen = () => {
1283
1622
  this.#requireOpen();
@@ -1301,11 +1640,11 @@ export class CodexSecurity {
1301
1640
  ? withoutOpenAiApiKeys(this.#dependencies.environment)
1302
1641
  : this.#dependencies.environment, options.auth, modelProvider);
1303
1642
  if (this.#dependencies.prepareRuntime === undefined) {
1304
- const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"));
1643
+ const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepositories(protectedRoots, path, "runtime"));
1305
1644
  releaseCredentialHome = await acquireCodexSecurityCredentialHomeLock(credentialHome, signal);
1306
1645
  }
1307
1646
  const previousRuntime = this.#runtime;
1308
- const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"), options.auth, requestedConfig);
1647
+ const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepositories(protectedRoots, path, "runtime"), options.auth, requestedConfig);
1309
1648
  if (runtime === previousRuntime &&
1310
1649
  this.#dependencies.prepareRuntime === undefined) {
1311
1650
  await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal, requestedConfig);
@@ -1317,7 +1656,7 @@ export class CodexSecurity {
1317
1656
  await writeCodexConfig(runtime.configPath, preflightConfig);
1318
1657
  }
1319
1658
  const runtimeHome = await realpath(runtime.codexHome);
1320
- requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");
1659
+ requireOutputOutsideRepositories(protectedRoots, runtimeHome, "runtime");
1321
1660
  const sessionConfig = scanRuntimeCodexConfig(effectiveConfig, runtimeHome);
1322
1661
  if (options.expectedPluginVersion !== undefined &&
1323
1662
  runtime.plugin.version !== options.expectedPluginVersion) {
@@ -1352,9 +1691,7 @@ export class CodexSecurity {
1352
1691
  apiKey === null &&
1353
1692
  !commandAuth &&
1354
1693
  authentication.method !== "aws_credentials") {
1355
- throw new AuthenticationRequiredError("No credentials were found. Run 'codex-security login', use " +
1356
- "'codex-security login --device-auth' on a remote or headless machine, or set " +
1357
- "OPENAI_API_KEY or CODEX_API_KEY for CI.");
1694
+ throw new AuthenticationRequiredError(NO_CREDENTIALS_MESSAGE);
1358
1695
  }
1359
1696
  if (!commandAuth)
1360
1697
  authentication = await runtimeScanAuthentication(this.#dependencies.environment, runtime.codexHome, options.auth, modelProvider);
@@ -1445,12 +1782,36 @@ export class CodexSecurity {
1445
1782
  : undefined;
1446
1783
  runtime.effectiveConfig = mergedConfig;
1447
1784
  }
1785
+ async #validatePolicyInputs(target, options, signal) {
1786
+ policyCodexConfig(await mergedCodexConfig(this.config));
1787
+ const sources = await inspectSecurityPolicySources(target, signal);
1788
+ const protectedRoots = [
1789
+ ...new Set([
1790
+ ...(await securityPolicyProtectedRoots(target, signal)),
1791
+ ...sources.gitMetadataPaths,
1792
+ ]),
1793
+ ];
1794
+ const inputs = await this.#prepareLocalInputs(target.repository, {
1795
+ auth: options.auth,
1796
+ target: target.scope === "." ? "repository" : [dirname(target.targetPath)],
1797
+ outputDir: options.outputDir,
1798
+ maxCostUsd: options.maxCostUsd,
1799
+ }, signal, protectedRoots);
1800
+ return {
1801
+ ...inputs,
1802
+ policyPaths: sources.policyPaths,
1803
+ gitMetadataPaths: [
1804
+ ...new Set([...protectedRoots.slice(1), ...sources.gitMetadataPaths]),
1805
+ ],
1806
+ };
1807
+ }
1448
1808
  async #runMock(repository, options) {
1449
1809
  const signal = AbortSignal.any([
1450
1810
  this.#abortController.signal,
1451
1811
  ...(options.signal ? [options.signal] : []),
1452
1812
  ]);
1453
- const local = await this.#validateLocalInputs(repository, options, signal);
1813
+ const local = await this.#prepareLocalInputs(repository, options, signal);
1814
+ options = { ...options, ...local.prompts };
1454
1815
  const temporaryRoot = await realpath(tmpdir());
1455
1816
  requireOutputOutsideRepository(local.protectedRoot, temporaryRoot, "temporary");
1456
1817
  const workspace = await mkdtemp(join(temporaryRoot, "codex-security-mock-"));
@@ -1515,7 +1876,18 @@ export class CodexSecurity {
1515
1876
  : ["--parent-scan-id", options.parentScanId]),
1516
1877
  ], JSON.stringify({
1517
1878
  recipe: {
1518
- ...scanRecipe(local.repository, local.target, local.mode, revision, plugin.version, { model }, options.failureSeverity, options.knowledgeBasePaths, options.maxCostUsd),
1879
+ ...scanRecipe({
1880
+ repository: local.repository,
1881
+ target: local.target,
1882
+ mode: local.mode,
1883
+ repositoryRevision: revision,
1884
+ pluginVersion: plugin.version,
1885
+ config: { model },
1886
+ failOnSeverity: options.failureSeverity,
1887
+ knowledgeBasePaths: options.knowledgeBasePaths,
1888
+ maxCostUsd: options.maxCostUsd,
1889
+ auth: options.auth,
1890
+ }),
1519
1891
  mock: true,
1520
1892
  },
1521
1893
  userContext: options.scanPrompt,
@@ -1597,14 +1969,25 @@ export class CodexSecurity {
1597
1969
  await cleanupSdkDirectory(workspace);
1598
1970
  }
1599
1971
  }
1600
- async #validateLocalInputs(repository, options, signal) {
1972
+ async #prepareLocalInputs(repository, options, signal, protectedRoots) {
1973
+ if (options.resumeScanId !== undefined &&
1974
+ (options.mode !== "deep" ||
1975
+ !options.outputDir ||
1976
+ options.archiveExisting ||
1977
+ options.parentScanId !== undefined ||
1978
+ options.workflowId !== undefined ||
1979
+ options.mock)) {
1980
+ throw new CodexSecurityError("Resume requires the original Deep Scan output directory without archive, rerun, or workflow options.");
1981
+ }
1601
1982
  if (options.mock &&
1602
1983
  (options.mode === "deep" ||
1603
1984
  options.validationPrompt !== undefined ||
1604
- options.postScanPrompt !== undefined)) {
1985
+ options.postScanPrompt !== undefined ||
1986
+ options.validationPromptFile !== undefined ||
1987
+ options.postScanPromptFile !== undefined)) {
1605
1988
  throw new CodexSecurityError("Mock scans support Standard mode without custom validation or post-scan prompts; those workflows require model calls.");
1606
1989
  }
1607
- deepScanOptions(options);
1990
+ const deep = deepScanOptions(options);
1608
1991
  const identifier = options.safetyIdentifier;
1609
1992
  if (identifier !== undefined &&
1610
1993
  (typeof identifier !== "string" ||
@@ -1614,7 +1997,7 @@ export class CodexSecurity {
1614
1997
  throw new ConfigurationError("safetyIdentifier must contain 1 to 64 characters, must not be blank, and must not contain NUL.");
1615
1998
  }
1616
1999
  if (options.maxCostUsd !== undefined &&
1617
- (!Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0)) {
2000
+ !ScanSettingsSchema.shape.maxCostUsd.safeParse(options.maxCostUsd).success) {
1618
2001
  throw new CodexSecurityError("The scan cost limit must be a positive USD amount.");
1619
2002
  }
1620
2003
  const repositoryPath = resolveRepositoryPath(repository);
@@ -1624,11 +2007,12 @@ export class CodexSecurity {
1624
2007
  validatedGitEnvironment(this.#dependencies.environment);
1625
2008
  const normalized = await normalizeTarget(repo, requestedTarget, signal);
1626
2009
  throwIfAborted(signal);
1627
- const mode = options.mode ?? "standard";
2010
+ const mode = options.mode ?? DEFAULT_SCAN_MODE;
1628
2011
  validateMode(normalized, mode);
1629
- if (options.validationPrompt !== undefined) {
1630
- if (typeof options.validationPrompt !== "string" ||
1631
- !options.validationPrompt.trim()) {
2012
+ const prompts = await resolveScanPrompts(options, repo);
2013
+ if (prompts.validationPrompt !== undefined) {
2014
+ if (typeof prompts.validationPrompt !== "string" ||
2015
+ !prompts.validationPrompt.trim()) {
1632
2016
  throw new CodexSecurityError("The validation prompt must not be empty.");
1633
2017
  }
1634
2018
  if (mode === "deep")
@@ -1636,11 +2020,11 @@ export class CodexSecurity {
1636
2020
  }
1637
2021
  await validateCommittedDiffCheckout(repo, normalized, signal);
1638
2022
  throwIfAborted(signal);
1639
- const protectedRoot = (await enclosingGitWorktreeRoot(repo, signal)) ?? repo;
1640
- const requestedOutput = await validateOutputDir(options.outputDir, options.archiveExisting);
1641
- if (requestedOutput !== null) {
1642
- requireOutputOutsideRepository(protectedRoot, requestedOutput);
1643
- }
2023
+ const protectedRoot = protectedRoots?.[0] ??
2024
+ (await enclosingGitWorktreeRoot(repo, signal)) ??
2025
+ repo;
2026
+ protectedRoots ??= [protectedRoot];
2027
+ const requestedOutput = await prepareScanOutputDir(options, protectedRoots);
1644
2028
  const stateDirectory = codexSecurityStateDirectory(this.#dependencies.environment);
1645
2029
  let canonicalStateDirectory = stateDirectory;
1646
2030
  while (true) {
@@ -1657,14 +2041,21 @@ export class CodexSecurity {
1657
2041
  canonicalStateDirectory = parent;
1658
2042
  }
1659
2043
  }
1660
- requireOutputOutsideRepository(protectedRoot, canonicalStateDirectory);
2044
+ requireOutputOutsideRepositories(protectedRoots, canonicalStateDirectory);
1661
2045
  return {
1662
2046
  repository: repo,
1663
2047
  target: normalized,
1664
2048
  mode,
1665
2049
  outputDir: requestedOutput,
1666
2050
  protectedRoot,
2051
+ protectedRoots,
1667
2052
  stateDirectory,
2053
+ prompts,
2054
+ ...(mode === "deep"
2055
+ ? {
2056
+ deepScanConfiguration: await resolveDeepScanConfig(deep, join(expandHome(environmentValue(this.#dependencies.environment, "CODEX_HOME") ?? join(homedir(), ".codex"), this.#dependencies.environment), "codex-security", "config.toml"), signal),
2057
+ }
2058
+ : {}),
1668
2059
  };
1669
2060
  }
1670
2061
  async #prepareRuntime(signal, temporaryRoot, validateLocation, auth = "auto", requestedConfig) {
@@ -1758,74 +2149,6 @@ export async function listRepositoryFindings(workbench, targetId, status = "open
1758
2149
  } while (offset !== undefined);
1759
2150
  return findings;
1760
2151
  }
1761
- function deepScanOptions(options) {
1762
- const selected = {};
1763
- for (const [name, , minimum] of DEEP_SCAN_SETTINGS) {
1764
- const value = options[name];
1765
- if (value === undefined)
1766
- continue;
1767
- if ((options.mode ?? "standard") !== "deep") {
1768
- throw new CodexSecurityError("Deep scan settings require deep mode.");
1769
- }
1770
- if (name === "maxTimeHours") {
1771
- if (!Number.isFinite(value) || value <= 0 || value > 96) {
1772
- throw new CodexSecurityError("Deep scan maxTimeHours must be a positive number no greater than 96.");
1773
- }
1774
- }
1775
- else if (!Number.isSafeInteger(value) || value < minimum) {
1776
- throw new CodexSecurityError(`Deep scan ${name} must be ${minimum === 0 ? "a non-negative" : "a positive"} integer.`);
1777
- }
1778
- selected[name] = value;
1779
- }
1780
- return selected;
1781
- }
1782
- async function prepareDeepScanConfig(destination, environment, options, signal) {
1783
- const ambientHome = expandHome(environmentValue(environment, "CODEX_HOME") ?? join(homedir(), ".codex"), environment);
1784
- const source = join(ambientHome, "codex-security", "config.toml");
1785
- let configured = {};
1786
- try {
1787
- configured = parseToml(await readFile(source, { encoding: "utf8", signal }));
1788
- }
1789
- catch (error) {
1790
- if (!isRecord(error) || error["code"] !== "ENOENT") {
1791
- throw new CodexSecurityError(`Cannot read Codex Security configuration at ${source}.`, { cause: error });
1792
- }
1793
- }
1794
- const existing = configured["deep_scan"];
1795
- if (existing !== undefined && !isRecord(existing)) {
1796
- throw new CodexSecurityError(`Codex Security configuration [deep_scan] at ${source} must be a TOML table.`);
1797
- }
1798
- const overrides = {};
1799
- for (const [name, key] of DEEP_SCAN_SETTINGS) {
1800
- const value = options[name];
1801
- if (value !== undefined)
1802
- overrides[key] = value;
1803
- }
1804
- const sharedConfig = await sameExistingPath(source, destination);
1805
- const hasOverrides = Object.keys(overrides).length > 0;
1806
- if (existing === undefined && !hasOverrides) {
1807
- if (!sharedConfig) {
1808
- await rm(destination, { force: true });
1809
- }
1810
- return;
1811
- }
1812
- if (sharedConfig && !hasOverrides)
1813
- return;
1814
- await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
1815
- await writeFile(destination, stringifyToml({
1816
- ...configured,
1817
- deep_scan: { ...existing, ...overrides },
1818
- }), { mode: 0o600, signal });
1819
- }
1820
- async function sameExistingPath(left, right) {
1821
- if (left === right)
1822
- return true;
1823
- const [canonicalLeft, canonicalRight] = await Promise.all([
1824
- realpath(left).catch(() => null),
1825
- realpath(right).catch(() => null),
1826
- ]);
1827
- return canonicalLeft !== null && canonicalLeft === canonicalRight;
1828
- }
1829
2152
  export function createSecurity(config = {}) {
1830
2153
  return createSecurityInternal(config, { surface: "sdk" });
1831
2154
  }
@@ -2095,7 +2418,7 @@ function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasK
2095
2418
  "This exhaustive scan authorizes the delegated-worker phases required by the selected skill; use available subagent tools and continue with parent-agent fallback if capacity changes.",
2096
2419
  ]),
2097
2420
  "This SDK host does not render MCP Apps; use the terminal/chat workflow.",
2098
- `Use ${python} as <python_command> for every plugin helper; replace any literal python or python3 helper invocation with this exact interpreter.`,
2421
+ `Use ${python} as <python_command> for plugin Python helper scripts (.py files); replace any literal python or python3 helper invocation with this exact interpreter.`,
2099
2422
  `Repository root: ${shellEnvironmentReference("CODEX_SECURITY_REPOSITORY")}`,
2100
2423
  `Use this exact scan directory for all scan output: ${shellEnvironmentReference("CODEX_SECURITY_SCAN_DIR")}`,
2101
2424
  `Use exactly ${JSON.stringify(scanId)} as the scan ID in the manifest, findings, and coverage.`,
@@ -2166,7 +2489,7 @@ function targetInstruction(target, python) {
2166
2489
  }
2167
2490
  return `Scan target: staged and unstaged working-tree changes against ${target.base}.`;
2168
2491
  }
2169
- function scanRecipe(repository, target, mode, repositoryRevision, pluginVersion, preflightConfig, failOnSeverity, knowledgeBasePaths, maxCostUsd, deepScan) {
2492
+ function scanRecipe({ repository, target, mode, repositoryRevision, pluginVersion, config, failOnSeverity, knowledgeBasePaths, maxCostUsd, deepScan, auth, }) {
2170
2493
  return {
2171
2494
  repository,
2172
2495
  target: {
@@ -2180,15 +2503,22 @@ function scanRecipe(repository, target, mode, repositoryRevision, pluginVersion,
2180
2503
  mode,
2181
2504
  ...(repositoryRevision === null ? {} : { repositoryRevision }),
2182
2505
  pluginVersion,
2183
- config: preflightConfig,
2506
+ config,
2507
+ ...(auth === undefined ? {} : { auth }),
2184
2508
  ...(failOnSeverity === undefined ? {} : { failOnSeverity }),
2185
2509
  ...(knowledgeBasePaths === undefined ? {} : { knowledgeBasePaths }),
2186
2510
  ...(maxCostUsd === undefined ? {} : { maxCostUsd }),
2187
- ...(deepScan === undefined || Object.keys(deepScan).length === 0
2511
+ ...(deepScan === undefined
2188
2512
  ? {}
2189
- : { deepScan: { ...deepScan } }),
2513
+ : { deepScan: { ...deepScan }, deepScanResolved: true }),
2190
2514
  };
2191
2515
  }
2516
+ async function prepareScanOutputDir(options, protectedRoots) {
2517
+ const output = await validateOutputDir(options.outputDir, options.resumeScanId !== undefined || options.archiveExisting);
2518
+ if (output !== null)
2519
+ requireOutputOutsideRepositories(protectedRoots, output);
2520
+ return output;
2521
+ }
2192
2522
  function validateScanCostLimit(maxCostUsd, model) {
2193
2523
  if (maxCostUsd === undefined)
2194
2524
  return;
@@ -2196,6 +2526,35 @@ function validateScanCostLimit(maxCostUsd, model) {
2196
2526
  throw new CodexSecurityError(`A scan cost limit is not available for the configured model: ${model}.`);
2197
2527
  }
2198
2528
  }
2529
+ function addScanCosts(previous, current) {
2530
+ if (previous === null)
2531
+ return { ...current };
2532
+ const { estimatedUsdRange: currentRange, ...currentCost } = current;
2533
+ const previousRange = previous.estimatedUsdRange;
2534
+ return {
2535
+ ...currentCost,
2536
+ inputTokens: previous.inputTokens + current.inputTokens,
2537
+ cachedInputTokens: previous.cachedInputTokens + current.cachedInputTokens,
2538
+ cacheWriteInputTokens: previous.cacheWriteInputTokens + current.cacheWriteInputTokens,
2539
+ outputTokens: previous.outputTokens + current.outputTokens,
2540
+ estimatedUsd: previous.estimatedUsd + current.estimatedUsd,
2541
+ ...(previous.cacheWriteInputTokensReported === false ||
2542
+ current.cacheWriteInputTokensReported === false
2543
+ ? { cacheWriteInputTokensReported: false }
2544
+ : {}),
2545
+ ...(previousRange === undefined || currentRange === undefined
2546
+ ? {}
2547
+ : {
2548
+ estimatedUsdRange: {
2549
+ context: "unknown",
2550
+ min: previousRange.min + currentRange.min,
2551
+ max: previousRange.max === null || currentRange.max === null
2552
+ ? null
2553
+ : previousRange.max + currentRange.max,
2554
+ },
2555
+ }),
2556
+ };
2557
+ }
2199
2558
  async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectation, signal, workbenchValidated = false) {
2200
2559
  const required = [
2201
2560
  "scan-manifest.json",
@@ -2241,7 +2600,7 @@ async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectat
2241
2600
  sarifPath,
2242
2601
  });
2243
2602
  }
2244
- export function scanAuthentication(environment, auth = "auto", modelProvider, commandAuth = false) {
2603
+ export function scanAuthentication(environment, auth = DEFAULT_SCAN_AUTH, modelProvider, commandAuth = false) {
2245
2604
  if (!SCAN_AUTH_MODES.includes(auth)) {
2246
2605
  throw new TypeError("Scan authentication mode must be auto, chatgpt, or api-key.");
2247
2606
  }
@@ -2290,7 +2649,8 @@ export function formatEnvironmentVariableRemovalGuidance(names) {
2290
2649
  }
2291
2650
  return `remove ${names.slice(0, -1).join(", ")}, and ${names[names.length - 1]} from the environment`;
2292
2651
  }
2293
- async function runtimeScanAuthentication(environment, codexHome, auth = "auto", modelProvider) {
2652
+ /** @internal */
2653
+ export async function runtimeScanAuthentication(environment, codexHome, auth = "auto", modelProvider) {
2294
2654
  const authentication = scanAuthentication(environment, auth, modelProvider);
2295
2655
  if (authentication.method !== "stored_credentials")
2296
2656
  return authentication;
@@ -2452,19 +2812,70 @@ export function scanRuntimeCodexConfig(config, protectedCredentialHome) {
2452
2812
  : { [protectedCredentialHome]: "read" }),
2453
2813
  },
2454
2814
  },
2815
+ [POLICY_PERMISSION_PROFILE]: {
2816
+ filesystem: policyFilesystemPermissions(),
2817
+ network: { enabled: false },
2818
+ },
2455
2819
  },
2456
2820
  };
2457
2821
  }
2822
+ function policyFilesystemPermissions(gitMetadataPaths = []) {
2823
+ return {
2824
+ ":minimal": "read",
2825
+ ":workspace_roots": "read",
2826
+ // A scoped "." keeps native permission paths literal, including glob characters.
2827
+ ...Object.fromEntries(gitMetadataPaths.map((path) => [path, { ".": "deny" }])),
2828
+ };
2829
+ }
2830
+ function rethrowPolicyOutputError(error) {
2831
+ if (error instanceof OutputDirectoryNotEmptyError)
2832
+ throw new OutputDirectoryNotEmptyError(error.directory, "policy");
2833
+ throw error;
2834
+ }
2835
+ function requirePolicyConfigKeys(config) {
2836
+ const tables = [config];
2837
+ if (isRecord(config["features"]))
2838
+ tables.push(config["features"]);
2839
+ // The Codex SDK flattens these keys without quoting their components.
2840
+ if (tables.some((table) => Object.keys(table).some((key) => !/^[A-Za-z0-9_-]+$/u.test(key))))
2841
+ throw new ConfigurationError("Policy generation does not accept dotted or quoted Codex override keys. Use nested objects instead.");
2842
+ }
2843
+ function policyCodexConfig(config) {
2844
+ const resolved = resolveCodexProfile(config);
2845
+ requirePolicyConfigKeys(resolved);
2846
+ // The selected provider is already written as TOML. The SDK cannot quote
2847
+ // provider names when it flattens this table into command-line overrides.
2848
+ delete resolved["model_providers"];
2849
+ const features = isRecord(resolved["features"]) ? resolved["features"] : {};
2850
+ return {
2851
+ ...resolved,
2852
+ approval_policy: "never",
2853
+ default_permissions: POLICY_PERMISSION_PROFILE,
2854
+ // The artifact directory may be inside an unrelated checkout.
2855
+ project_doc_max_bytes: 0,
2856
+ project_root_markers: [],
2857
+ allow_login_shell: false,
2858
+ shell_environment_policy: {
2859
+ inherit: "core",
2860
+ ignore_default_excludes: false,
2861
+ },
2862
+ features: {
2863
+ ...features,
2864
+ plugins: false,
2865
+ apps: false,
2866
+ shell_snapshot: false,
2867
+ },
2868
+ mcp_servers: {},
2869
+ web_search: "disabled",
2870
+ sandbox_workspace_write: { network_access: false },
2871
+ };
2872
+ }
2458
2873
  function sharedCredentialCodexConfig(config, credentialHome) {
2459
2874
  const shared = {
2460
2875
  approval_policy: scanApprovalPolicy(config),
2461
2876
  features: { plugins: true },
2462
2877
  };
2463
- for (const key of [
2464
- "cli_auth_credentials_store",
2465
- "forced_login_method",
2466
- "forced_chatgpt_workspace_id",
2467
- ]) {
2878
+ for (const key of CODEX_AUTH_CONFIG_KEYS) {
2468
2879
  if (Object.hasOwn(config, key))
2469
2880
  shared[key] = structuredClone(config[key]);
2470
2881
  }
@@ -2524,6 +2935,7 @@ export function scanPreflightCodexConfig(config) {
2524
2935
  for (const key of [
2525
2936
  "model",
2526
2937
  "model_reasoning_effort",
2938
+ "model_reasoning_summary",
2527
2939
  "model_provider",
2528
2940
  "service_tier",
2529
2941
  ]) {
@@ -2554,6 +2966,11 @@ export function scanPreflightCodexConfig(config) {
2554
2966
  return result;
2555
2967
  };
2556
2968
  const result = executionConfig(config);
2969
+ // Keep the effective summary even when preflight filters the profile name.
2970
+ const reasoningSummary = resolveCodexProfile(config)["model_reasoning_summary"];
2971
+ if (safeString(reasoningSummary)) {
2972
+ result["model_reasoning_summary"] = reasoningSummary;
2973
+ }
2557
2974
  const selectedProfile = safeProfileName(config["profile"])
2558
2975
  ? config["profile"]
2559
2976
  : undefined;
@@ -2663,7 +3080,7 @@ function bundledCodexSdkEnvironment(command, environment) {
2663
3080
  const pathKeys = Object.keys(result).filter((key) => key.toLowerCase() === "path");
2664
3081
  const pathKey = pathKeys.includes("Path")
2665
3082
  ? "Path"
2666
- : pathKeys.at(-1) ?? "PATH";
3083
+ : (pathKeys.at(-1) ?? "PATH");
2667
3084
  for (const key of pathKeys) {
2668
3085
  if (key !== pathKey)
2669
3086
  delete result[key];