@openai/codex-security 0.9.1 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (444) hide show
  1. package/README.md +37 -788
  2. package/_bundled_plugin/.codex-plugin/plugin.json +2 -0
  3. package/_bundled_plugin/.mcp.json +3 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br +0 -0
  5. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  6. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  7. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  8. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  9. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  10. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  11. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  12. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  13. package/_bundled_plugin/mcp/server.mjs.br +0 -0
  14. package/_bundled_plugin/references/access-advisory.md +1 -1
  15. package/_bundled_plugin/references/artifact-storage.md +1 -1
  16. package/_bundled_plugin/references/baseline-auditor.md +18 -0
  17. package/_bundled_plugin/references/core-scan.md +5 -42
  18. package/_bundled_plugin/references/final-report.md +1 -1
  19. package/_bundled_plugin/references/focused-investigator.md +13 -0
  20. package/_bundled_plugin/references/scan-prologue.md +2 -2
  21. package/_bundled_plugin/references/scan-runtime.md +4 -2
  22. package/_bundled_plugin/references/security-guidance.md +14 -1
  23. package/_bundled_plugin/references/threat-model.md +1 -0
  24. package/_bundled_plugin/references/validate-scan-findings.md +3 -0
  25. package/_bundled_plugin/scripts/deep_scan_workbench.py +30 -12
  26. package/_bundled_plugin/scripts/dispatch_inventory_tool +7 -0
  27. package/_bundled_plugin/scripts/finalize_scan_contract.py +47 -9
  28. package/_bundled_plugin/scripts/launch_codex_security_mcp +54 -16
  29. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +2 -0
  30. package/_bundled_plugin/scripts/posix_scan_local_files.py +26 -1
  31. package/_bundled_plugin/scripts/snapshot_sqlite.py +8 -2
  32. package/_bundled_plugin/scripts/windows_scan_local_files.py +216 -25
  33. package/_bundled_plugin/scripts/workbench/handoff.py +55 -25
  34. package/_bundled_plugin/scripts/workbench/storage.py +25 -5
  35. package/_bundled_plugin/scripts/workbench_cli.py +24 -2
  36. package/_bundled_plugin/scripts/workbench_constants.py +2 -0
  37. package/_bundled_plugin/scripts/workbench_db.py +257 -268
  38. package/_bundled_plugin/scripts/workbench_feedback.py +49 -4
  39. package/_bundled_plugin/scripts/workbench_native_indexes.py +226 -29
  40. package/_bundled_plugin/scripts/workbench_progress.py +159 -3
  41. package/_bundled_plugin/scripts/workbench_publication.py +2 -3
  42. package/_bundled_plugin/scripts/workbench_remediation.py +142 -2
  43. package/_bundled_plugin/scripts/workbench_saved_results.py +48 -8
  44. package/_bundled_plugin/scripts/workbench_scan_history.py +291 -134
  45. package/_bundled_plugin/scripts/workbench_scan_start.py +208 -11
  46. package/_bundled_plugin/scripts/workbench_scan_usage.py +36 -10
  47. package/_bundled_plugin/scripts/workbench_schema.py +220 -14
  48. package/_bundled_plugin/scripts/workbench_setup.py +1 -1
  49. package/_bundled_plugin/scripts/workbench_source_scopes.py +8 -0
  50. package/_bundled_plugin/scripts/workbench_target.py +486 -85
  51. package/_bundled_plugin/scripts/workbench_target_state.py +1108 -22
  52. package/_bundled_plugin/shared/workbench-history-repairs.json +64 -14
  53. package/_bundled_plugin/shared/workbench-migrations.json +66 -0
  54. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +4 -2
  55. package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +2 -2
  56. package/_bundled_plugin/skills/fix-finding/SKILL.md +1 -0
  57. package/_bundled_plugin/skills/publish-findings/SKILL.md +26 -160
  58. package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +2 -2
  59. package/_bundled_plugin/skills/publish-findings/references/checkmarx-import.md +2 -2
  60. package/_bundled_plugin/skills/publish-findings/scripts/collect_checkmarx.py +3 -58
  61. package/_bundled_plugin/skills/publish-findings/scripts/collector_paths.py +63 -0
  62. package/_bundled_plugin/skills/security-scan/SKILL.md +9 -46
  63. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +2 -2
  64. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +3 -21
  65. package/_bundled_plugin/skills/security-scan/references/managed-scan.md +11 -0
  66. package/_bundled_plugin/skills/security-scan/references/scan-results.md +15 -0
  67. package/_bundled_plugin/skills/security-scan/references/scoped-paths.md +23 -0
  68. package/_bundled_plugin/skills/security-scan/references/sdk-files.md +24 -0
  69. package/bin/codex-security.mjs +2 -2
  70. package/dist/api.d.ts +7 -1
  71. package/dist/api.d.ts.map +1 -1
  72. package/dist/api.js +459 -157
  73. package/dist/api.js.map +1 -1
  74. package/dist/armorcode-findings.d.ts +9 -0
  75. package/dist/armorcode-findings.d.ts.map +1 -0
  76. package/dist/armorcode-findings.js +145 -0
  77. package/dist/armorcode-findings.js.map +1 -0
  78. package/dist/artifact-export.d.ts +2 -0
  79. package/dist/artifact-export.d.ts.map +1 -1
  80. package/dist/artifact-export.js +29 -13
  81. package/dist/artifact-export.js.map +1 -1
  82. package/dist/auth.d.ts +6 -2
  83. package/dist/auth.d.ts.map +1 -1
  84. package/dist/auth.js +33 -12
  85. package/dist/auth.js.map +1 -1
  86. package/dist/batch-cost.d.ts +18 -0
  87. package/dist/batch-cost.d.ts.map +1 -0
  88. package/dist/batch-cost.js +41 -0
  89. package/dist/batch-cost.js.map +1 -0
  90. package/dist/blackduck-findings.d.ts +1 -1
  91. package/dist/blackduck-findings.d.ts.map +1 -1
  92. package/dist/blackduck-findings.js +5 -18
  93. package/dist/blackduck-findings.js.map +1 -1
  94. package/dist/bundled-plugin.d.ts +4 -0
  95. package/dist/bundled-plugin.d.ts.map +1 -0
  96. package/dist/bundled-plugin.js +23 -0
  97. package/dist/bundled-plugin.js.map +1 -0
  98. package/dist/classify-scan-severity.d.ts +1 -1
  99. package/dist/classify-scan-severity.d.ts.map +1 -1
  100. package/dist/classify-scan-severity.js +11 -3
  101. package/dist/classify-scan-severity.js.map +1 -1
  102. package/dist/classify-severity-diagnostics.d.ts +10 -0
  103. package/dist/classify-severity-diagnostics.d.ts.map +1 -0
  104. package/dist/classify-severity-diagnostics.js +57 -0
  105. package/dist/classify-severity-diagnostics.js.map +1 -0
  106. package/dist/classify-severity-records.d.ts +4 -0
  107. package/dist/classify-severity-records.d.ts.map +1 -1
  108. package/dist/classify-severity-records.js +35 -8
  109. package/dist/classify-severity-records.js.map +1 -1
  110. package/dist/classify-severity.d.ts.map +1 -1
  111. package/dist/classify-severity.js +9 -6
  112. package/dist/classify-severity.js.map +1 -1
  113. package/dist/cli-argument.d.ts +4 -0
  114. package/dist/cli-argument.d.ts.map +1 -0
  115. package/dist/cli-argument.js +17 -0
  116. package/dist/cli-argument.js.map +1 -0
  117. package/dist/cli-help.d.ts +1 -1
  118. package/dist/cli-help.d.ts.map +1 -1
  119. package/dist/cli-help.js +71 -29
  120. package/dist/cli-help.js.map +1 -1
  121. package/dist/cli-hook.d.ts +3 -0
  122. package/dist/cli-hook.d.ts.map +1 -0
  123. package/dist/cli-hook.js +87 -0
  124. package/dist/cli-hook.js.map +1 -0
  125. package/dist/cli-integrations.d.ts +13 -0
  126. package/dist/cli-integrations.d.ts.map +1 -0
  127. package/dist/cli-integrations.js +333 -0
  128. package/dist/cli-integrations.js.map +1 -0
  129. package/dist/cli-mcp.d.ts +15 -0
  130. package/dist/cli-mcp.d.ts.map +1 -0
  131. package/dist/cli-mcp.js +178 -0
  132. package/dist/cli-mcp.js.map +1 -0
  133. package/dist/cli-token-view.d.ts +10 -0
  134. package/dist/cli-token-view.d.ts.map +1 -0
  135. package/dist/cli-token-view.js +41 -0
  136. package/dist/cli-token-view.js.map +1 -0
  137. package/dist/cli.d.ts +8 -3
  138. package/dist/cli.d.ts.map +1 -1
  139. package/dist/cli.js +1860 -903
  140. package/dist/cli.js.map +1 -1
  141. package/dist/cloud-publish.d.ts.map +1 -1
  142. package/dist/cloud-publish.js +33 -31
  143. package/dist/cloud-publish.js.map +1 -1
  144. package/dist/codex-sdk-environment.d.ts +6 -0
  145. package/dist/codex-sdk-environment.d.ts.map +1 -1
  146. package/dist/codex-sdk-environment.js +19 -0
  147. package/dist/codex-sdk-environment.js.map +1 -1
  148. package/dist/command-words.d.ts +3 -0
  149. package/dist/command-words.d.ts.map +1 -0
  150. package/dist/command-words.js +46 -0
  151. package/dist/command-words.js.map +1 -0
  152. package/dist/component-plan.d.ts.map +1 -1
  153. package/dist/component-plan.js +3 -3
  154. package/dist/component-plan.js.map +1 -1
  155. package/dist/component-scan.d.ts +3 -1
  156. package/dist/component-scan.d.ts.map +1 -1
  157. package/dist/component-scan.js +40 -7
  158. package/dist/component-scan.js.map +1 -1
  159. package/dist/config.d.ts +1 -1
  160. package/dist/config.d.ts.map +1 -1
  161. package/dist/config.js +30 -1
  162. package/dist/config.js.map +1 -1
  163. package/dist/continuum-aws.d.ts +6 -0
  164. package/dist/continuum-aws.d.ts.map +1 -0
  165. package/dist/continuum-aws.js +202 -0
  166. package/dist/continuum-aws.js.map +1 -0
  167. package/dist/continuum-collector.d.ts +44 -0
  168. package/dist/continuum-collector.d.ts.map +1 -0
  169. package/dist/continuum-collector.js +266 -0
  170. package/dist/continuum-collector.js.map +1 -0
  171. package/dist/continuum-findings.d.ts +31 -2
  172. package/dist/continuum-findings.d.ts.map +1 -1
  173. package/dist/continuum-findings.js +497 -59
  174. package/dist/continuum-findings.js.map +1 -1
  175. package/dist/contract.d.ts +1 -0
  176. package/dist/contract.d.ts.map +1 -1
  177. package/dist/contract.js +3 -0
  178. package/dist/contract.js.map +1 -1
  179. package/dist/cost.d.ts.map +1 -1
  180. package/dist/cost.js +1 -45
  181. package/dist/cost.js.map +1 -1
  182. package/dist/crowdstrike-findings.d.ts +7 -0
  183. package/dist/crowdstrike-findings.d.ts.map +1 -0
  184. package/dist/crowdstrike-findings.js +210 -0
  185. package/dist/crowdstrike-findings.js.map +1 -0
  186. package/dist/custom-validation-prompt.d.ts +1 -1
  187. package/dist/custom-validation-prompt.d.ts.map +1 -1
  188. package/dist/custom-validation-prompt.js +29 -19
  189. package/dist/custom-validation-prompt.js.map +1 -1
  190. package/dist/deduplication/local.d.ts +3 -1
  191. package/dist/deduplication/local.d.ts.map +1 -1
  192. package/dist/deduplication/local.js +8 -1
  193. package/dist/deduplication/local.js.map +1 -1
  194. package/dist/deduplication/refusal.d.ts.map +1 -1
  195. package/dist/deduplication/refusal.js +2 -1
  196. package/dist/deduplication/refusal.js.map +1 -1
  197. package/dist/deduplication/scan.d.ts +2 -0
  198. package/dist/deduplication/scan.d.ts.map +1 -1
  199. package/dist/deduplication/scan.js +24 -7
  200. package/dist/deduplication/scan.js.map +1 -1
  201. package/dist/deep-scan.d.ts.map +1 -1
  202. package/dist/deep-scan.js +16 -15
  203. package/dist/deep-scan.js.map +1 -1
  204. package/dist/endor-findings.d.ts +2 -2
  205. package/dist/endor-findings.d.ts.map +1 -1
  206. package/dist/endor-findings.js +6 -23
  207. package/dist/endor-findings.js.map +1 -1
  208. package/dist/errors.d.ts +3 -1
  209. package/dist/errors.d.ts.map +1 -1
  210. package/dist/errors.js +7 -3
  211. package/dist/errors.js.map +1 -1
  212. package/dist/executable-path.d.ts +3 -0
  213. package/dist/executable-path.d.ts.map +1 -1
  214. package/dist/executable-path.js +26 -0
  215. package/dist/executable-path.js.map +1 -1
  216. package/dist/external-findings-import.d.ts.map +1 -1
  217. package/dist/external-findings-import.js +12 -1
  218. package/dist/external-findings-import.js.map +1 -1
  219. package/dist/external-findings-local.d.ts +66 -4
  220. package/dist/external-findings-local.d.ts.map +1 -1
  221. package/dist/external-findings-local.js +258 -59
  222. package/dist/external-findings-local.js.map +1 -1
  223. package/dist/external-findings-publish.d.ts +6 -1
  224. package/dist/external-findings-publish.d.ts.map +1 -1
  225. package/dist/external-findings-publish.js +330 -1633
  226. package/dist/external-findings-publish.js.map +1 -1
  227. package/dist/external-findings-read.d.ts +11 -2
  228. package/dist/external-findings-read.d.ts.map +1 -1
  229. package/dist/external-findings-read.js +56 -53
  230. package/dist/external-findings-read.js.map +1 -1
  231. package/dist/external-findings.d.ts +1 -1
  232. package/dist/external-findings.d.ts.map +1 -1
  233. package/dist/external-findings.js +12 -1
  234. package/dist/external-findings.js.map +1 -1
  235. package/dist/external-import-contract.d.ts +6 -11
  236. package/dist/external-import-contract.d.ts.map +1 -1
  237. package/dist/external-import-contract.js +35 -177
  238. package/dist/external-import-contract.js.map +1 -1
  239. package/dist/external-import-models.d.ts +1 -1
  240. package/dist/external-import-models.d.ts.map +1 -1
  241. package/dist/external-import-models.js.map +1 -1
  242. package/dist/finding-prompt.d.ts.map +1 -1
  243. package/dist/finding-prompt.js +2 -2
  244. package/dist/finding-prompt.js.map +1 -1
  245. package/dist/github-dependabot-findings.d.ts.map +1 -1
  246. package/dist/github-dependabot-findings.js +3 -4
  247. package/dist/github-dependabot-findings.js.map +1 -1
  248. package/dist/github-findings.d.ts.map +1 -1
  249. package/dist/github-findings.js +19 -287
  250. package/dist/github-findings.js.map +1 -1
  251. package/dist/host-protocol.d.ts +6 -0
  252. package/dist/host-protocol.d.ts.map +1 -1
  253. package/dist/host-protocol.js +11 -1
  254. package/dist/host-protocol.js.map +1 -1
  255. package/dist/host-records-protocol.d.ts +2 -0
  256. package/dist/host-records-protocol.d.ts.map +1 -1
  257. package/dist/host-records-protocol.js +4 -0
  258. package/dist/host-records-protocol.js.map +1 -1
  259. package/dist/hosted-remediation.d.ts +1 -0
  260. package/dist/hosted-remediation.d.ts.map +1 -1
  261. package/dist/hosted-remediation.js +23 -3
  262. package/dist/hosted-remediation.js.map +1 -1
  263. package/dist/index.d.ts +5 -3
  264. package/dist/index.d.ts.map +1 -1
  265. package/dist/index.js +3 -1
  266. package/dist/index.js.map +1 -1
  267. package/dist/inspector-findings.d.ts.map +1 -1
  268. package/dist/inspector-findings.js +19 -35
  269. package/dist/inspector-findings.js.map +1 -1
  270. package/dist/knowledge-base.d.ts +1 -1
  271. package/dist/knowledge-base.d.ts.map +1 -1
  272. package/dist/knowledge-base.js +34 -27
  273. package/dist/knowledge-base.js.map +1 -1
  274. package/dist/linear.d.ts +11 -0
  275. package/dist/linear.d.ts.map +1 -1
  276. package/dist/linear.js.map +1 -1
  277. package/dist/local-git-metadata.d.ts +5 -2
  278. package/dist/local-git-metadata.d.ts.map +1 -1
  279. package/dist/local-git-metadata.js +8 -4
  280. package/dist/local-git-metadata.js.map +1 -1
  281. package/dist/multiscan.d.ts +4 -0
  282. package/dist/multiscan.d.ts.map +1 -1
  283. package/dist/multiscan.js +83 -39
  284. package/dist/multiscan.js.map +1 -1
  285. package/dist/opengrep-findings.d.ts +4 -2
  286. package/dist/opengrep-findings.d.ts.map +1 -1
  287. package/dist/opengrep-findings.js +39 -22
  288. package/dist/opengrep-findings.js.map +1 -1
  289. package/dist/private-finding-import.d.ts +8 -13
  290. package/dist/private-finding-import.d.ts.map +1 -1
  291. package/dist/private-finding-import.js +69 -129
  292. package/dist/private-finding-import.js.map +1 -1
  293. package/dist/project-config-schema.d.ts +2 -0
  294. package/dist/project-config-schema.d.ts.map +1 -1
  295. package/dist/project-config-schema.js +1 -0
  296. package/dist/project-config-schema.js.map +1 -1
  297. package/dist/project-config.d.ts +1 -0
  298. package/dist/project-config.d.ts.map +1 -1
  299. package/dist/project-config.js +56 -13
  300. package/dist/project-config.js.map +1 -1
  301. package/dist/prompt-files.d.ts +7 -2
  302. package/dist/prompt-files.d.ts.map +1 -1
  303. package/dist/prompt-files.js +42 -20
  304. package/dist/prompt-files.js.map +1 -1
  305. package/dist/provider-profile.d.ts.map +1 -1
  306. package/dist/provider-profile.js +4 -9
  307. package/dist/provider-profile.js.map +1 -1
  308. package/dist/publication.d.ts +1 -1
  309. package/dist/publication.d.ts.map +1 -1
  310. package/dist/publication.js.map +1 -1
  311. package/dist/record.d.ts +1 -5
  312. package/dist/record.d.ts.map +1 -1
  313. package/dist/record.js +3 -51
  314. package/dist/record.js.map +1 -1
  315. package/dist/remediation.d.ts.map +1 -1
  316. package/dist/remediation.js +3 -1
  317. package/dist/remediation.js.map +1 -1
  318. package/dist/runtime.d.ts +35 -7
  319. package/dist/runtime.d.ts.map +1 -1
  320. package/dist/runtime.js +782 -153
  321. package/dist/runtime.js.map +1 -1
  322. package/dist/saved-scan-bootstrap.d.ts +6 -1
  323. package/dist/saved-scan-bootstrap.d.ts.map +1 -1
  324. package/dist/saved-scan-bootstrap.js +267 -115
  325. package/dist/saved-scan-bootstrap.js.map +1 -1
  326. package/dist/scan-archive-path.d.ts +2 -0
  327. package/dist/scan-archive-path.d.ts.map +1 -0
  328. package/dist/scan-archive-path.js +5 -0
  329. package/dist/scan-archive-path.js.map +1 -0
  330. package/dist/scan-comparison.d.ts +20 -2
  331. package/dist/scan-comparison.d.ts.map +1 -1
  332. package/dist/scan-comparison.js +26 -5
  333. package/dist/scan-comparison.js.map +1 -1
  334. package/dist/scan-dashboard.d.ts +1 -0
  335. package/dist/scan-dashboard.d.ts.map +1 -1
  336. package/dist/scan-dashboard.js +18 -2
  337. package/dist/scan-dashboard.js.map +1 -1
  338. package/dist/scan-executor.d.ts.map +1 -1
  339. package/dist/scan-executor.js +4 -2
  340. package/dist/scan-executor.js.map +1 -1
  341. package/dist/scan-history-renderer.d.ts +1 -0
  342. package/dist/scan-history-renderer.d.ts.map +1 -1
  343. package/dist/scan-history-renderer.js +25 -9
  344. package/dist/scan-history-renderer.js.map +1 -1
  345. package/dist/scan-logs.d.ts.map +1 -1
  346. package/dist/scan-logs.js +28 -4
  347. package/dist/scan-logs.js.map +1 -1
  348. package/dist/scan-settings.d.ts +1 -0
  349. package/dist/scan-settings.d.ts.map +1 -1
  350. package/dist/scan-settings.js +1 -0
  351. package/dist/scan-settings.js.map +1 -1
  352. package/dist/scanner-import.d.ts +5 -11
  353. package/dist/scanner-import.d.ts.map +1 -1
  354. package/dist/scanner-import.js +16 -89
  355. package/dist/scanner-import.js.map +1 -1
  356. package/dist/security-policy.d.ts.map +1 -1
  357. package/dist/security-policy.js +26 -6
  358. package/dist/security-policy.js.map +1 -1
  359. package/dist/semgrep-findings.d.ts.map +1 -1
  360. package/dist/semgrep-findings.js +14 -48
  361. package/dist/semgrep-findings.js.map +1 -1
  362. package/dist/semgrep-platform-findings.d.ts +20 -70
  363. package/dist/semgrep-platform-findings.d.ts.map +1 -1
  364. package/dist/semgrep-platform-findings.js +116 -333
  365. package/dist/semgrep-platform-findings.js.map +1 -1
  366. package/dist/severity-review.d.ts.map +1 -1
  367. package/dist/severity-review.js +1 -0
  368. package/dist/severity-review.js.map +1 -1
  369. package/dist/snyk-findings.d.ts +2 -0
  370. package/dist/snyk-findings.d.ts.map +1 -1
  371. package/dist/snyk-findings.js +5 -8
  372. package/dist/snyk-findings.js.map +1 -1
  373. package/dist/snyk-rest-findings.d.ts +3 -20
  374. package/dist/snyk-rest-findings.d.ts.map +1 -1
  375. package/dist/snyk-rest-findings.js +45 -217
  376. package/dist/snyk-rest-findings.js.map +1 -1
  377. package/dist/sonar-findings.d.ts +1 -1
  378. package/dist/sonar-findings.d.ts.map +1 -1
  379. package/dist/sonar-findings.js +2 -4
  380. package/dist/sonar-findings.js.map +1 -1
  381. package/dist/sonar-import.d.ts +3 -0
  382. package/dist/sonar-import.d.ts.map +1 -1
  383. package/dist/sonar-import.js +28 -30
  384. package/dist/sonar-import.js.map +1 -1
  385. package/dist/stored-finding-projection.d.ts +6 -0
  386. package/dist/stored-finding-projection.d.ts.map +1 -0
  387. package/dist/stored-finding-projection.js +129 -0
  388. package/dist/stored-finding-projection.js.map +1 -0
  389. package/dist/stored-findings-publication.d.ts +23 -0
  390. package/dist/stored-findings-publication.d.ts.map +1 -0
  391. package/dist/stored-findings-publication.js +169 -0
  392. package/dist/stored-findings-publication.js.map +1 -0
  393. package/dist/targets.d.ts +8 -1
  394. package/dist/targets.d.ts.map +1 -1
  395. package/dist/targets.js +103 -23
  396. package/dist/targets.js.map +1 -1
  397. package/dist/tenable-findings.d.ts +1 -4
  398. package/dist/tenable-findings.d.ts.map +1 -1
  399. package/dist/tenable-findings.js.map +1 -1
  400. package/dist/trivy-findings.d.ts.map +1 -1
  401. package/dist/trivy-findings.js +0 -11
  402. package/dist/trivy-findings.js.map +1 -1
  403. package/dist/trusted-executable.d.ts +7 -0
  404. package/dist/trusted-executable.d.ts.map +1 -1
  405. package/dist/trusted-executable.js +148 -37
  406. package/dist/trusted-executable.js.map +1 -1
  407. package/dist/value.js +3 -1
  408. package/dist/value.js.map +1 -1
  409. package/dist/veracode-findings.d.ts +1 -3
  410. package/dist/veracode-findings.d.ts.map +1 -1
  411. package/dist/veracode-findings.js +13 -38
  412. package/dist/veracode-findings.js.map +1 -1
  413. package/dist/version.d.ts +3 -1
  414. package/dist/version.d.ts.map +1 -1
  415. package/dist/version.js +184 -32
  416. package/dist/version.js.map +1 -1
  417. package/dist/wiz-findings.d.ts +2 -2
  418. package/dist/wiz-findings.d.ts.map +1 -1
  419. package/dist/wiz-findings.js +14 -92
  420. package/dist/wiz-findings.js.map +1 -1
  421. package/docs/classify-severity-records.md +30 -0
  422. package/docs/cli.md +537 -124
  423. package/docs/findings-service.md +22 -9
  424. package/docs/hosted-remediation.md +13 -4
  425. package/docs/sdk.md +918 -0
  426. package/package.json +15 -6
  427. package/schemas/external-findings.schema.json +2 -1
  428. package/schemas/project-config.schema.json +5 -0
  429. package/dist/hosted-scanner-v1.d.ts +0 -6
  430. package/dist/hosted-scanner-v1.d.ts.map +0 -1
  431. package/dist/hosted-scanner-v1.js +0 -60
  432. package/dist/hosted-scanner-v1.js.map +0 -1
  433. package/dist/reader-selection.d.ts +0 -15
  434. package/dist/reader-selection.d.ts.map +0 -1
  435. package/dist/reader-selection.js +0 -89
  436. package/dist/reader-selection.js.map +0 -1
  437. package/dist/semgrep-platform-v1.d.ts +0 -6
  438. package/dist/semgrep-platform-v1.d.ts.map +0 -1
  439. package/dist/semgrep-platform-v1.js +0 -83
  440. package/dist/semgrep-platform-v1.js.map +0 -1
  441. package/dist/snyk-rest-v1.d.ts +0 -28
  442. package/dist/snyk-rest-v1.d.ts.map +0 -1
  443. package/dist/snyk-rest-v1.js +0 -132
  444. package/dist/snyk-rest-v1.js.map +0 -1
package/dist/runtime.js CHANGED
@@ -1,27 +1,30 @@
1
- import { executablePathForSpawn } from "./executable-path.js";
1
+ import { configuredExecutableValue, executablePathForSpawn, isExplicitPathWithTrailingWhitespace, isExecutableFile, } from "./executable-path.js";
2
2
  import { retryWindowsRename } from "./retry-windows-rename.js";
3
3
  export { executablePathForSpawn } from "./executable-path.js";
4
+ import { bundledPluginRoot, hasPluginManifest } from "./bundled-plugin.js";
5
+ export { bundledPluginCandidates, bundledPluginRoot, } from "./bundled-plugin.js";
4
6
  import { PLUGIN_PYTHON_PROBE, PLUGIN_PYTHON_PROBE_TIMEOUT_MS, PLUGIN_PYTHON_READY, } from "./plugin-python-probe.js";
5
7
  import { resolveBundledCodexExecutable } from "./codex-sdk-environment.js";
6
- import { gitProtectionRoots } from "./targets.js";
8
+ import { abortable, gitProtectionRoots, resolveTargetPath } from "./targets.js";
7
9
  import { isNonEmptyString, notify } from "./value.js";
8
10
  import { execFile as execFileCallback, spawn, } from "node:child_process";
9
- import { randomUUID } from "node:crypto";
11
+ import { createHash, randomUUID } from "node:crypto";
12
+ import { shortArchivePrefix } from "./scan-archive-path.js";
10
13
  import { chmodSync, close as closeCallback, constants, createWriteStream, fstat as fstatCallback, open as openCallback, read as readCallback, } from "node:fs";
11
- import { chmod, cp, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, utimes, writeFile, } from "node:fs/promises";
14
+ import { access, chmod, cp, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, utimes, writeFile, } from "node:fs/promises";
12
15
  import { homedir, tmpdir } from "node:os";
13
16
  import { createRequire } from "node:module";
14
17
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep, win32, } from "node:path";
15
- import { fileURLToPath } from "node:url";
16
18
  import { promisify } from "node:util";
17
19
  import { pipeline } from "node:stream/promises";
18
20
  import { crc32 } from "node:zlib";
19
21
  import { setTimeout as delay } from "node:timers/promises";
20
22
  import { fromFdPromise } from "yauzl";
21
23
  import { parse } from "smol-toml";
22
- import { CodexSecurityError, OutputDirectoryError, OutputDirectoryNotEmptyError, OutputInsideProtectedRootError, PluginBootstrapError, LocalPluginBootstrapError, PluginPythonUnavailableError, SandboxUnavailableError, errorMessage, abortReason, } from "./errors.js";
24
+ import { CodexSecurityError, InvalidTargetError, OutputDirectoryError, OutputDirectoryNotEmptyError, OutputInsideProtectedRootError, PluginBootstrapError, LocalPluginBootstrapError, PluginPythonUnavailableError, SandboxUnavailableError, errorMessage, abortReason, } from "./errors.js";
25
+ import { writeCodexConfig, writePrivateConfig, } from "./config.js";
23
26
  import { isRecord } from "./record.js";
24
- import { isWithin, resolveTrustedExecutable, } from "./trusted-executable.js";
27
+ import { campaignExecutable, inspectTrustedExecutable, isWithin, resolveTrustedExecutable, } from "./trusted-executable.js";
25
28
  import { isWindowsUnsafePathComponent, sqliteFilename, windowsUnsafePathComponent, } from "./windows-path.js";
26
29
  const execFile = promisify(execFileCallback);
27
30
  export const MARKETPLACE_NAME = "codex-security-sdk";
@@ -46,6 +49,7 @@ const MODEL_UNSAFE_PATH = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u;
46
49
  const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";
47
50
  const CREDENTIAL_LOCK_DATABASE = ".codex-security-scan.sqlite3";
48
51
  const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";
52
+ const KEYRING_LOGIN = ".codex-security-keyring-login";
49
53
  const CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS = 5_000;
50
54
  const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;
51
55
  const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;
@@ -99,7 +103,7 @@ function environmentValue(environment, requested, preserveWhitespace = false) {
99
103
  return preserveWhitespace ? value : value?.trim();
100
104
  }
101
105
  export function codexSecurityStateDirectory(environment = process.env) {
102
- const configured = environmentValue(environment, "CODEX_SECURITY_STATE_DIR");
106
+ const configured = environmentValue(environment, "CODEX_SECURITY_STATE_DIR", process.platform !== "win32");
103
107
  const path = configured !== undefined
104
108
  ? resolve(expandHome(configured, environment))
105
109
  : resolve(expandHome(environmentValue(environment, "CODEX_HOME", true) ??
@@ -914,6 +918,32 @@ export function sqliteDatabaseOpener(access = "read-write") {
914
918
  : { readOnly: true });
915
919
  };
916
920
  }
921
+ function sqliteBusy(error) {
922
+ return (isRecord(error) &&
923
+ (error["errcode"] === 5 || error["code"] === "SQLITE_BUSY"));
924
+ }
925
+ export async function acquireScanExecutionLock(stateDirectory, scanDirectory) {
926
+ const directory = join(stateDirectory, "scan-locks");
927
+ await mkdir(directory, { recursive: true, mode: 0o700 });
928
+ await requirePrivateDirectory(await stat(directory), directory, "scan locks");
929
+ const identity = createHash("sha256").update(scanDirectory).digest("hex");
930
+ const path = join(directory, `${identity}.sqlite3`);
931
+ const database = sqliteDatabaseOpener()(path);
932
+ try {
933
+ if (process.platform !== "win32")
934
+ await chmod(path, 0o600);
935
+ database.exec("PRAGMA busy_timeout = 0");
936
+ database.exec("BEGIN EXCLUSIVE");
937
+ }
938
+ catch (error) {
939
+ database.close();
940
+ if (sqliteBusy(error)) {
941
+ throw new CodexSecurityError("This scan is already running in another CLI or SDK call.");
942
+ }
943
+ throw error;
944
+ }
945
+ return () => database.close();
946
+ }
917
947
  export async function withCredentialHomeLock(codexHome, operation, signal) {
918
948
  const release = await acquireCodexSecurityCredentialHomeLock(codexHome, signal);
919
949
  try {
@@ -971,8 +1001,7 @@ export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal,
971
1001
  database.exec("BEGIN EXCLUSIVE");
972
1002
  }
973
1003
  catch (error) {
974
- if (!isRecord(error) ||
975
- (error["errcode"] !== 5 && error["code"] !== "SQLITE_BUSY")) {
1004
+ if (!sqliteBusy(error)) {
976
1005
  throw error;
977
1006
  }
978
1007
  await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
@@ -1138,47 +1167,141 @@ async function hasSeparateAmbientLink(localPath, ambientHome) {
1138
1167
  return false;
1139
1168
  }
1140
1169
  }
1170
+ /** Native Codex defaults to file storage when the managed home has no setting. */
1171
+ async function credentialStore(home) {
1172
+ const contents = await readFile(join(home, "config.toml"), "utf8").catch(nullIfMissingFileError);
1173
+ return contents === null
1174
+ ? "file"
1175
+ : (parse(contents, { integersAsBigInt: "asNeeded" })["cli_auth_credentials_store"] ?? "file");
1176
+ }
1177
+ async function hasCredentialFile(home) {
1178
+ const file = await lstat(join(home, "auth.json")).catch(nullIfMissingFileError);
1179
+ return file?.isFile() === true;
1180
+ }
1181
+ function savedKeyringHistory(home) {
1182
+ return readFile(join(home, KEYRING_LOGIN), "utf8").catch(nullIfMissingFileError);
1183
+ }
1184
+ function canUseKeyring(store) {
1185
+ return store === "auto" || store === "keyring";
1186
+ }
1187
+ function keyringHistory(saved, store, hasFile) {
1188
+ if (saved === "keyring" || saved === "pending")
1189
+ return "keyring";
1190
+ // On upgrade, a prior keyring login may exist. Auto can also move a file
1191
+ // credential into the keyring on refresh, removing auth.json.
1192
+ if ((saved === null && canUseKeyring(store)) ||
1193
+ (saved === "file" && store === "auto" && !hasFile))
1194
+ return "keyring";
1195
+ return hasFile ? "file" : "none";
1196
+ }
1197
+ async function rememberStoredFile(home) {
1198
+ if ((await savedKeyringHistory(home)) === "none") {
1199
+ await writePrivateConfig(join(home, KEYRING_LOGIN), "file");
1200
+ }
1201
+ }
1202
+ /** Arm logout before a native login can persist a keyring grant and be interrupted. */
1203
+ export async function beginCredentialLogin(home) {
1204
+ const store = await credentialStore(home);
1205
+ if (!canUseKeyring(store))
1206
+ return;
1207
+ const marker = join(home, KEYRING_LOGIN);
1208
+ const saved = await savedKeyringHistory(home);
1209
+ const present = await hasCredentialFile(home);
1210
+ const previous = keyringHistory(saved, store, present);
1211
+ // Only this login's successful file fallback can discharge a new pending marker.
1212
+ const next = previous === "keyring" ? "keyring" : "pending";
1213
+ if (next !== saved)
1214
+ await writePrivateConfig(marker, next);
1215
+ }
1216
+ /** Is the managed file the active login, or a known-empty file destination for an ambient import? */
1217
+ export async function credentialHomeUsesFileStorage(home, options = {}) {
1218
+ const store = await credentialStore(home);
1219
+ if (store !== "auto")
1220
+ return store === "file";
1221
+ const saved = await savedKeyringHistory(home);
1222
+ const hasFile = await hasCredentialFile(home);
1223
+ return hasFile
1224
+ ? saved === "file"
1225
+ : options.allowAmbientImport === true && saved === "none";
1226
+ }
1227
+ /** Preserve credential provenance before a scan or sign-in replaces the shared config. */
1228
+ export async function writeCredentialHomeConfig(home, config) {
1229
+ const old = await credentialStore(home);
1230
+ if (canUseKeyring(old) ||
1231
+ canUseKeyring(config["cli_auth_credentials_store"])) {
1232
+ const marker = join(home, KEYRING_LOGIN);
1233
+ const saved = await savedKeyringHistory(home);
1234
+ const hasFile = await hasCredentialFile(home);
1235
+ const observed = keyringHistory(saved, old, hasFile);
1236
+ if (observed !== saved)
1237
+ await writePrivateConfig(marker, observed);
1238
+ }
1239
+ await writeCodexConfig(join(home, "config.toml"), config);
1240
+ }
1141
1241
  /** Run under the credential-home lock so status cannot reimport the sign-in during logout. */
1142
1242
  export async function logoutCredentialHome(home, ambientHome, nativeLogout, onLoggedOut) {
1143
1243
  const localPath = join(home, "auth.json");
1144
1244
  const shared = await hasSeparateAmbientLink(localPath, ambientHome);
1245
+ let recorded = false;
1145
1246
  const recordLogout = async () => {
1247
+ if (recorded)
1248
+ return;
1146
1249
  await setCodexSecurityCredentialLogout(home, true);
1147
1250
  if (shared)
1148
1251
  await rm(localPath);
1149
1252
  onLoggedOut?.();
1253
+ recorded = true;
1150
1254
  };
1151
1255
  // Detach before native logout can revoke a shared token, even if native cleanup fails.
1152
1256
  if (shared)
1153
1257
  await recordLogout();
1154
- const status = await nativeLogout();
1155
- if (!shared && (status === undefined || status === 0))
1258
+ const marker = join(home, KEYRING_LOGIN);
1259
+ const previous = await savedKeyringHistory(home);
1260
+ const active = await credentialStore(home);
1261
+ const hasFile = await hasCredentialFile(home);
1262
+ const keyring = keyringHistory(previous, active, hasFile || shared) === "keyring";
1263
+ if (keyring && hasFile) {
1264
+ // Native keyring logout also unlinks the file, but only revokes the token it loads.
1265
+ const status = await nativeLogout(active === "file" ? undefined : "file");
1266
+ if (status !== undefined && status !== 0)
1267
+ return status;
1268
+ // A retry must not re-import ambient credentials after the file was revoked.
1269
+ await recordLogout();
1270
+ }
1271
+ let override;
1272
+ if (keyring && !canUseKeyring(active))
1273
+ override = "keyring";
1274
+ else if (!keyring && active !== "file" && (hasFile || canUseKeyring(active)))
1275
+ override = "file";
1276
+ const status = await nativeLogout(override);
1277
+ if (status === undefined || status === 0) {
1156
1278
  await recordLogout();
1279
+ if (canUseKeyring(active))
1280
+ await writePrivateConfig(marker, "none");
1281
+ else
1282
+ await rm(marker, { force: true });
1283
+ }
1157
1284
  return status;
1158
1285
  }
1159
1286
  export async function setCodexSecurityCredentialLogout(codexHome, loggedOut) {
1160
1287
  await requireSecureCredentialHome(codexHome);
1161
1288
  const marker = join(codexHome, CREDENTIAL_LOGOUT_MARKER);
1162
1289
  if (!loggedOut) {
1163
- await rm(marker, { force: true });
1164
- return;
1165
- }
1166
- const temporary = join(codexHome, `.codex-security-logout-${randomUUID()}.tmp`);
1167
- try {
1168
- const handle = await open(temporary, "wx", 0o600);
1169
- try {
1170
- await handle.chmod(0o600);
1171
- await handle.writeFile("logged out\n", "utf8");
1172
- await handle.sync();
1290
+ // Native auto removes auth.json on keyring success and leaves it on file fallback.
1291
+ const store = await credentialStore(codexHome);
1292
+ const history = join(codexHome, KEYRING_LOGIN);
1293
+ if (store === "keyring" ||
1294
+ (store === "auto" && !(await hasCredentialFile(codexHome)))) {
1295
+ await writePrivateConfig(history, "keyring");
1173
1296
  }
1174
- finally {
1175
- await handle.close();
1297
+ else if (store === "auto" &&
1298
+ (await savedKeyringHistory(codexHome)) === "pending") {
1299
+ await writePrivateConfig(history, "file");
1176
1300
  }
1177
- await rename(temporary, marker);
1178
- }
1179
- finally {
1180
- await rm(temporary, { force: true });
1301
+ await rm(marker, { force: true });
1302
+ return;
1181
1303
  }
1304
+ await writePrivateConfig(marker, "logged out\n");
1182
1305
  }
1183
1306
  export async function codexSecurityCredentialAllowsAmbientImport(codexHome) {
1184
1307
  await requireSecureCredentialHome(codexHome);
@@ -1272,6 +1395,40 @@ export function requireOutputOutsideRepositories(repositories, outputDirectory,
1272
1395
  for (const repository of repositories)
1273
1396
  requireOutputOutsideRepository(repository, outputDirectory, pathKind);
1274
1397
  }
1398
+ /** Check where the scan will create state and default artifacts without creating them. */
1399
+ export async function checkScanStorage(stateDirectory, defaultOutputRepository) {
1400
+ try {
1401
+ let root = await canonicalConfigPath(stateDirectory);
1402
+ await requireWritableDirectoryOrParent(root);
1403
+ if (defaultOutputRepository === undefined)
1404
+ return;
1405
+ for (const name of ["scans", safePrefix(defaultOutputRepository)]) {
1406
+ root = join(root, name);
1407
+ const metadata = await lstat(root).catch(nullIfMissingFileError);
1408
+ if (metadata !== null && !metadata.isDirectory()) {
1409
+ throw new OutputDirectoryError(`Persistent scan output must use real directories: ${root}`);
1410
+ }
1411
+ }
1412
+ await requireWritableDirectoryOrParent(root);
1413
+ // New per-scan directories are created beneath this root.
1414
+ await requireSecureOutputAncestry(join(root, `codex-security-${randomUUID()}`));
1415
+ }
1416
+ catch (error) {
1417
+ throw new OutputDirectoryError(`Cannot use scan state directory ${stateDirectory}. Check CODEX_SECURITY_STATE_DIR: ${errorMessage(error)}`, { cause: error });
1418
+ }
1419
+ }
1420
+ async function requireWritableDirectoryOrParent(path) {
1421
+ const metadata = await lstat(path).catch(nullIfMissingFileError);
1422
+ if (metadata === null) {
1423
+ const parent = dirname(path);
1424
+ if (parent === path)
1425
+ throw new OutputDirectoryError(`Directory does not exist: ${path}`);
1426
+ return requireWritableDirectoryOrParent(parent);
1427
+ }
1428
+ if (!metadata.isDirectory())
1429
+ throw new OutputDirectoryError(`Expected a directory: ${path}`);
1430
+ await access(path, constants.W_OK | constants.X_OK);
1431
+ }
1275
1432
  export async function preparePersistentOutputRoot(stateDirectory, category, repositoryName) {
1276
1433
  requireModelSafeOutputDir(stateDirectory);
1277
1434
  await mkdir(stateDirectory, { recursive: true, mode: 0o700 });
@@ -1294,20 +1451,21 @@ import runpy, sys
1294
1451
  sys.argv = sys.argv[1:]
1295
1452
  runpy.run_path(sys.argv[0], run_name="__main__")
1296
1453
  `;
1297
- const ARCHIVE_READY = "codex-security-archive-ready\n";
1298
- const ARCHIVE_REGISTRATION_PROGRAM = String.raw `
1299
- import io, json, runpy, sys
1300
- control = sys.stdin
1301
- payload = json.loads(control.readline())
1302
- sys.stdin = io.TextIOWrapper(io.BytesIO(payload.encode("utf-8")), encoding="utf-8")
1454
+ const WORKBENCH_REGISTRATION_PROGRAM = String.raw `
1455
+ import os, runpy, sys
1303
1456
  sys.argv = sys.argv[1:]
1304
- workbench = runpy.run_path(sys.argv[0])
1305
- def before_archive():
1306
- sys.stdout.buffer.write(b"codex-security-archive-ready\n")
1307
- sys.stdout.buffer.flush()
1308
- if control.readline() != "\n":
1309
- raise SystemExit("Scan registration canceled before archival.")
1310
- workbench["main"](before_archive=before_archive)
1457
+ def before_output_change():
1458
+ with os.fdopen(3, "r+b", buffering=0) as control:
1459
+ control.write(b"?")
1460
+ if control.read(1) != b"!":
1461
+ raise SystemExit("Scan registration canceled before changing the output.")
1462
+ sys._codex_security_before_output_change = before_output_change
1463
+ if "--archive-existing" in sys.argv[1:] and "--archived-scan-dir" not in sys.argv[1:]:
1464
+ # Released workbenches accept this callback before moving an existing output.
1465
+ runpy.run_path(sys.argv[0])["main"](before_archive=before_output_change)
1466
+ else:
1467
+ # A selected plugin keeps its script entrypoint, argv, stdin and stdout.
1468
+ runpy.run_path(sys.argv[0], run_name="__main__")
1311
1469
  `;
1312
1470
  export async function runWorkbench(options, args, input) {
1313
1471
  const script = join(options.pluginRoot, "scripts", "workbench_db.py");
@@ -1315,14 +1473,17 @@ export async function runWorkbench(options, args, input) {
1315
1473
  // Explicitly selected external plugins retain their own workbench protocol.
1316
1474
  const nativeLocalDedupe = args[0] === "local-dedupe" &&
1317
1475
  (await sameFile(options.pluginRoot, await bundledPluginRoot()));
1318
- const run = async (arguments_, input, archiveHandshake = false) => {
1476
+ const run = async (arguments_, input, registrationHandshake = false) => {
1319
1477
  const native = nativeLocalDedupe ||
1320
1478
  [
1321
1479
  "database-info",
1322
1480
  "store-findings",
1323
1481
  "list-stored-findings",
1324
1482
  "store-external-findings",
1325
- "list-external-findings",
1483
+ "read-external-findings",
1484
+ "list-external-imports",
1485
+ "record-external-finding-publications",
1486
+ "list-external-finding-publications",
1326
1487
  "find-potential-duplicates",
1327
1488
  "store-dedupe-groups",
1328
1489
  "list-dedupe-groups",
@@ -1366,12 +1527,16 @@ export async function runWorkbench(options, args, input) {
1366
1527
  "-B",
1367
1528
  "-c",
1368
1529
  WORKBENCH_ARGUMENTS_PROGRAM +
1369
- (archiveHandshake
1370
- ? ARCHIVE_REGISTRATION_PROGRAM
1530
+ (registrationHandshake
1531
+ ? WORKBENCH_REGISTRATION_PROGRAM
1371
1532
  : WORKBENCH_SCRIPT_PROGRAM),
1372
1533
  script,
1373
1534
  ], pluginHelperEnvironment({
1374
1535
  ...(node?.environment ?? options.environment),
1536
+ // Older plugins ignore this request and keep returning inline findings.
1537
+ ...(arguments_[0] === "list-unmatched-scan-pairs"
1538
+ ? { CODEX_SECURITY_MATCHING_PLAN_FORMAT: "compact" }
1539
+ : {}),
1375
1540
  // Python's compressed-rollout reader needs the selected Node even when
1376
1541
  // this SDK was launched by absolute path without Node on PATH.
1377
1542
  ...(!native &&
@@ -1391,11 +1556,13 @@ export async function runWorkbench(options, args, input) {
1391
1556
  stateDirectory,
1392
1557
  payload: input === undefined ? undefined : JSON.parse(input),
1393
1558
  })
1394
- : input, signal, archiveHandshake,
1395
- // Frame Python arguments on stdin to preserve NUL and long diagnostics.
1396
- native
1397
- ? undefined
1398
- : `${JSON.stringify(arguments_.map((argument) => argument.toWellFormed()))}\n`);
1559
+ : input, signal, {
1560
+ registrationHandshake,
1561
+ // Frame Python arguments on stdin to preserve NUL and long diagnostics.
1562
+ stdinPrefix: native
1563
+ ? undefined
1564
+ : `${JSON.stringify(arguments_.map((argument) => argument.toWellFormed()))}\n`,
1565
+ });
1399
1566
  if (!result.success) {
1400
1567
  throw new Error(result.stderr.trim() ||
1401
1568
  result.stdout.trim() ||
@@ -1405,11 +1572,25 @@ export async function runWorkbench(options, args, input) {
1405
1572
  };
1406
1573
  let stdout;
1407
1574
  try {
1408
- const archiveHandshake = signal !== undefined &&
1575
+ const registrationHandshake = signal !== undefined &&
1409
1576
  args[0] === "register-cli-scan" &&
1410
- args.includes("--archive-existing") &&
1411
- !args.includes("--archived-scan-dir");
1412
- stdout = await run(args, input, archiveHandshake);
1577
+ (process.platform === "win32" ||
1578
+ (args.includes("--archive-existing") &&
1579
+ !args.includes("--archived-scan-dir")));
1580
+ try {
1581
+ stdout = await run(args, input, registrationHandshake);
1582
+ }
1583
+ catch (error) {
1584
+ const focusedIndex = args.indexOf("--after-scan-id");
1585
+ if (args[0] !== "list-unmatched-scan-pairs" ||
1586
+ focusedIndex === -1 ||
1587
+ !/unrecognized arguments: --after-scan-id(?:\s+\S+)?$/u.test(processErrorDetail(error)))
1588
+ throw error;
1589
+ options.signal?.throwIfAborted();
1590
+ const legacyArgs = [...args];
1591
+ legacyArgs.splice(focusedIndex, 2);
1592
+ stdout = await run(legacyArgs, input, registrationHandshake);
1593
+ }
1413
1594
  }
1414
1595
  catch (error) {
1415
1596
  if (options.signal?.aborted)
@@ -1430,28 +1611,28 @@ export async function runWorkbench(options, args, input) {
1430
1611
  }
1431
1612
  return result;
1432
1613
  }
1433
- export function bundledPluginCandidates(moduleDirectory) {
1434
- return [
1435
- resolve(moduleDirectory, "_bundled_plugin"),
1436
- resolve(moduleDirectory, "../_bundled_plugin"),
1437
- ];
1438
- }
1439
- export async function bundledPluginRoot() {
1440
- const moduleDirectory = dirname(fileURLToPath(import.meta.url));
1441
- for (const candidate of bundledPluginCandidates(moduleDirectory)) {
1442
- if (await hasPluginManifest(candidate)) {
1443
- return await realpath(candidate);
1614
+ export async function resolveScanOutputPath(outputDirectory, validateTraversalLink) {
1615
+ try {
1616
+ const requested = resolveInputPath(outputDirectory);
1617
+ const path = await resolveParentTraversal(requested, {
1618
+ allowMissing: true,
1619
+ });
1620
+ requireModelSafeOutputDir(path);
1621
+ if (validateTraversalLink && path !== resolve(requested)) {
1622
+ await validateDirectoryLinks(requested, validateTraversalLink);
1444
1623
  }
1624
+ return path;
1625
+ }
1626
+ catch (error) {
1627
+ throw outputInspectionError(outputDirectory, error);
1445
1628
  }
1446
- throw new PluginBootstrapError("The bundled Codex Security plugin is missing.");
1447
1629
  }
1448
- export async function validateOutputDir(outputDirectory, archiveExisting = false) {
1630
+ export async function validateOutputDir(outputDirectory, archiveExisting = false, validateTraversalLink) {
1449
1631
  if (outputDirectory === undefined) {
1450
1632
  return null;
1451
1633
  }
1452
- const path = resolve(expandHome(outputDirectory));
1453
- requireModelSafeOutputDir(path);
1454
1634
  try {
1635
+ const path = await resolveScanOutputPath(outputDirectory, validateTraversalLink);
1455
1636
  const metadata = await lstat(path).catch(nullIfMissingFileError);
1456
1637
  if (metadata !== null) {
1457
1638
  if (!metadata.isDirectory()) {
@@ -1463,7 +1644,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
1463
1644
  requireOutputDirectoryOwnership(metadata, path);
1464
1645
  const writableLeaf = !archiveExisting ||
1465
1646
  (process.platform === "win32" && (await readdir(path)).length === 0);
1466
- const canonical = await checkedOutputPath(path, writableLeaf);
1647
+ const canonical = await checkedOutputPath(path, writableLeaf).catch(rethrowOutputPathValidationError);
1467
1648
  requireModelSafeOutputDir(canonical);
1468
1649
  return canonical;
1469
1650
  }
@@ -1473,7 +1654,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
1473
1654
  if ((await stat(parent)).isDirectory()) {
1474
1655
  const canonical = resolve(await realpath(parent), relative(parent, path));
1475
1656
  requireModelSafeOutputDir(canonical);
1476
- await requireSecureOutputAncestry(canonical);
1657
+ await requireSecureOutputAncestry(canonical).catch(rethrowOutputPathValidationError);
1477
1658
  return canonical;
1478
1659
  }
1479
1660
  break;
@@ -1490,11 +1671,41 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
1490
1671
  throw new OutputDirectoryError(`Unable to create scan output directory: ${path}`);
1491
1672
  }
1492
1673
  catch (error) {
1493
- if (error instanceof OutputDirectoryError)
1494
- throw error;
1495
- throw new OutputDirectoryError(`Unable to inspect scan output directory: ${outputDirectory}`, { cause: error });
1674
+ throw outputInspectionError(outputDirectory, error);
1675
+ }
1676
+ }
1677
+ function outputInspectionError(outputDirectory, cause) {
1678
+ return cause instanceof OutputDirectoryError
1679
+ ? cause
1680
+ : new OutputDirectoryError(`Unable to inspect scan output directory: ${outputDirectory}`, { cause });
1681
+ }
1682
+ /** Check each traversed directory link at its physical location, including linked targets. */
1683
+ export async function validateDirectoryLinks(requested, validateLocation) {
1684
+ const directories = [dirname(requested)];
1685
+ const visited = new Set();
1686
+ while (directories.length > 0) {
1687
+ let directory = directories.pop();
1688
+ while (dirname(directory) !== directory && !visited.has(directory)) {
1689
+ visited.add(directory);
1690
+ if ((await lstat(directory).catch(nullIfMissingFileError))?.isSymbolicLink()) {
1691
+ const parent = await realpath(await resolveParentTraversal(dirname(directory)));
1692
+ validateLocation(join(parent, basename(directory)));
1693
+ directories.push(resolveTargetPath(await readlink(directory), parent));
1694
+ }
1695
+ directory = dirname(directory);
1696
+ }
1496
1697
  }
1497
1698
  }
1699
+ function rethrowOutputPathValidationError(error) {
1700
+ if (process.platform !== "win32" ||
1701
+ nodeErrorCode(error) !== "ERR_DLOPEN_FAILED")
1702
+ throw error;
1703
+ const blocked = error instanceof Error &&
1704
+ /^(?:LoadLibrary failed: )?An Application Control policy has blocked this file\.(?:\s|$)/u.test(error.message);
1705
+ throw new OutputDirectoryError(blocked
1706
+ ? "Windows Application Control blocked the bundled Codex Security filesystem module (windows.node). Check the CodeIntegrity Operational log in Event Viewer."
1707
+ : "Could not load the bundled Codex Security filesystem module (windows.node) on Windows.", { cause: error });
1708
+ }
1498
1709
  export async function prepareScanArtifactRestorer(options, scanDirectory) {
1499
1710
  let helperPath;
1500
1711
  let canonicalPath;
@@ -1570,13 +1781,30 @@ export async function planOutputArchive(outputDirectory) {
1570
1781
  const entries = await readdir(outputDirectory).catch(nullIfMissingFileError);
1571
1782
  if (entries === null || entries.length === 0)
1572
1783
  return null;
1573
- return `${outputDirectory}${outputArchiveSuffix()}`;
1784
+ const id = randomUUID().slice(0, 8);
1785
+ const archive = `${outputDirectory}${outputArchiveSuffix(id)}`;
1786
+ if (process.platform === "win32" || !(await archiveNameTooLong(archive)))
1787
+ return archive;
1788
+ // The workbench reserves a sibling with an eight-character random suffix.
1789
+ const sibling = `${outputDirectory}.previous-${id}`;
1790
+ if (!(await archiveNameTooLong(sibling)))
1791
+ return sibling;
1792
+ return join(dirname(outputDirectory), shortArchivePrefix(basename(outputDirectory)) + id);
1793
+ }
1794
+ async function archiveNameTooLong(path) {
1795
+ try {
1796
+ await lstat(path);
1797
+ return false;
1798
+ }
1799
+ catch (error) {
1800
+ return nodeErrorCode(error) === "ENAMETOOLONG";
1801
+ }
1574
1802
  }
1575
- function outputArchiveSuffix() {
1803
+ function outputArchiveSuffix(id = randomUUID().slice(0, 8)) {
1576
1804
  return `.previous-${new Date()
1577
1805
  .toISOString()
1578
1806
  .replaceAll(/[-:]/g, "")
1579
- .replace(/\.\d{3}Z$/, "")}-${randomUUID().slice(0, 8)}`;
1807
+ .replace(/\.\d{3}Z$/, "")}-${id}`;
1580
1808
  }
1581
1809
  export function requireModelSafeOutputDir(path) {
1582
1810
  if (MODEL_UNSAFE_PATH.test(path)) {
@@ -1594,12 +1822,15 @@ export async function canonicalizeModelSafePath(input) {
1594
1822
  requireModelSafeOutputDir(canonical);
1595
1823
  return canonical;
1596
1824
  }
1597
- export async function canonicalConfigPath(path) {
1825
+ export async function canonicalConfigPath(path, { verifyIdentity = false } = {}) {
1598
1826
  let existing = resolve(path);
1599
1827
  const missing = [];
1600
1828
  while (true) {
1601
1829
  try {
1602
- return join(await realpath(existing), ...missing);
1830
+ const canonical = await realpath(existing);
1831
+ if (verifyIdentity && !(await sameFile(existing, canonical)))
1832
+ throw new InvalidTargetError(`Repository path changed: ${existing}`);
1833
+ return join(canonical, ...missing);
1603
1834
  }
1604
1835
  catch (error) {
1605
1836
  const parent = dirname(existing);
@@ -1619,7 +1850,7 @@ export async function prepareScanRegistrationOutput(outputDirectory, repositoryN
1619
1850
  return prepareOutputDirectory(outputDirectory, repositoryName, temporaryRoot, validateLocation, archiveExisting ? "preserve" : "reject");
1620
1851
  }
1621
1852
  async function prepareOutputDirectory(outputDirectory, repositoryName, temporaryRoot, validateLocation, existingOutput, onOutputArchived) {
1622
- const path = await validateOutputDir(outputDirectory, existingOutput !== "reject");
1853
+ const path = await validateOutputDir(outputDirectory, existingOutput !== "reject", validateLocation);
1623
1854
  if (path === null) {
1624
1855
  requireModelSafeOutputDir(temporaryRoot);
1625
1856
  const canonicalRoot = await realpath(temporaryRoot);
@@ -1636,7 +1867,15 @@ async function prepareOutputDirectory(outputDirectory, repositoryName, temporary
1636
1867
  await createWindowsOutputDirectory(created, false);
1637
1868
  }
1638
1869
  else {
1639
- created = await mkdtemp(join(canonicalRoot, `${prefix}-`));
1870
+ try {
1871
+ created = await mkdtemp(join(canonicalRoot, `${prefix}-`));
1872
+ }
1873
+ catch (error) {
1874
+ if (nodeErrorCode(error) !== "ENAMETOOLONG")
1875
+ throw error;
1876
+ // The repository name itself can fill a filesystem component.
1877
+ created = await mkdtemp(join(canonicalRoot, "codex-security-"));
1878
+ }
1640
1879
  }
1641
1880
  try {
1642
1881
  if ((process.umask() & 0o700) !== 0)
@@ -1897,6 +2136,7 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
1897
2136
  throw error;
1898
2137
  }
1899
2138
  await chmod(destination, 0o600);
2139
+ await rememberStoredFile(isolatedHome);
1900
2140
  return true;
1901
2141
  }
1902
2142
  catch (error) {
@@ -1909,9 +2149,17 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
1909
2149
  }
1910
2150
  }
1911
2151
  export async function extractPluginZip(archive, destination, signal) {
2152
+ return extractValidatedPluginZip(archive, destination, signal);
2153
+ }
2154
+ async function extractValidatedPluginZip(archive, destination, signal, digest) {
1912
2155
  const archivePath = resolve(expandHome(archive));
1913
- await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
1914
- const staging = await realpath(await mkdtemp(join(dirname(destination), ".codex-security-plugin-")));
2156
+ const parent = dirname(destination);
2157
+ await mkdir(parent, { recursive: true, mode: 0o700 });
2158
+ // Windows mkdtemp otherwise fails at 248 UTF-16 units, including its suffix.
2159
+ const stagingParent = process.platform === "win32"
2160
+ ? win32.toNamespacedPath(await realpath(parent))
2161
+ : parent;
2162
+ const staging = await realpath(await mkdtemp(join(stagingParent, ".codex-security-plugin-")));
1915
2163
  let publishingOnWindows = false;
1916
2164
  try {
1917
2165
  throwIfSignalAborted(signal);
@@ -1951,6 +2199,7 @@ export async function extractPluginZip(archive, destination, signal) {
1951
2199
  const output = join(staging, ...path.split("/"));
1952
2200
  const entryMode = (entry.externalFileAttributes >>> 16) & 0xffff;
1953
2201
  const permissions = (entryMode || (directory ? 0o700 : 0o600)) & 0o777;
2202
+ digest?.update(JSON.stringify([path, directory, permissions]));
1954
2203
  await mkdir(directory ? output : dirname(output), {
1955
2204
  recursive: true,
1956
2205
  ...(directory ? { mode: permissions } : {}),
@@ -1971,6 +2220,7 @@ export async function extractPluginZip(archive, destination, signal) {
1971
2220
  if (crc32(bytes) !== checksum) {
1972
2221
  throw new PluginBootstrapError(`Plugin ZIP entry failed CRC-32 validation: ${path}`);
1973
2222
  }
2223
+ digest?.update(createHash("sha256").update(bytes).digest());
1974
2224
  }
1975
2225
  const pluginRoot = await discoverPluginRoot(staging);
1976
2226
  throwIfSignalAborted(signal);
@@ -2076,18 +2326,28 @@ async function openPluginZip(path, signal) {
2076
2326
  }
2077
2327
  }
2078
2328
  export async function resolvePluginPath(pluginPath, workspace, signal) {
2329
+ return (await resolvePluginSource(pluginPath, workspace, signal)).root;
2330
+ }
2331
+ /** @internal */
2332
+ export async function resolvePluginSource(pluginPath, workspace, signal, pinZip = false) {
2079
2333
  try {
2080
2334
  if (pluginPath === undefined) {
2081
- return await bundledPluginRoot();
2335
+ return { root: await bundledPluginRoot() };
2082
2336
  }
2083
2337
  const path = resolve(expandHome(pluginPath));
2084
2338
  const metadata = await lstat(path).catch(() => null);
2085
2339
  if (metadata?.isFile() && extname(path).toLowerCase() === ".zip") {
2086
- return await extractPluginZip(path, join(workspace, "extracted-plugin"), signal);
2340
+ const digest = pinZip ? createHash("sha256") : undefined;
2341
+ const archive = digest ? await realpath(path) : path;
2342
+ const root = await extractValidatedPluginZip(archive, join(workspace, "extracted-plugin"), signal, digest);
2343
+ return {
2344
+ root,
2345
+ ...(digest && { zip: { path: archive, digest: digest.digest("hex") } }),
2346
+ };
2087
2347
  }
2088
2348
  if (metadata?.isDirectory()) {
2089
2349
  throwIfSignalAborted(signal);
2090
- return await validatePluginRoot(path);
2350
+ return { root: await validatePluginRoot(path) };
2091
2351
  }
2092
2352
  throw new PluginBootstrapError(`Plugin path must be a directory or ZIP: ${path}`);
2093
2353
  }
@@ -2097,6 +2357,79 @@ export async function resolvePluginPath(pluginPath, workspace, signal) {
2097
2357
  throw new LocalPluginBootstrapError(errorMessage(error), { cause: error });
2098
2358
  }
2099
2359
  }
2360
+ /** @internal */
2361
+ export async function prepareWindowsScanPluginZip(source, scanDirectory, protectedDirectories, validateLocation, signal) {
2362
+ throwIfSignalAborted(signal);
2363
+ const protectedPath = (path) => protectedDirectories.some((directory) => isWithin(directory, path));
2364
+ if (protectedPath(source.path))
2365
+ return;
2366
+ const metadata = await lstat(source.path).catch(nullIfMissingFileError);
2367
+ if (metadata === null)
2368
+ return;
2369
+ const changed = "The selected plugin ZIP changed after runtime preparation.";
2370
+ if (!metadata.isFile())
2371
+ throw new LocalPluginBootstrapError(changed);
2372
+ const canonicalSource = await realpath(source.path).catch(nullIfMissingFileError);
2373
+ if (canonicalSource === null)
2374
+ return;
2375
+ if (protectedPath(canonicalSource))
2376
+ throw new LocalPluginBootstrapError(changed);
2377
+ let workspace;
2378
+ const parents = [...new Set([dirname(scanDirectory), tmpdir()])].filter((parent) => !protectedPath(parent) && !isWithin(scanDirectory, parent));
2379
+ // PowerShell may fail to launch the selected plugin's .cmd at a long path.
2380
+ // Prefer the shorter canonical parent, retaining the output parent on ties.
2381
+ const candidates = await abortable(() => Promise.allSettled(parents.map((path) => realpath(path))), signal);
2382
+ const length = (candidate) => candidate.status === "fulfilled" ? candidate.value.length : Infinity;
2383
+ for (const candidate of candidates.sort((a, b) => length(a) - length(b))) {
2384
+ throwIfSignalAborted(signal);
2385
+ try {
2386
+ if (candidate.status === "rejected")
2387
+ throw candidate.reason;
2388
+ const canonical = candidate.value;
2389
+ if (protectedPath(canonical) || isWithin(scanDirectory, canonical))
2390
+ continue;
2391
+ // Host-side plugin helpers may execute from this copy. A sibling keeps it
2392
+ // outside the writable scan, and the native creator verifies its parents.
2393
+ workspace = await prepareOutputDir(undefined, "plugin-input", canonical, validateLocation);
2394
+ break;
2395
+ }
2396
+ catch (error) {
2397
+ if (!(error instanceof OutputDirectoryError) &&
2398
+ !["EACCES", "EPERM", "ENOENT"].includes(nodeErrorCode(error) ?? ""))
2399
+ throw error;
2400
+ }
2401
+ }
2402
+ // Keep existing plugin handling where neither scan input location is usable.
2403
+ if (workspace === undefined)
2404
+ return;
2405
+ try {
2406
+ throwIfSignalAborted(signal);
2407
+ const digest = createHash("sha256");
2408
+ const root = await extractValidatedPluginZip(source.path, join(workspace, "plugin"), signal, digest);
2409
+ throwIfSignalAborted(signal);
2410
+ if (digest.digest("hex") !== source.digest) {
2411
+ throw new LocalPluginBootstrapError(changed);
2412
+ }
2413
+ return { workspace, root };
2414
+ }
2415
+ catch (error) {
2416
+ try {
2417
+ await cleanupSdkDirectory(workspace);
2418
+ }
2419
+ catch (cleanupError) {
2420
+ throwIfSignalAborted(signal);
2421
+ throw new LocalPluginBootstrapError(`${errorMessage(error)}\nCould not remove scan input directory ${workspace}: ${errorMessage(cleanupError)}`, { cause: error });
2422
+ }
2423
+ throwIfSignalAborted(signal);
2424
+ const cause = error instanceof PluginBootstrapError ? error.cause : undefined;
2425
+ if (isRecord(cause) &&
2426
+ cause["code"] === "ENOENT" &&
2427
+ cause["syscall"] === "open" &&
2428
+ cause["path"] === source.path)
2429
+ return;
2430
+ throw error;
2431
+ }
2432
+ }
2100
2433
  export async function createMarketplace(codexHome, pluginRoot, signal) {
2101
2434
  try {
2102
2435
  throwIfSignalAborted(signal);
@@ -2149,6 +2482,20 @@ async function writeMarketplaceManifest(marketplace, signal) {
2149
2482
  await rm(temporary, { force: true });
2150
2483
  }
2151
2484
  }
2485
+ // Private handoff to the staged SDK launcher and shell-invoked helpers.
2486
+ export const SDK_NODE_SEARCH_PATH = "_CODEX_SECURITY_SDK_NODE_SEARCH_PATH";
2487
+ export async function sdkNodeSearchPath(roots) {
2488
+ let fallback = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin";
2489
+ const current = dirname(process.execPath);
2490
+ if (process.release.name === "node" &&
2491
+ !process.versions["bun"] &&
2492
+ !process.versions["electron"] &&
2493
+ basename(process.execPath) === "node" &&
2494
+ !current.includes(":"))
2495
+ fallback += `:${current}`;
2496
+ const inspected = await inspectTrustedExecutable("node", { PATH: fallback }, roots);
2497
+ return inspected.environment["PATH"] ?? "";
2498
+ }
2152
2499
  async function pluginRuntimeProjection(root, signal) {
2153
2500
  const path = join(root, ".mcp.json");
2154
2501
  // Keep the source link checks ahead of any configuration read.
@@ -2167,13 +2514,10 @@ async function pluginRuntimeProjection(root, signal) {
2167
2514
  const environment = server["env_vars"];
2168
2515
  if (environment !== undefined && !Array.isArray(environment))
2169
2516
  return;
2170
- if (!Array.isArray(environment) ||
2171
- !environment.includes("CODEX_SECURITY_PLUGIN_ROOT")) {
2172
- server["env_vars"] = [
2173
- ...(Array.isArray(environment) ? environment : []),
2174
- "CODEX_SECURITY_PLUGIN_ROOT",
2175
- ];
2176
- }
2517
+ server["env_vars"] = [
2518
+ ...(environment ?? []),
2519
+ ...["CODEX_SECURITY_PLUGIN_ROOT", "CODEX_SECURITY_REPOSITORY"].filter((name) => !environment?.includes(name)),
2520
+ ];
2177
2521
  const files = new Map();
2178
2522
  server["command"] =
2179
2523
  server["command"] === "./scripts/launch_codex_security_mcp.cmd"
@@ -2184,7 +2528,7 @@ async function pluginRuntimeProjection(root, signal) {
2184
2528
  'if [ -n "${CODEX_SECURITY_PLUGIN_ROOT:-}" ]; then\n' +
2185
2529
  ' exec "$CODEX_SECURITY_PLUGIN_ROOT/scripts/launch_codex_security_mcp" "$@"\n' +
2186
2530
  "fi\n" +
2187
- 'exec "$(dirname "$0")/launch_codex_security_mcp" "$@"\n'),
2531
+ 'exec "$(command -p dirname "$0")/launch_codex_security_mcp" "$@"\n'),
2188
2532
  mode: 0o755,
2189
2533
  });
2190
2534
  files.set("scripts/launch_codex_security_mcp_sdk.cmd", {
@@ -2201,10 +2545,10 @@ async function pluginRuntimeProjection(root, signal) {
2201
2545
  return { root, files };
2202
2546
  }
2203
2547
  export function resolveCodexCommand(environment = process.env) {
2204
- const configured = environmentValue(environment, "CODEX_CLI_PATH");
2548
+ const configured = configuredExecutableValue(environmentValue(environment, "CODEX_CLI_PATH", true), process.platform, (value) => isExecutableFile(expandHomeForLookup(value, environment)));
2205
2549
  const expanded = configured === undefined
2206
2550
  ? undefined
2207
- : expandExecutableHome(configured, environment);
2551
+ : expandHomeForLookup(configured, environment);
2208
2552
  if (expanded &&
2209
2553
  (process.platform !== "win32" || /\.(?:exe|com)$/iu.test(expanded))) {
2210
2554
  return {
@@ -2265,8 +2609,22 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2265
2609
  ? null
2266
2610
  : await pluginMetadata(join(marketplace, "plugins", PLUGIN_NAME)).catch(() => null);
2267
2611
  const stagedRoot = join(marketplace, "plugins", PLUGIN_NAME);
2268
- const stagedMatches = staged?.version === version &&
2269
- (await pluginContentsMatch(root, stagedRoot, options.signal, false, projection));
2612
+ const matchesSelected = (destination, allowExtraFiles = false, generatedDirectory) => pluginContentsMatch(root, destination, options.signal, allowExtraFiles, projection, generatedDirectory);
2613
+ const stagedMatches = staged?.version === version && (await matchesSelected(stagedRoot));
2614
+ const matchesNativeInstall = async (installedRoot, allowRuntimeFiles = false) => (await matchesSelected(stagedRoot)) &&
2615
+ // Ordinary reuse permits runtime files when all selected bytes are present.
2616
+ // The native receipt still verifies the complete generated command output.
2617
+ ((allowRuntimeFiles && (await matchesSelected(installedRoot, true))) ||
2618
+ (await matchesSelected(installedRoot, false, migratedCommands(installedRoot))));
2619
+ const nativeMigration = (installedRoot, allowRuntimeFiles = false) => verifiedCommandMigration(installedRoot, (path) => matchesNativeInstall(path, allowRuntimeFiles), options.signal);
2620
+ const matchesReceipt = async (installedRoot, migration) => {
2621
+ if (typeof migration === "string" &&
2622
+ options.runCodex === undefined &&
2623
+ (await isBundledPluginInstaller(command))) {
2624
+ return (await nativeMigration(installedRoot, true)) === migration;
2625
+ }
2626
+ return matchesSelected(installedRoot, true);
2627
+ };
2270
2628
  if (!stagedMatches) {
2271
2629
  if (existing !== null) {
2272
2630
  await rm(marketplace, { recursive: true, force: true });
@@ -2324,7 +2682,7 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2324
2682
  isRecord(previous) &&
2325
2683
  typeof previous["installedPath"] === "string" &&
2326
2684
  previous["version"] === version &&
2327
- (await pluginContentsMatch(root, previous["installedPath"], options.signal, true, projection))) {
2685
+ (await matchesReceipt(previous["installedPath"], previous["nativeCommandMigration"]))) {
2328
2686
  return {
2329
2687
  pluginRoot: root,
2330
2688
  marketplaceRoot: marketplace,
@@ -2334,7 +2692,35 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2334
2692
  version,
2335
2693
  };
2336
2694
  }
2337
- const output = await run(command, ["plugin", "add", "--json", `${PLUGIN_NAME}@${MARKETPLACE_NAME}`], environment, options.signal);
2695
+ const addPlugin = () => run(command, ["plugin", "add", "--json", `${PLUGIN_NAME}@${MARKETPLACE_NAME}`], environment, options.signal);
2696
+ let output;
2697
+ let retried = false;
2698
+ try {
2699
+ output = await addPlugin();
2700
+ }
2701
+ catch (first) {
2702
+ if (!isRolledBackPluginActivation(first))
2703
+ throw first;
2704
+ throwIfSignalAborted(options.signal);
2705
+ if (!(await isBundledPluginInstaller(command)))
2706
+ throw first;
2707
+ // The bundled CLI restored the old cache. A short-lived Windows reader
2708
+ // of the new tree can release it before a fresh installation attempt.
2709
+ try {
2710
+ await delay(100, undefined, { signal: options.signal });
2711
+ throwIfSignalAborted(options.signal);
2712
+ if (!(await matchesSelected(stagedRoot))) {
2713
+ throw new LocalPluginBootstrapError("The selected plugin or its marketplace changed before the native installation could be retried.", { cause: first });
2714
+ }
2715
+ throwIfSignalAborted(options.signal);
2716
+ output = await addPlugin();
2717
+ retried = true;
2718
+ }
2719
+ catch (second) {
2720
+ throwIfSignalAborted(options.signal);
2721
+ throw isRolledBackPluginActivation(second) ? first : second;
2722
+ }
2723
+ }
2338
2724
  let installed;
2339
2725
  try {
2340
2726
  installed = JSON.parse(output);
@@ -2347,9 +2733,25 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2347
2733
  installed["version"] !== version) {
2348
2734
  throw new PluginBootstrapError("Codex plugin install did not return the selected plugin path and version.");
2349
2735
  }
2736
+ // The bundled installer removes stale command skills before regenerating them.
2737
+ const bundledInstaller = retried ||
2738
+ (options.runCodex === undefined &&
2739
+ (await isBundledPluginInstaller(command)));
2740
+ const hasSourceMigration = bundledInstaller &&
2741
+ (await lstat(migratedCommands(root)).catch(nullIfMissingFileError))?.isDirectory() === true;
2742
+ const nativeCommandMigration = hasSourceMigration
2743
+ ? await nativeMigration(installed["installedPath"])
2744
+ : undefined;
2745
+ if (retried &&
2746
+ !(hasSourceMigration
2747
+ ? nativeCommandMigration !== undefined
2748
+ : await matchesNativeInstall(installed["installedPath"]))) {
2749
+ throw new PluginBootstrapError("The retried Codex plugin install did not install the selected plugin contents.");
2750
+ }
2350
2751
  await writeFile(installRecord, JSON.stringify({
2351
2752
  installedPath: installed["installedPath"],
2352
2753
  version,
2754
+ ...(nativeCommandMigration ? { nativeCommandMigration } : {}),
2353
2755
  }), { mode: 0o600, signal: options.signal });
2354
2756
  return {
2355
2757
  pluginRoot: root,
@@ -2360,7 +2762,92 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2360
2762
  version,
2361
2763
  };
2362
2764
  }
2363
- async function pluginContentsMatch(source, destination, signal, allowExtraFiles = false, projection) {
2765
+ async function isBundledPluginInstaller(command) {
2766
+ try {
2767
+ return await sameFile(command.command, resolveBundledCodexExecutable());
2768
+ }
2769
+ catch {
2770
+ return false;
2771
+ }
2772
+ }
2773
+ function migratedCommands(plugin) {
2774
+ return join(plugin, ".codex-plugin", "migrated-command-skills");
2775
+ }
2776
+ // Bind a receipt to the generated files observed in this installation.
2777
+ // Entry names come from its directories, never from the saved digest.
2778
+ async function verifiedCommandMigration(installedRoot, matchesSelected, signal) {
2779
+ const digest = createHash("sha256");
2780
+ const record = (...fields) => digest.update(JSON.stringify(fields)).update("\n");
2781
+ async function visit(path, name) {
2782
+ throwIfSignalAborted(signal);
2783
+ const metadata = await lstat(path, { bigint: true });
2784
+ if (metadata.isSymbolicLink() ||
2785
+ relative(path, await realpath(path)) !== "")
2786
+ return false;
2787
+ if (metadata.isDirectory()) {
2788
+ record("directory", name);
2789
+ for (const entry of (await readdir(path)).sort()) {
2790
+ const child = join(path, entry);
2791
+ if (!(await visit(child, name ? `${name}/${entry}` : entry)))
2792
+ return false;
2793
+ }
2794
+ return sameInode(metadata, await lstat(path, { bigint: true }));
2795
+ }
2796
+ if (!metadata.isFile())
2797
+ return false;
2798
+ const file = await open(path, constants.O_RDONLY |
2799
+ (constants.O_NOFOLLOW ?? 0) |
2800
+ (constants.O_NONBLOCK ?? 0));
2801
+ try {
2802
+ const opened = await file.stat({ bigint: true });
2803
+ if (!opened.isFile())
2804
+ return false;
2805
+ if (!sameInode(metadata, opened)) {
2806
+ if (process.platform !== "win32")
2807
+ return false;
2808
+ // Some Windows Node versions report a different device on an open handle.
2809
+ const { sameCheckedFileDevice } = await import("./contract.js");
2810
+ if (!(await sameCheckedFileDevice(file, { path, metadata }, opened)))
2811
+ return false;
2812
+ }
2813
+ const contents = createHash("sha256")
2814
+ .update(await file.readFile({ signal }))
2815
+ .digest("hex");
2816
+ record("file", name, Number(opened.mode & 73n), contents);
2817
+ }
2818
+ finally {
2819
+ await file.close();
2820
+ }
2821
+ return true;
2822
+ }
2823
+ throwIfSignalAborted(signal);
2824
+ const installation = await lstat(installedRoot, { bigint: true }).catch(nullIfMissingFileError);
2825
+ if (!installation?.isDirectory() ||
2826
+ installation.ino === 0n ||
2827
+ !(await matchesSelected(installedRoot)))
2828
+ return;
2829
+ try {
2830
+ const directory = migratedCommands(await realpath(installedRoot));
2831
+ const parent = dirname(directory);
2832
+ if (!(await lstat(parent)).isDirectory() ||
2833
+ relative(parent, await realpath(parent)) !== "")
2834
+ return;
2835
+ const root = await lstat(directory, { bigint: true }).catch(nullIfMissingFileError);
2836
+ if (root && (!root.isDirectory() || !(await visit(directory, ""))))
2837
+ return;
2838
+ // Native activation replaces the installed directory even at the same version.
2839
+ if (!sameInode(installation, await lstat(installedRoot, { bigint: true })))
2840
+ return;
2841
+ throwIfSignalAborted(signal);
2842
+ return root ? `sha256:${digest.digest("hex")}` : "absent";
2843
+ }
2844
+ catch (error) {
2845
+ throwIfSignalAborted(signal);
2846
+ if (!["ENOENT", "ENOTDIR", "ELOOP", "EISDIR", "EACCES", "EPERM"].includes(nodeErrorCode(error) ?? ""))
2847
+ throw error;
2848
+ }
2849
+ }
2850
+ async function pluginContentsMatch(source, destination, signal, allowExtraFiles = false, projection, generatedDirectory) {
2364
2851
  throwIfSignalAborted(signal);
2365
2852
  const sourceMetadata = await lstat(source);
2366
2853
  const destinationMetadata = await lstat(destination).catch((error) => {
@@ -2389,15 +2876,39 @@ async function pluginContentsMatch(source, destination, signal, allowExtraFiles
2389
2876
  if (!sourceMetadata.isDirectory() || !destinationMetadata.isDirectory()) {
2390
2877
  return false;
2391
2878
  }
2392
- const entries = await readdir(source);
2879
+ let entries = await readdir(source);
2880
+ let nativeOutputs = 0;
2881
+ if (generatedDirectory) {
2882
+ const parent = dirname(generatedDirectory);
2883
+ if (parent === destination ||
2884
+ (relative(parent, destination) === "" &&
2885
+ (await sameFile(parent, destination)))) {
2886
+ // The installer removes old command output before regenerating it. Resolve
2887
+ // its source spelling on volumes that preserve case but ignore it on lookup.
2888
+ const path = join(source, basename(generatedDirectory));
2889
+ const original = await lstat(path).catch(nullIfMissingFileError);
2890
+ if (original?.isSymbolicLink())
2891
+ return false;
2892
+ if (original) {
2893
+ const name = basename(await realpath(path));
2894
+ entries = entries.filter((entry) => entry !== name);
2895
+ }
2896
+ const installed = await lstat(generatedDirectory).catch(nullIfMissingFileError);
2897
+ if (installed) {
2898
+ if (!installed.isDirectory())
2899
+ return false;
2900
+ nativeOutputs = 1;
2901
+ }
2902
+ }
2903
+ }
2393
2904
  const projectedDirectory = projection === undefined
2394
2905
  ? undefined
2395
2906
  : relative(projection.root, source).split(sep).join("/") || ".";
2396
2907
  const generated = [...(projection?.files ?? [])].filter(([path]) => dirname(path) === projectedDirectory && !entries.includes(basename(path)));
2397
2908
  if (!allowExtraFiles &&
2398
- entries.length + generated.length !== (await readdir(destination)).length) {
2909
+ entries.length + generated.length + nativeOutputs !==
2910
+ (await readdir(destination)).length)
2399
2911
  return false;
2400
- }
2401
2912
  for (const [path, file] of generated) {
2402
2913
  const generatedPath = join(destination, basename(path));
2403
2914
  const metadata = await lstat(generatedPath).catch(nullIfMissingFileError);
@@ -2409,7 +2920,7 @@ async function pluginContentsMatch(source, destination, signal, allowExtraFiles
2409
2920
  }
2410
2921
  }
2411
2922
  for (const entry of entries) {
2412
- if (!(await pluginContentsMatch(join(source, entry), join(destination, entry), signal, allowExtraFiles, projection))) {
2923
+ if (!(await pluginContentsMatch(join(source, entry), join(destination, entry), signal, allowExtraFiles, projection, generatedDirectory))) {
2413
2924
  return false;
2414
2925
  }
2415
2926
  }
@@ -2440,12 +2951,10 @@ export async function pluginMetadata(root) {
2440
2951
  }
2441
2952
  export async function resolvePluginPython(options = {}) {
2442
2953
  const environment = options.environment ?? process.env;
2443
- const requestedRoots = options.protectedRoot ?? process.cwd();
2954
+ const cwd = process.cwd();
2955
+ const requestedRoots = options.protectedRoot ?? cwd;
2444
2956
  const protectedRoot = typeof requestedRoots === "string" ? [requestedRoots] : [...requestedRoots];
2445
- const callerDirectories = [
2446
- process.cwd(),
2447
- options.currentDirectory ?? process.cwd(),
2448
- ];
2957
+ const callerDirectories = new Set([cwd, options.currentDirectory ?? cwd]);
2449
2958
  // Preserve target and enclosing-checkout protection for every interpreter.
2450
2959
  for (const directory of new Set([...callerDirectories, ...protectedRoot])) {
2451
2960
  for (const checkout of await gitProtectionRoots(directory, options.signal))
@@ -2454,20 +2963,59 @@ export async function resolvePluginPython(options = {}) {
2454
2963
  }
2455
2964
  // Named interpreters are ambient PATH discovery, even when PYTHON names one.
2456
2965
  // Explicit trusted paths and managed runtimes retain their existing precedence.
2457
- const discoveryRoots = [...protectedRoot, ...callerDirectories];
2966
+ const discoveryRoots = [
2967
+ ...protectedRoot,
2968
+ ...(options.discoveryProtectedRoots ?? []),
2969
+ ];
2970
+ for (const directory of callerDirectories) {
2971
+ const physical = directory === cwd
2972
+ ? cwd
2973
+ : await realpath(directory).catch(() => undefined);
2974
+ // A filesystem-root launch directory also contains the operator's installed tools.
2975
+ // Explicit scan roots and enclosing checkouts are already in protectedRoot.
2976
+ if (protectedRoot.length === 0 ||
2977
+ physical === undefined ||
2978
+ dirname(physical) !== physical)
2979
+ discoveryRoots.push(directory);
2980
+ }
2981
+ const missingBoundaryMessage = "Could not establish the saved checkout boundary for Python discovery. Set PYTHON to an absolute trusted interpreter.";
2458
2982
  if (options.configuredPath !== undefined) {
2983
+ if (!isPythonPathCandidate(options.configuredPath) &&
2984
+ options.allowPathLookup === false)
2985
+ throw new PluginPythonUnavailableError(missingBoundaryMessage);
2459
2986
  return await requirePython(options.configuredPath, "configured plugin Python", environment, isPythonPathCandidate(options.configuredPath)
2460
2987
  ? protectedRoot
2461
2988
  : discoveryRoots, options.signal);
2462
2989
  }
2463
- const inherited = environmentValue(environment, "PYTHON");
2990
+ const inherited = environmentValue(environment, "PYTHON", true);
2464
2991
  if (inherited) {
2465
- return await requirePython(inherited, "PYTHON", environment, isPythonPathCandidate(inherited) ? protectedRoot : discoveryRoots, options.signal);
2992
+ if (!isPythonPathCandidate(inherited) && options.allowPathLookup === false)
2993
+ throw new PluginPythonUnavailableError(missingBoundaryMessage);
2994
+ const roots = isPythonPathCandidate(inherited)
2995
+ ? protectedRoot
2996
+ : discoveryRoots;
2997
+ // Check an explicit literal path with the same repository protections as the launch.
2998
+ const candidate = isExplicitPathWithTrailingWhitespace(inherited, process.platform) &&
2999
+ (await resolveTrustedExecutable(expandHomeForLookup(inherited, environment), environment, roots))
3000
+ ? inherited
3001
+ : inherited.trim();
3002
+ return await requirePython(candidate, "PYTHON", environment, roots, options.signal);
3003
+ }
3004
+ let managedRoots = options.managedRuntimeRoots;
3005
+ if (managedRoots === undefined) {
3006
+ try {
3007
+ const cache = environmentValue(environment, "XDG_CACHE_HOME", true) ||
3008
+ join(options.homeDirectory ?? homedir(), ".cache");
3009
+ managedRoots = [join(cache, "codex-runtimes", "codex-primary-runtime")];
3010
+ }
3011
+ catch (error) {
3012
+ // A numeric Linux UID can lack a home for the optional managed cache.
3013
+ if (process.platform !== "linux" ||
3014
+ error.info?.code !== "ENOENT")
3015
+ throw error;
3016
+ managedRoots = [];
3017
+ }
2466
3018
  }
2467
- const managedRoots = options.managedRuntimeRoots ?? [
2468
- join(environmentValue(environment, "XDG_CACHE_HOME", true) ||
2469
- join(options.homeDirectory ?? homedir(), ".cache"), "codex-runtimes", "codex-primary-runtime"),
2470
- ];
2471
3019
  const relativeCandidates = process.platform === "win32"
2472
3020
  ? [
2473
3021
  join("dependencies", "python", "python.exe"),
@@ -2486,6 +3034,8 @@ export async function resolvePluginPython(options = {}) {
2486
3034
  return resolved;
2487
3035
  }
2488
3036
  }
3037
+ if (options.allowPathLookup === false)
3038
+ throw new PluginPythonUnavailableError(missingBoundaryMessage);
2489
3039
  for (const candidate of process.platform === "win32"
2490
3040
  ? ["python", "python3", "py"]
2491
3041
  : ["python3", "python"]) {
@@ -2543,35 +3093,46 @@ export function isDisconnectedChildStdin(error) {
2543
3093
  "ERR_STREAM_DESTROYED",
2544
3094
  ].includes(error.code ?? "");
2545
3095
  }
2546
- export async function runCodexCommand(command, args, environment, input, signal, archiveHandshake = false, stdinPrefix) {
2547
- const cancellation = archiveHandshake ? new AbortController() : undefined;
3096
+ export async function runCodexCommand(command, args, environment, input, launchSignal, { registrationHandshake = false, stdinPrefix, cwd, } = {}) {
3097
+ const campaign = campaignExecutable(command.command, environment);
3098
+ const selected = campaign && (await campaign);
3099
+ const executable = selected?.executable ?? command.command;
3100
+ const commandArgs = typeof args === "function" ? args(executable) : args;
3101
+ const signal = typeof launchSignal === "function" ? launchSignal() : launchSignal;
3102
+ const cancellation = registrationHandshake
3103
+ ? new AbortController()
3104
+ : undefined;
2548
3105
  const abort = () => cancellation?.abort(signal?.reason);
2549
3106
  const commandSignal = cancellation?.signal ?? signal;
2550
- let awaitingArchive = archiveHandshake;
2551
- const child = spawn(executablePathForSpawn(command.command), [...(command.args ?? []), ...args], {
2552
- env: environment,
2553
- stdio: ["pipe", "pipe", "pipe"],
3107
+ const child = spawn(executablePathForSpawn(executable), [...(command.args ?? []), ...commandArgs], {
3108
+ cwd,
3109
+ env: selected?.environment ?? environment,
3110
+ stdio: registrationHandshake
3111
+ ? ["pipe", "pipe", "pipe", "pipe"]
3112
+ : ["pipe", "pipe", "pipe"],
2554
3113
  windowsHide: true,
2555
3114
  signal: commandSignal,
2556
3115
  });
2557
3116
  let stdout = "";
2558
3117
  let stderr = "";
2559
3118
  let processError;
3119
+ const control = child.stdio[3];
3120
+ control?.once("data", () => {
3121
+ // The helper cannot change the output until the host allows the transaction.
3122
+ signal?.removeEventListener("abort", abort);
3123
+ if (signal?.aborted)
3124
+ abort();
3125
+ else
3126
+ control.end("!");
3127
+ });
3128
+ control?.on("error", (error) => {
3129
+ if (!isDisconnectedChildStdin(error))
3130
+ processError = error;
3131
+ });
2560
3132
  child.stdout.setEncoding("utf8");
2561
3133
  child.stderr.setEncoding("utf8");
2562
3134
  child.stdout.on("data", (chunk) => {
2563
3135
  stdout += chunk;
2564
- if (awaitingArchive && stdout.startsWith(ARCHIVE_READY)) {
2565
- awaitingArchive = false;
2566
- stdout = stdout.slice(ARCHIVE_READY.length);
2567
- signal?.removeEventListener("abort", abort);
2568
- // The helper cannot rename until this acknowledgement. Detach and check
2569
- // cancellation before allowing the filesystem/database transaction.
2570
- if (signal?.aborted)
2571
- abort();
2572
- else
2573
- child.stdin.end("\n");
2574
- }
2575
3136
  });
2576
3137
  child.stderr.on("data", (chunk) => {
2577
3138
  stderr += chunk;
@@ -2600,12 +3161,13 @@ export async function runCodexCommand(command, args, environment, input, signal,
2600
3161
  child.stdin.destroy();
2601
3162
  child.stdout.destroy();
2602
3163
  child.stderr.destroy();
3164
+ control?.destroy();
2603
3165
  };
2604
3166
  commandSignal?.addEventListener("abort", settleCanceledChild, { once: true });
2605
3167
  child.once("exit", settleCanceledChild);
2606
3168
  if (commandSignal?.aborted)
2607
3169
  settleCanceledChild();
2608
- if (archiveHandshake) {
3170
+ if (registrationHandshake) {
2609
3171
  signal?.addEventListener("abort", abort, { once: true });
2610
3172
  if (signal?.aborted)
2611
3173
  abort();
@@ -2613,15 +3175,13 @@ export async function runCodexCommand(command, args, environment, input, signal,
2613
3175
  try {
2614
3176
  if (stdinPrefix !== undefined)
2615
3177
  child.stdin.write(stdinPrefix);
2616
- if (archiveHandshake)
2617
- child.stdin.write(`${JSON.stringify(input ?? "")}\n`);
2618
- else
2619
- child.stdin.end(input);
3178
+ child.stdin.end(input);
2620
3179
  return await completion;
2621
3180
  }
2622
3181
  finally {
2623
- if (archiveHandshake)
3182
+ if (registrationHandshake)
2624
3183
  signal?.removeEventListener("abort", abort);
3184
+ control?.destroy();
2625
3185
  clearTimeout(forceTermination);
2626
3186
  commandSignal?.removeEventListener("abort", settleCanceledChild);
2627
3187
  child.removeListener("exit", settleCanceledChild);
@@ -2632,11 +3192,24 @@ export async function probeCodexSandbox(command, environment, signal) {
2632
3192
  if (process.platform === "win32")
2633
3193
  return;
2634
3194
  // Reuse the resolved Codex executable instead of looking up a probe on PATH.
2635
- const args = ["sandbox", "--", command.command, "--version"];
2636
- const timeout = AbortSignal.timeout(SANDBOX_PROBE_TIMEOUT_MILLISECONDS);
3195
+ const args = (executable) => [
3196
+ "sandbox",
3197
+ "--",
3198
+ executable,
3199
+ "--version",
3200
+ ];
3201
+ signal?.throwIfAborted();
3202
+ let timeout;
2637
3203
  let detail;
2638
3204
  try {
2639
- const result = await runCodexCommand(command, args, environment, undefined, signal === undefined ? timeout : AbortSignal.any([signal, timeout]));
3205
+ const result = await runCodexCommand(command, args, environment, undefined, () => {
3206
+ // Campaign tool selection happens before the sandbox process starts.
3207
+ signal?.throwIfAborted();
3208
+ timeout = AbortSignal.timeout(SANDBOX_PROBE_TIMEOUT_MILLISECONDS);
3209
+ return signal === undefined
3210
+ ? timeout
3211
+ : AbortSignal.any([signal, timeout]);
3212
+ });
2640
3213
  if (result.success)
2641
3214
  return;
2642
3215
  detail =
@@ -2646,22 +3219,49 @@ export async function probeCodexSandbox(command, environment, signal) {
2646
3219
  }
2647
3220
  catch (error) {
2648
3221
  signal?.throwIfAborted();
2649
- if (timeout.aborted)
3222
+ if (timeout?.aborted)
2650
3223
  throw new SandboxUnavailableError(`Codex sandbox probe timed out after ${SANDBOX_PROBE_TIMEOUT_MILLISECONDS / 1000} seconds.`, { cause: error });
2651
3224
  detail = processErrorDetail(error);
2652
3225
  }
2653
3226
  const guidance = process.platform === "linux"
2654
3227
  ? "\nOn Linux this usually means unprivileged user namespaces are restricted (kernel.apparmor_restrict_unprivileged_userns=1 on Ubuntu 24.04 and later), which Bubblewrap needs; inside the container image, use the AppArmor profile and Compose override from the SDK README."
2655
3228
  : "";
2656
- throw new SandboxUnavailableError(`Codex could not run a command in its sandbox: ${detail}\nTo reproduce, run '${command.command} ${args.join(" ")}'.${guidance}`);
3229
+ throw new SandboxUnavailableError(`Codex could not run a command in its sandbox: ${detail}\nTo reproduce, run '${command.command} ${args(command.command).join(" ")}'.${guidance}`);
3230
+ }
3231
+ class RolledBackPluginActivationError extends Error {
3232
+ }
3233
+ function isRolledBackPluginActivation(error) {
3234
+ return (error instanceof PluginBootstrapError &&
3235
+ error.cause instanceof RolledBackPluginActivationError);
2657
3236
  }
2658
3237
  async function runPluginCommand(command, args, environment, signal) {
2659
3238
  try {
2660
- const { success, exitCode, stdout, stderr } = await runCodexCommand(command, args, environment, undefined, signal);
3239
+ const run = (argv, cwd) => runCodexCommand(command, argv, environment, undefined, signal, { cwd });
3240
+ let result = await run(args);
3241
+ const source = args[1] === "marketplace" ? args[3] : undefined;
3242
+ if (result.exitCode === 1 &&
3243
+ source?.includes("#") &&
3244
+ result.stderr
3245
+ .split(/\r?\n/u)
3246
+ .includes("Error: --ref is only supported for git marketplace sources")) {
3247
+ // Native Codex parsed a literal hash in the local path as a Git ref.
3248
+ result = await run(["plugin", "marketplace", "add", "."], source);
3249
+ }
3250
+ const { success, exitCode, stdout, stderr } = result;
2661
3251
  if (!success) {
2662
- throw new Error(stderr.trim() ||
3252
+ const detail = stderr.trim() ||
2663
3253
  stdout.trim() ||
2664
- `Codex exited with status ${exitCode}.`);
3254
+ `Codex exited with status ${exitCode}.`;
3255
+ // This native headline is emitted only after the previous entry was
3256
+ // restored. The Windows message itself may be localized.
3257
+ if (process.platform === "win32" &&
3258
+ args[0] === "plugin" &&
3259
+ args[1] === "add" &&
3260
+ exitCode === 1 &&
3261
+ /^Error: failed to activate updated plugin cache entry: [^\r\n]+ \(os error 5\)(?:\r?\n|$)/u.test(stderr) &&
3262
+ !stderr.includes("failed to restore previous cache entry"))
3263
+ throw new RolledBackPluginActivationError(detail);
3264
+ throw new Error(detail);
2665
3265
  }
2666
3266
  return stdout;
2667
3267
  }
@@ -2749,7 +3349,7 @@ async function requirePython(candidate, source, environment, protectedRoot, sign
2749
3349
  }
2750
3350
  async function usablePython(candidate, environment = process.env, protectedRoot = process.cwd(), signal) {
2751
3351
  const command = await resolveTrustedExecutable(isPythonPathCandidate(candidate)
2752
- ? expandExecutableHome(candidate, environment)
3352
+ ? expandHomeForLookup(candidate, environment)
2753
3353
  : candidate, environment, protectedRoot);
2754
3354
  if (command === null)
2755
3355
  return null;
@@ -2772,9 +3372,6 @@ async function usablePython(candidate, environment = process.env, protectedRoot
2772
3372
  export function isPythonPathCandidate(candidate) {
2773
3373
  return candidate.includes("/") || candidate.includes("\\");
2774
3374
  }
2775
- async function hasPluginManifest(root) {
2776
- return await lstat(join(root, ".codex-plugin", "plugin.json")).then((metadata) => metadata.isFile(), () => false);
2777
- }
2778
3375
  /** @internal Compare filesystem identity without depending on path spelling. */
2779
3376
  export function sameFile(left, right) {
2780
3377
  // NTFS file IDs can exceed JavaScript's safe integer range.
@@ -2783,7 +3380,39 @@ export function sameFile(left, right) {
2783
3380
  stat(right, { bigint: true }),
2784
3381
  ]).then(([leftMetadata, rightMetadata]) => sameInode(leftMetadata, rightMetadata), () => false);
2785
3382
  }
2786
- function expandExecutableHome(value, environment) {
3383
+ export function resolveInputPath(value, directory = process.cwd(), environment = process.env) {
3384
+ if (value === "~")
3385
+ value = expandHome("~", environment);
3386
+ else if (value.startsWith("~/") || value.startsWith("~\\")) {
3387
+ const home = expandHome("~", environment);
3388
+ const suffix = value.startsWith("~\\")
3389
+ ? value.slice(2).split("\\").filter(Boolean).join(sep)
3390
+ : value.slice(2);
3391
+ value = home === "" ? suffix : `${home}${sep}${suffix}`;
3392
+ }
3393
+ return resolveTargetPath(value, directory);
3394
+ }
3395
+ /** Resolve through the last parent traversal while retaining aliases in the remaining path. */
3396
+ export async function resolveParentTraversal(path, { allowMissing = false } = {}) {
3397
+ const parts = path.split(sep);
3398
+ const parent = parts.lastIndexOf("..");
3399
+ if (parent === -1)
3400
+ return path;
3401
+ const prefix = parts.slice(0, parent + 1).join(sep);
3402
+ // A new output directory can be spelled missing/../scan before its parent exists.
3403
+ if (allowMissing &&
3404
+ (await stat(prefix).catch(nullIfMissingFileError)) === null) {
3405
+ return resolve(path);
3406
+ }
3407
+ // Resolve each directory before moving to its parent. Some runtimes collapse
3408
+ // a literal ".." inside realpath before consulting the filesystem.
3409
+ const before = parts.slice(0, parent).join(sep) || (isAbsolute(path) ? sep : ".");
3410
+ const physical = dirname(await realpath(await resolveParentTraversal(before)));
3411
+ if (!(await sameFile(prefix, physical)))
3412
+ throw new InvalidTargetError(`Repository path changed: ${prefix}`);
3413
+ return join(physical, ...parts.slice(parent + 1));
3414
+ }
3415
+ export function expandHomeForLookup(value, environment = process.env) {
2787
3416
  const path = value.startsWith("~\\") ? value.replaceAll("\\", "/") : value;
2788
3417
  // Expand only the home prefix; joining the suffix would collapse symlink/.. paths.
2789
3418
  return path.startsWith("~/")