@openai/codex-security 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (387) hide show
  1. package/README.md +37 -788
  2. package/_bundled_plugin/.codex-plugin/plugin.json +2 -0
  3. package/_bundled_plugin/.mcp.json +2 -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/artifact-storage.md +1 -1
  15. package/_bundled_plugin/references/baseline-auditor.md +18 -0
  16. package/_bundled_plugin/references/core-scan.md +5 -42
  17. package/_bundled_plugin/references/final-report.md +1 -1
  18. package/_bundled_plugin/references/focused-investigator.md +13 -0
  19. package/_bundled_plugin/references/scan-prologue.md +2 -2
  20. package/_bundled_plugin/references/scan-runtime.md +4 -2
  21. package/_bundled_plugin/references/security-guidance.md +14 -1
  22. package/_bundled_plugin/references/validate-scan-findings.md +3 -0
  23. package/_bundled_plugin/scripts/deep_scan_workbench.py +29 -12
  24. package/_bundled_plugin/scripts/dispatch_inventory_tool +7 -0
  25. package/_bundled_plugin/scripts/finalize_scan_contract.py +29 -3
  26. package/_bundled_plugin/scripts/launch_codex_security_mcp +54 -16
  27. package/_bundled_plugin/scripts/posix_scan_local_files.py +26 -1
  28. package/_bundled_plugin/scripts/snapshot_sqlite.py +8 -2
  29. package/_bundled_plugin/scripts/windows_scan_local_files.py +216 -25
  30. package/_bundled_plugin/scripts/workbench/handoff.py +55 -25
  31. package/_bundled_plugin/scripts/workbench/storage.py +25 -5
  32. package/_bundled_plugin/scripts/workbench_cli.py +24 -2
  33. package/_bundled_plugin/scripts/workbench_constants.py +2 -0
  34. package/_bundled_plugin/scripts/workbench_db.py +244 -217
  35. package/_bundled_plugin/scripts/workbench_feedback.py +49 -4
  36. package/_bundled_plugin/scripts/workbench_native_indexes.py +226 -29
  37. package/_bundled_plugin/scripts/workbench_progress.py +159 -3
  38. package/_bundled_plugin/scripts/workbench_publication.py +2 -3
  39. package/_bundled_plugin/scripts/workbench_remediation.py +142 -2
  40. package/_bundled_plugin/scripts/workbench_saved_results.py +48 -8
  41. package/_bundled_plugin/scripts/workbench_scan_history.py +281 -119
  42. package/_bundled_plugin/scripts/workbench_scan_start.py +143 -9
  43. package/_bundled_plugin/scripts/workbench_scan_usage.py +36 -10
  44. package/_bundled_plugin/scripts/workbench_schema.py +220 -14
  45. package/_bundled_plugin/scripts/workbench_setup.py +1 -1
  46. package/_bundled_plugin/scripts/workbench_target.py +471 -84
  47. package/_bundled_plugin/scripts/workbench_target_state.py +1108 -22
  48. package/_bundled_plugin/shared/workbench-history-repairs.json +60 -14
  49. package/_bundled_plugin/shared/workbench-migrations.json +66 -0
  50. package/_bundled_plugin/skills/fix-finding/SKILL.md +1 -0
  51. package/_bundled_plugin/skills/publish-findings/SKILL.md +24 -160
  52. package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +2 -2
  53. package/_bundled_plugin/skills/publish-findings/references/checkmarx-import.md +2 -2
  54. package/_bundled_plugin/skills/publish-findings/scripts/collect_checkmarx.py +3 -58
  55. package/_bundled_plugin/skills/publish-findings/scripts/collect_continuum.py +224 -0
  56. package/_bundled_plugin/skills/publish-findings/scripts/collector_paths.py +63 -0
  57. package/_bundled_plugin/skills/security-scan/SKILL.md +9 -46
  58. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +2 -2
  59. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +3 -21
  60. package/_bundled_plugin/skills/security-scan/references/managed-scan.md +11 -0
  61. package/_bundled_plugin/skills/security-scan/references/scan-results.md +15 -0
  62. package/_bundled_plugin/skills/security-scan/references/scoped-paths.md +23 -0
  63. package/_bundled_plugin/skills/security-scan/references/sdk-files.md +24 -0
  64. package/bin/codex-security.mjs +2 -2
  65. package/dist/api.d.ts +6 -1
  66. package/dist/api.d.ts.map +1 -1
  67. package/dist/api.js +437 -154
  68. package/dist/api.js.map +1 -1
  69. package/dist/armorcode-findings.d.ts +9 -0
  70. package/dist/armorcode-findings.d.ts.map +1 -0
  71. package/dist/armorcode-findings.js +145 -0
  72. package/dist/armorcode-findings.js.map +1 -0
  73. package/dist/artifact-export.d.ts +2 -0
  74. package/dist/artifact-export.d.ts.map +1 -1
  75. package/dist/artifact-export.js +29 -13
  76. package/dist/artifact-export.js.map +1 -1
  77. package/dist/auth.d.ts +6 -2
  78. package/dist/auth.d.ts.map +1 -1
  79. package/dist/auth.js +33 -12
  80. package/dist/auth.js.map +1 -1
  81. package/dist/batch-cost.d.ts +18 -0
  82. package/dist/batch-cost.d.ts.map +1 -0
  83. package/dist/batch-cost.js +41 -0
  84. package/dist/batch-cost.js.map +1 -0
  85. package/dist/blackduck-findings.d.ts +1 -1
  86. package/dist/blackduck-findings.d.ts.map +1 -1
  87. package/dist/blackduck-findings.js +5 -18
  88. package/dist/blackduck-findings.js.map +1 -1
  89. package/dist/bundled-plugin.d.ts +4 -0
  90. package/dist/bundled-plugin.d.ts.map +1 -0
  91. package/dist/bundled-plugin.js +23 -0
  92. package/dist/bundled-plugin.js.map +1 -0
  93. package/dist/classify-scan-severity.d.ts +1 -1
  94. package/dist/classify-scan-severity.d.ts.map +1 -1
  95. package/dist/classify-scan-severity.js +11 -3
  96. package/dist/classify-scan-severity.js.map +1 -1
  97. package/dist/classify-severity.d.ts.map +1 -1
  98. package/dist/classify-severity.js +9 -6
  99. package/dist/classify-severity.js.map +1 -1
  100. package/dist/cli-argument.d.ts +4 -0
  101. package/dist/cli-argument.d.ts.map +1 -0
  102. package/dist/cli-argument.js +17 -0
  103. package/dist/cli-argument.js.map +1 -0
  104. package/dist/cli-help.d.ts +1 -1
  105. package/dist/cli-help.d.ts.map +1 -1
  106. package/dist/cli-help.js +71 -29
  107. package/dist/cli-help.js.map +1 -1
  108. package/dist/cli-hook.d.ts +3 -0
  109. package/dist/cli-hook.d.ts.map +1 -0
  110. package/dist/cli-hook.js +87 -0
  111. package/dist/cli-hook.js.map +1 -0
  112. package/dist/cli-integrations.d.ts +13 -0
  113. package/dist/cli-integrations.d.ts.map +1 -0
  114. package/dist/cli-integrations.js +333 -0
  115. package/dist/cli-integrations.js.map +1 -0
  116. package/dist/cli-mcp.d.ts +15 -0
  117. package/dist/cli-mcp.d.ts.map +1 -0
  118. package/dist/cli-mcp.js +178 -0
  119. package/dist/cli-mcp.js.map +1 -0
  120. package/dist/cli-token-view.d.ts +10 -0
  121. package/dist/cli-token-view.d.ts.map +1 -0
  122. package/dist/cli-token-view.js +41 -0
  123. package/dist/cli-token-view.js.map +1 -0
  124. package/dist/cli.d.ts +5 -3
  125. package/dist/cli.d.ts.map +1 -1
  126. package/dist/cli.js +1763 -894
  127. package/dist/cli.js.map +1 -1
  128. package/dist/cloud-publish.d.ts.map +1 -1
  129. package/dist/cloud-publish.js +33 -31
  130. package/dist/cloud-publish.js.map +1 -1
  131. package/dist/codex-sdk-environment.d.ts +6 -0
  132. package/dist/codex-sdk-environment.d.ts.map +1 -1
  133. package/dist/codex-sdk-environment.js +19 -0
  134. package/dist/codex-sdk-environment.js.map +1 -1
  135. package/dist/command-words.d.ts +3 -0
  136. package/dist/command-words.d.ts.map +1 -0
  137. package/dist/command-words.js +46 -0
  138. package/dist/command-words.js.map +1 -0
  139. package/dist/component-scan.d.ts +3 -1
  140. package/dist/component-scan.d.ts.map +1 -1
  141. package/dist/component-scan.js +40 -7
  142. package/dist/component-scan.js.map +1 -1
  143. package/dist/config.d.ts +1 -1
  144. package/dist/config.d.ts.map +1 -1
  145. package/dist/config.js +30 -1
  146. package/dist/config.js.map +1 -1
  147. package/dist/continuum-findings.d.ts +1 -1
  148. package/dist/continuum-findings.d.ts.map +1 -1
  149. package/dist/continuum-findings.js +93 -31
  150. package/dist/continuum-findings.js.map +1 -1
  151. package/dist/cost.d.ts.map +1 -1
  152. package/dist/cost.js +1 -45
  153. package/dist/cost.js.map +1 -1
  154. package/dist/custom-validation-prompt.d.ts +1 -1
  155. package/dist/custom-validation-prompt.d.ts.map +1 -1
  156. package/dist/custom-validation-prompt.js +29 -19
  157. package/dist/custom-validation-prompt.js.map +1 -1
  158. package/dist/deduplication/local.d.ts +3 -1
  159. package/dist/deduplication/local.d.ts.map +1 -1
  160. package/dist/deduplication/local.js +8 -1
  161. package/dist/deduplication/local.js.map +1 -1
  162. package/dist/deduplication/refusal.d.ts.map +1 -1
  163. package/dist/deduplication/refusal.js +2 -1
  164. package/dist/deduplication/refusal.js.map +1 -1
  165. package/dist/deduplication/scan.d.ts +2 -0
  166. package/dist/deduplication/scan.d.ts.map +1 -1
  167. package/dist/deduplication/scan.js +24 -7
  168. package/dist/deduplication/scan.js.map +1 -1
  169. package/dist/deep-scan.d.ts.map +1 -1
  170. package/dist/deep-scan.js +16 -15
  171. package/dist/deep-scan.js.map +1 -1
  172. package/dist/endor-findings.d.ts +2 -2
  173. package/dist/endor-findings.d.ts.map +1 -1
  174. package/dist/endor-findings.js +6 -23
  175. package/dist/endor-findings.js.map +1 -1
  176. package/dist/errors.d.ts +3 -1
  177. package/dist/errors.d.ts.map +1 -1
  178. package/dist/errors.js +7 -3
  179. package/dist/errors.js.map +1 -1
  180. package/dist/executable-path.d.ts +3 -0
  181. package/dist/executable-path.d.ts.map +1 -1
  182. package/dist/executable-path.js +26 -0
  183. package/dist/executable-path.js.map +1 -1
  184. package/dist/external-findings-import.d.ts.map +1 -1
  185. package/dist/external-findings-import.js +12 -1
  186. package/dist/external-findings-import.js.map +1 -1
  187. package/dist/external-findings-local.d.ts +66 -4
  188. package/dist/external-findings-local.d.ts.map +1 -1
  189. package/dist/external-findings-local.js +234 -53
  190. package/dist/external-findings-local.js.map +1 -1
  191. package/dist/external-findings-publish.d.ts +6 -1
  192. package/dist/external-findings-publish.d.ts.map +1 -1
  193. package/dist/external-findings-publish.js +326 -1633
  194. package/dist/external-findings-publish.js.map +1 -1
  195. package/dist/external-findings-read.d.ts +1 -0
  196. package/dist/external-findings-read.d.ts.map +1 -1
  197. package/dist/external-findings-read.js +31 -51
  198. package/dist/external-findings-read.js.map +1 -1
  199. package/dist/external-findings.d.ts +1 -1
  200. package/dist/external-findings.d.ts.map +1 -1
  201. package/dist/external-findings.js +12 -1
  202. package/dist/external-findings.js.map +1 -1
  203. package/dist/external-import-contract.d.ts +3 -11
  204. package/dist/external-import-contract.d.ts.map +1 -1
  205. package/dist/external-import-contract.js +29 -176
  206. package/dist/external-import-contract.js.map +1 -1
  207. package/dist/external-import-models.d.ts +1 -1
  208. package/dist/external-import-models.d.ts.map +1 -1
  209. package/dist/external-import-models.js.map +1 -1
  210. package/dist/finding-prompt.d.ts.map +1 -1
  211. package/dist/finding-prompt.js +2 -2
  212. package/dist/finding-prompt.js.map +1 -1
  213. package/dist/github-dependabot-findings.d.ts.map +1 -1
  214. package/dist/github-dependabot-findings.js +3 -4
  215. package/dist/github-dependabot-findings.js.map +1 -1
  216. package/dist/github-findings.d.ts.map +1 -1
  217. package/dist/github-findings.js +19 -287
  218. package/dist/github-findings.js.map +1 -1
  219. package/dist/hosted-remediation.d.ts +1 -0
  220. package/dist/hosted-remediation.d.ts.map +1 -1
  221. package/dist/hosted-remediation.js +23 -3
  222. package/dist/hosted-remediation.js.map +1 -1
  223. package/dist/index.d.ts +3 -2
  224. package/dist/index.d.ts.map +1 -1
  225. package/dist/index.js +2 -1
  226. package/dist/index.js.map +1 -1
  227. package/dist/inspector-findings.d.ts.map +1 -1
  228. package/dist/inspector-findings.js +19 -35
  229. package/dist/inspector-findings.js.map +1 -1
  230. package/dist/knowledge-base.d.ts +1 -1
  231. package/dist/knowledge-base.d.ts.map +1 -1
  232. package/dist/knowledge-base.js +34 -27
  233. package/dist/knowledge-base.js.map +1 -1
  234. package/dist/linear.d.ts +11 -0
  235. package/dist/linear.d.ts.map +1 -1
  236. package/dist/linear.js.map +1 -1
  237. package/dist/local-git-metadata.d.ts +5 -2
  238. package/dist/local-git-metadata.d.ts.map +1 -1
  239. package/dist/local-git-metadata.js +8 -4
  240. package/dist/local-git-metadata.js.map +1 -1
  241. package/dist/multiscan.d.ts +4 -0
  242. package/dist/multiscan.d.ts.map +1 -1
  243. package/dist/multiscan.js +79 -37
  244. package/dist/multiscan.js.map +1 -1
  245. package/dist/opengrep-findings.d.ts +4 -2
  246. package/dist/opengrep-findings.d.ts.map +1 -1
  247. package/dist/opengrep-findings.js +39 -22
  248. package/dist/opengrep-findings.js.map +1 -1
  249. package/dist/private-finding-import.d.ts +8 -13
  250. package/dist/private-finding-import.d.ts.map +1 -1
  251. package/dist/private-finding-import.js +69 -129
  252. package/dist/private-finding-import.js.map +1 -1
  253. package/dist/project-config.d.ts.map +1 -1
  254. package/dist/project-config.js +53 -13
  255. package/dist/project-config.js.map +1 -1
  256. package/dist/prompt-files.d.ts +7 -2
  257. package/dist/prompt-files.d.ts.map +1 -1
  258. package/dist/prompt-files.js +42 -20
  259. package/dist/prompt-files.js.map +1 -1
  260. package/dist/provider-profile.d.ts.map +1 -1
  261. package/dist/provider-profile.js +4 -9
  262. package/dist/provider-profile.js.map +1 -1
  263. package/dist/publication.d.ts +1 -1
  264. package/dist/publication.d.ts.map +1 -1
  265. package/dist/publication.js.map +1 -1
  266. package/dist/record.d.ts +1 -5
  267. package/dist/record.d.ts.map +1 -1
  268. package/dist/record.js +3 -51
  269. package/dist/record.js.map +1 -1
  270. package/dist/remediation.d.ts.map +1 -1
  271. package/dist/remediation.js +3 -1
  272. package/dist/remediation.js.map +1 -1
  273. package/dist/runtime.d.ts +35 -7
  274. package/dist/runtime.d.ts.map +1 -1
  275. package/dist/runtime.js +778 -153
  276. package/dist/runtime.js.map +1 -1
  277. package/dist/saved-scan-bootstrap.d.ts +6 -1
  278. package/dist/saved-scan-bootstrap.d.ts.map +1 -1
  279. package/dist/saved-scan-bootstrap.js +267 -115
  280. package/dist/saved-scan-bootstrap.js.map +1 -1
  281. package/dist/scan-archive-path.d.ts +2 -0
  282. package/dist/scan-archive-path.d.ts.map +1 -0
  283. package/dist/scan-archive-path.js +5 -0
  284. package/dist/scan-archive-path.js.map +1 -0
  285. package/dist/scan-comparison.d.ts.map +1 -1
  286. package/dist/scan-comparison.js +6 -2
  287. package/dist/scan-comparison.js.map +1 -1
  288. package/dist/scan-dashboard.d.ts +1 -0
  289. package/dist/scan-dashboard.d.ts.map +1 -1
  290. package/dist/scan-dashboard.js +18 -2
  291. package/dist/scan-dashboard.js.map +1 -1
  292. package/dist/scan-executor.d.ts.map +1 -1
  293. package/dist/scan-executor.js +4 -2
  294. package/dist/scan-executor.js.map +1 -1
  295. package/dist/scan-history-renderer.d.ts +1 -0
  296. package/dist/scan-history-renderer.d.ts.map +1 -1
  297. package/dist/scan-history-renderer.js +25 -9
  298. package/dist/scan-history-renderer.js.map +1 -1
  299. package/dist/scan-logs.d.ts.map +1 -1
  300. package/dist/scan-logs.js +28 -4
  301. package/dist/scan-logs.js.map +1 -1
  302. package/dist/scanner-import.d.ts +5 -11
  303. package/dist/scanner-import.d.ts.map +1 -1
  304. package/dist/scanner-import.js +16 -89
  305. package/dist/scanner-import.js.map +1 -1
  306. package/dist/security-policy.d.ts.map +1 -1
  307. package/dist/security-policy.js +26 -6
  308. package/dist/security-policy.js.map +1 -1
  309. package/dist/semgrep-findings.d.ts.map +1 -1
  310. package/dist/semgrep-findings.js +14 -48
  311. package/dist/semgrep-findings.js.map +1 -1
  312. package/dist/semgrep-platform-findings.d.ts +20 -70
  313. package/dist/semgrep-platform-findings.d.ts.map +1 -1
  314. package/dist/semgrep-platform-findings.js +116 -333
  315. package/dist/semgrep-platform-findings.js.map +1 -1
  316. package/dist/snyk-findings.d.ts +2 -0
  317. package/dist/snyk-findings.d.ts.map +1 -1
  318. package/dist/snyk-findings.js +5 -8
  319. package/dist/snyk-findings.js.map +1 -1
  320. package/dist/snyk-rest-findings.d.ts +3 -20
  321. package/dist/snyk-rest-findings.d.ts.map +1 -1
  322. package/dist/snyk-rest-findings.js +45 -217
  323. package/dist/snyk-rest-findings.js.map +1 -1
  324. package/dist/sonar-findings.d.ts +1 -1
  325. package/dist/sonar-findings.d.ts.map +1 -1
  326. package/dist/sonar-findings.js +2 -4
  327. package/dist/sonar-findings.js.map +1 -1
  328. package/dist/sonar-import.d.ts +3 -0
  329. package/dist/sonar-import.d.ts.map +1 -1
  330. package/dist/sonar-import.js +28 -30
  331. package/dist/sonar-import.js.map +1 -1
  332. package/dist/stored-finding-projection.d.ts +6 -0
  333. package/dist/stored-finding-projection.d.ts.map +1 -0
  334. package/dist/stored-finding-projection.js +104 -0
  335. package/dist/stored-finding-projection.js.map +1 -0
  336. package/dist/stored-findings-publication.d.ts +23 -0
  337. package/dist/stored-findings-publication.d.ts.map +1 -0
  338. package/dist/stored-findings-publication.js +169 -0
  339. package/dist/stored-findings-publication.js.map +1 -0
  340. package/dist/targets.d.ts +6 -1
  341. package/dist/targets.d.ts.map +1 -1
  342. package/dist/targets.js +76 -23
  343. package/dist/targets.js.map +1 -1
  344. package/dist/tenable-findings.d.ts +1 -4
  345. package/dist/tenable-findings.d.ts.map +1 -1
  346. package/dist/tenable-findings.js.map +1 -1
  347. package/dist/trivy-findings.d.ts.map +1 -1
  348. package/dist/trivy-findings.js +0 -11
  349. package/dist/trivy-findings.js.map +1 -1
  350. package/dist/trusted-executable.d.ts +6 -0
  351. package/dist/trusted-executable.d.ts.map +1 -1
  352. package/dist/trusted-executable.js +140 -37
  353. package/dist/trusted-executable.js.map +1 -1
  354. package/dist/veracode-findings.d.ts +1 -3
  355. package/dist/veracode-findings.d.ts.map +1 -1
  356. package/dist/veracode-findings.js +13 -38
  357. package/dist/veracode-findings.js.map +1 -1
  358. package/dist/version.d.ts +3 -1
  359. package/dist/version.d.ts.map +1 -1
  360. package/dist/version.js +184 -32
  361. package/dist/version.js.map +1 -1
  362. package/dist/wiz-findings.d.ts +2 -2
  363. package/dist/wiz-findings.d.ts.map +1 -1
  364. package/dist/wiz-findings.js +14 -92
  365. package/dist/wiz-findings.js.map +1 -1
  366. package/docs/cli.md +373 -106
  367. package/docs/findings-service.md +22 -9
  368. package/docs/hosted-remediation.md +13 -4
  369. package/docs/sdk.md +903 -0
  370. package/package.json +10 -6
  371. package/schemas/external-findings.schema.json +2 -1
  372. package/dist/hosted-scanner-v1.d.ts +0 -6
  373. package/dist/hosted-scanner-v1.d.ts.map +0 -1
  374. package/dist/hosted-scanner-v1.js +0 -60
  375. package/dist/hosted-scanner-v1.js.map +0 -1
  376. package/dist/reader-selection.d.ts +0 -15
  377. package/dist/reader-selection.d.ts.map +0 -1
  378. package/dist/reader-selection.js +0 -89
  379. package/dist/reader-selection.js.map +0 -1
  380. package/dist/semgrep-platform-v1.d.ts +0 -6
  381. package/dist/semgrep-platform-v1.d.ts.map +0 -1
  382. package/dist/semgrep-platform-v1.js +0 -83
  383. package/dist/semgrep-platform-v1.js.map +0 -1
  384. package/dist/snyk-rest-v1.d.ts +0 -28
  385. package/dist/snyk-rest-v1.d.ts.map +0 -1
  386. package/dist/snyk-rest-v1.js +0 -132
  387. 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,8 +1527,8 @@ 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({
@@ -1391,11 +1552,13 @@ export async function runWorkbench(options, args, input) {
1391
1552
  stateDirectory,
1392
1553
  payload: input === undefined ? undefined : JSON.parse(input),
1393
1554
  })
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`);
1555
+ : input, signal, {
1556
+ registrationHandshake,
1557
+ // Frame Python arguments on stdin to preserve NUL and long diagnostics.
1558
+ stdinPrefix: native
1559
+ ? undefined
1560
+ : `${JSON.stringify(arguments_.map((argument) => argument.toWellFormed()))}\n`,
1561
+ });
1399
1562
  if (!result.success) {
1400
1563
  throw new Error(result.stderr.trim() ||
1401
1564
  result.stdout.trim() ||
@@ -1405,11 +1568,25 @@ export async function runWorkbench(options, args, input) {
1405
1568
  };
1406
1569
  let stdout;
1407
1570
  try {
1408
- const archiveHandshake = signal !== undefined &&
1571
+ const registrationHandshake = signal !== undefined &&
1409
1572
  args[0] === "register-cli-scan" &&
1410
- args.includes("--archive-existing") &&
1411
- !args.includes("--archived-scan-dir");
1412
- stdout = await run(args, input, archiveHandshake);
1573
+ (process.platform === "win32" ||
1574
+ (args.includes("--archive-existing") &&
1575
+ !args.includes("--archived-scan-dir")));
1576
+ try {
1577
+ stdout = await run(args, input, registrationHandshake);
1578
+ }
1579
+ catch (error) {
1580
+ const focusedIndex = args.indexOf("--after-scan-id");
1581
+ if (args[0] !== "list-unmatched-scan-pairs" ||
1582
+ focusedIndex === -1 ||
1583
+ !/unrecognized arguments: --after-scan-id(?:\s+\S+)?$/u.test(processErrorDetail(error)))
1584
+ throw error;
1585
+ options.signal?.throwIfAborted();
1586
+ const legacyArgs = [...args];
1587
+ legacyArgs.splice(focusedIndex, 2);
1588
+ stdout = await run(legacyArgs, input, registrationHandshake);
1589
+ }
1413
1590
  }
1414
1591
  catch (error) {
1415
1592
  if (options.signal?.aborted)
@@ -1430,28 +1607,28 @@ export async function runWorkbench(options, args, input) {
1430
1607
  }
1431
1608
  return result;
1432
1609
  }
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);
1610
+ export async function resolveScanOutputPath(outputDirectory, validateTraversalLink) {
1611
+ try {
1612
+ const requested = resolveInputPath(outputDirectory);
1613
+ const path = await resolveParentTraversal(requested, {
1614
+ allowMissing: true,
1615
+ });
1616
+ requireModelSafeOutputDir(path);
1617
+ if (validateTraversalLink && path !== resolve(requested)) {
1618
+ await validateDirectoryLinks(requested, validateTraversalLink);
1444
1619
  }
1620
+ return path;
1621
+ }
1622
+ catch (error) {
1623
+ throw outputInspectionError(outputDirectory, error);
1445
1624
  }
1446
- throw new PluginBootstrapError("The bundled Codex Security plugin is missing.");
1447
1625
  }
1448
- export async function validateOutputDir(outputDirectory, archiveExisting = false) {
1626
+ export async function validateOutputDir(outputDirectory, archiveExisting = false, validateTraversalLink) {
1449
1627
  if (outputDirectory === undefined) {
1450
1628
  return null;
1451
1629
  }
1452
- const path = resolve(expandHome(outputDirectory));
1453
- requireModelSafeOutputDir(path);
1454
1630
  try {
1631
+ const path = await resolveScanOutputPath(outputDirectory, validateTraversalLink);
1455
1632
  const metadata = await lstat(path).catch(nullIfMissingFileError);
1456
1633
  if (metadata !== null) {
1457
1634
  if (!metadata.isDirectory()) {
@@ -1463,7 +1640,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
1463
1640
  requireOutputDirectoryOwnership(metadata, path);
1464
1641
  const writableLeaf = !archiveExisting ||
1465
1642
  (process.platform === "win32" && (await readdir(path)).length === 0);
1466
- const canonical = await checkedOutputPath(path, writableLeaf);
1643
+ const canonical = await checkedOutputPath(path, writableLeaf).catch(rethrowOutputPathValidationError);
1467
1644
  requireModelSafeOutputDir(canonical);
1468
1645
  return canonical;
1469
1646
  }
@@ -1473,7 +1650,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
1473
1650
  if ((await stat(parent)).isDirectory()) {
1474
1651
  const canonical = resolve(await realpath(parent), relative(parent, path));
1475
1652
  requireModelSafeOutputDir(canonical);
1476
- await requireSecureOutputAncestry(canonical);
1653
+ await requireSecureOutputAncestry(canonical).catch(rethrowOutputPathValidationError);
1477
1654
  return canonical;
1478
1655
  }
1479
1656
  break;
@@ -1490,11 +1667,41 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
1490
1667
  throw new OutputDirectoryError(`Unable to create scan output directory: ${path}`);
1491
1668
  }
1492
1669
  catch (error) {
1493
- if (error instanceof OutputDirectoryError)
1494
- throw error;
1495
- throw new OutputDirectoryError(`Unable to inspect scan output directory: ${outputDirectory}`, { cause: error });
1670
+ throw outputInspectionError(outputDirectory, error);
1671
+ }
1672
+ }
1673
+ function outputInspectionError(outputDirectory, cause) {
1674
+ return cause instanceof OutputDirectoryError
1675
+ ? cause
1676
+ : new OutputDirectoryError(`Unable to inspect scan output directory: ${outputDirectory}`, { cause });
1677
+ }
1678
+ /** Check each traversed directory link at its physical location, including linked targets. */
1679
+ export async function validateDirectoryLinks(requested, validateLocation) {
1680
+ const directories = [dirname(requested)];
1681
+ const visited = new Set();
1682
+ while (directories.length > 0) {
1683
+ let directory = directories.pop();
1684
+ while (dirname(directory) !== directory && !visited.has(directory)) {
1685
+ visited.add(directory);
1686
+ if ((await lstat(directory).catch(nullIfMissingFileError))?.isSymbolicLink()) {
1687
+ const parent = await realpath(await resolveParentTraversal(dirname(directory)));
1688
+ validateLocation(join(parent, basename(directory)));
1689
+ directories.push(resolveTargetPath(await readlink(directory), parent));
1690
+ }
1691
+ directory = dirname(directory);
1692
+ }
1496
1693
  }
1497
1694
  }
1695
+ function rethrowOutputPathValidationError(error) {
1696
+ if (process.platform !== "win32" ||
1697
+ nodeErrorCode(error) !== "ERR_DLOPEN_FAILED")
1698
+ throw error;
1699
+ const blocked = error instanceof Error &&
1700
+ /^(?:LoadLibrary failed: )?An Application Control policy has blocked this file\.(?:\s|$)/u.test(error.message);
1701
+ throw new OutputDirectoryError(blocked
1702
+ ? "Windows Application Control blocked the bundled Codex Security filesystem module (windows.node). Check the CodeIntegrity Operational log in Event Viewer."
1703
+ : "Could not load the bundled Codex Security filesystem module (windows.node) on Windows.", { cause: error });
1704
+ }
1498
1705
  export async function prepareScanArtifactRestorer(options, scanDirectory) {
1499
1706
  let helperPath;
1500
1707
  let canonicalPath;
@@ -1570,13 +1777,30 @@ export async function planOutputArchive(outputDirectory) {
1570
1777
  const entries = await readdir(outputDirectory).catch(nullIfMissingFileError);
1571
1778
  if (entries === null || entries.length === 0)
1572
1779
  return null;
1573
- return `${outputDirectory}${outputArchiveSuffix()}`;
1780
+ const id = randomUUID().slice(0, 8);
1781
+ const archive = `${outputDirectory}${outputArchiveSuffix(id)}`;
1782
+ if (process.platform === "win32" || !(await archiveNameTooLong(archive)))
1783
+ return archive;
1784
+ // The workbench reserves a sibling with an eight-character random suffix.
1785
+ const sibling = `${outputDirectory}.previous-${id}`;
1786
+ if (!(await archiveNameTooLong(sibling)))
1787
+ return sibling;
1788
+ return join(dirname(outputDirectory), shortArchivePrefix(basename(outputDirectory)) + id);
1789
+ }
1790
+ async function archiveNameTooLong(path) {
1791
+ try {
1792
+ await lstat(path);
1793
+ return false;
1794
+ }
1795
+ catch (error) {
1796
+ return nodeErrorCode(error) === "ENAMETOOLONG";
1797
+ }
1574
1798
  }
1575
- function outputArchiveSuffix() {
1799
+ function outputArchiveSuffix(id = randomUUID().slice(0, 8)) {
1576
1800
  return `.previous-${new Date()
1577
1801
  .toISOString()
1578
1802
  .replaceAll(/[-:]/g, "")
1579
- .replace(/\.\d{3}Z$/, "")}-${randomUUID().slice(0, 8)}`;
1803
+ .replace(/\.\d{3}Z$/, "")}-${id}`;
1580
1804
  }
1581
1805
  export function requireModelSafeOutputDir(path) {
1582
1806
  if (MODEL_UNSAFE_PATH.test(path)) {
@@ -1594,12 +1818,15 @@ export async function canonicalizeModelSafePath(input) {
1594
1818
  requireModelSafeOutputDir(canonical);
1595
1819
  return canonical;
1596
1820
  }
1597
- export async function canonicalConfigPath(path) {
1821
+ export async function canonicalConfigPath(path, { verifyIdentity = false } = {}) {
1598
1822
  let existing = resolve(path);
1599
1823
  const missing = [];
1600
1824
  while (true) {
1601
1825
  try {
1602
- return join(await realpath(existing), ...missing);
1826
+ const canonical = await realpath(existing);
1827
+ if (verifyIdentity && !(await sameFile(existing, canonical)))
1828
+ throw new InvalidTargetError(`Repository path changed: ${existing}`);
1829
+ return join(canonical, ...missing);
1603
1830
  }
1604
1831
  catch (error) {
1605
1832
  const parent = dirname(existing);
@@ -1619,7 +1846,7 @@ export async function prepareScanRegistrationOutput(outputDirectory, repositoryN
1619
1846
  return prepareOutputDirectory(outputDirectory, repositoryName, temporaryRoot, validateLocation, archiveExisting ? "preserve" : "reject");
1620
1847
  }
1621
1848
  async function prepareOutputDirectory(outputDirectory, repositoryName, temporaryRoot, validateLocation, existingOutput, onOutputArchived) {
1622
- const path = await validateOutputDir(outputDirectory, existingOutput !== "reject");
1849
+ const path = await validateOutputDir(outputDirectory, existingOutput !== "reject", validateLocation);
1623
1850
  if (path === null) {
1624
1851
  requireModelSafeOutputDir(temporaryRoot);
1625
1852
  const canonicalRoot = await realpath(temporaryRoot);
@@ -1636,7 +1863,15 @@ async function prepareOutputDirectory(outputDirectory, repositoryName, temporary
1636
1863
  await createWindowsOutputDirectory(created, false);
1637
1864
  }
1638
1865
  else {
1639
- created = await mkdtemp(join(canonicalRoot, `${prefix}-`));
1866
+ try {
1867
+ created = await mkdtemp(join(canonicalRoot, `${prefix}-`));
1868
+ }
1869
+ catch (error) {
1870
+ if (nodeErrorCode(error) !== "ENAMETOOLONG")
1871
+ throw error;
1872
+ // The repository name itself can fill a filesystem component.
1873
+ created = await mkdtemp(join(canonicalRoot, "codex-security-"));
1874
+ }
1640
1875
  }
1641
1876
  try {
1642
1877
  if ((process.umask() & 0o700) !== 0)
@@ -1897,6 +2132,7 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
1897
2132
  throw error;
1898
2133
  }
1899
2134
  await chmod(destination, 0o600);
2135
+ await rememberStoredFile(isolatedHome);
1900
2136
  return true;
1901
2137
  }
1902
2138
  catch (error) {
@@ -1909,9 +2145,17 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
1909
2145
  }
1910
2146
  }
1911
2147
  export async function extractPluginZip(archive, destination, signal) {
2148
+ return extractValidatedPluginZip(archive, destination, signal);
2149
+ }
2150
+ async function extractValidatedPluginZip(archive, destination, signal, digest) {
1912
2151
  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-")));
2152
+ const parent = dirname(destination);
2153
+ await mkdir(parent, { recursive: true, mode: 0o700 });
2154
+ // Windows mkdtemp otherwise fails at 248 UTF-16 units, including its suffix.
2155
+ const stagingParent = process.platform === "win32"
2156
+ ? win32.toNamespacedPath(await realpath(parent))
2157
+ : parent;
2158
+ const staging = await realpath(await mkdtemp(join(stagingParent, ".codex-security-plugin-")));
1915
2159
  let publishingOnWindows = false;
1916
2160
  try {
1917
2161
  throwIfSignalAborted(signal);
@@ -1951,6 +2195,7 @@ export async function extractPluginZip(archive, destination, signal) {
1951
2195
  const output = join(staging, ...path.split("/"));
1952
2196
  const entryMode = (entry.externalFileAttributes >>> 16) & 0xffff;
1953
2197
  const permissions = (entryMode || (directory ? 0o700 : 0o600)) & 0o777;
2198
+ digest?.update(JSON.stringify([path, directory, permissions]));
1954
2199
  await mkdir(directory ? output : dirname(output), {
1955
2200
  recursive: true,
1956
2201
  ...(directory ? { mode: permissions } : {}),
@@ -1971,6 +2216,7 @@ export async function extractPluginZip(archive, destination, signal) {
1971
2216
  if (crc32(bytes) !== checksum) {
1972
2217
  throw new PluginBootstrapError(`Plugin ZIP entry failed CRC-32 validation: ${path}`);
1973
2218
  }
2219
+ digest?.update(createHash("sha256").update(bytes).digest());
1974
2220
  }
1975
2221
  const pluginRoot = await discoverPluginRoot(staging);
1976
2222
  throwIfSignalAborted(signal);
@@ -2076,18 +2322,28 @@ async function openPluginZip(path, signal) {
2076
2322
  }
2077
2323
  }
2078
2324
  export async function resolvePluginPath(pluginPath, workspace, signal) {
2325
+ return (await resolvePluginSource(pluginPath, workspace, signal)).root;
2326
+ }
2327
+ /** @internal */
2328
+ export async function resolvePluginSource(pluginPath, workspace, signal, pinZip = false) {
2079
2329
  try {
2080
2330
  if (pluginPath === undefined) {
2081
- return await bundledPluginRoot();
2331
+ return { root: await bundledPluginRoot() };
2082
2332
  }
2083
2333
  const path = resolve(expandHome(pluginPath));
2084
2334
  const metadata = await lstat(path).catch(() => null);
2085
2335
  if (metadata?.isFile() && extname(path).toLowerCase() === ".zip") {
2086
- return await extractPluginZip(path, join(workspace, "extracted-plugin"), signal);
2336
+ const digest = pinZip ? createHash("sha256") : undefined;
2337
+ const archive = digest ? await realpath(path) : path;
2338
+ const root = await extractValidatedPluginZip(archive, join(workspace, "extracted-plugin"), signal, digest);
2339
+ return {
2340
+ root,
2341
+ ...(digest && { zip: { path: archive, digest: digest.digest("hex") } }),
2342
+ };
2087
2343
  }
2088
2344
  if (metadata?.isDirectory()) {
2089
2345
  throwIfSignalAborted(signal);
2090
- return await validatePluginRoot(path);
2346
+ return { root: await validatePluginRoot(path) };
2091
2347
  }
2092
2348
  throw new PluginBootstrapError(`Plugin path must be a directory or ZIP: ${path}`);
2093
2349
  }
@@ -2097,6 +2353,79 @@ export async function resolvePluginPath(pluginPath, workspace, signal) {
2097
2353
  throw new LocalPluginBootstrapError(errorMessage(error), { cause: error });
2098
2354
  }
2099
2355
  }
2356
+ /** @internal */
2357
+ export async function prepareWindowsScanPluginZip(source, scanDirectory, protectedDirectories, validateLocation, signal) {
2358
+ throwIfSignalAborted(signal);
2359
+ const protectedPath = (path) => protectedDirectories.some((directory) => isWithin(directory, path));
2360
+ if (protectedPath(source.path))
2361
+ return;
2362
+ const metadata = await lstat(source.path).catch(nullIfMissingFileError);
2363
+ if (metadata === null)
2364
+ return;
2365
+ const changed = "The selected plugin ZIP changed after runtime preparation.";
2366
+ if (!metadata.isFile())
2367
+ throw new LocalPluginBootstrapError(changed);
2368
+ const canonicalSource = await realpath(source.path).catch(nullIfMissingFileError);
2369
+ if (canonicalSource === null)
2370
+ return;
2371
+ if (protectedPath(canonicalSource))
2372
+ throw new LocalPluginBootstrapError(changed);
2373
+ let workspace;
2374
+ const parents = [...new Set([dirname(scanDirectory), tmpdir()])].filter((parent) => !protectedPath(parent) && !isWithin(scanDirectory, parent));
2375
+ // PowerShell may fail to launch the selected plugin's .cmd at a long path.
2376
+ // Prefer the shorter canonical parent, retaining the output parent on ties.
2377
+ const candidates = await abortable(() => Promise.allSettled(parents.map((path) => realpath(path))), signal);
2378
+ const length = (candidate) => candidate.status === "fulfilled" ? candidate.value.length : Infinity;
2379
+ for (const candidate of candidates.sort((a, b) => length(a) - length(b))) {
2380
+ throwIfSignalAborted(signal);
2381
+ try {
2382
+ if (candidate.status === "rejected")
2383
+ throw candidate.reason;
2384
+ const canonical = candidate.value;
2385
+ if (protectedPath(canonical) || isWithin(scanDirectory, canonical))
2386
+ continue;
2387
+ // Host-side plugin helpers may execute from this copy. A sibling keeps it
2388
+ // outside the writable scan, and the native creator verifies its parents.
2389
+ workspace = await prepareOutputDir(undefined, "plugin-input", canonical, validateLocation);
2390
+ break;
2391
+ }
2392
+ catch (error) {
2393
+ if (!(error instanceof OutputDirectoryError) &&
2394
+ !["EACCES", "EPERM", "ENOENT"].includes(nodeErrorCode(error) ?? ""))
2395
+ throw error;
2396
+ }
2397
+ }
2398
+ // Keep existing plugin handling where neither scan input location is usable.
2399
+ if (workspace === undefined)
2400
+ return;
2401
+ try {
2402
+ throwIfSignalAborted(signal);
2403
+ const digest = createHash("sha256");
2404
+ const root = await extractValidatedPluginZip(source.path, join(workspace, "plugin"), signal, digest);
2405
+ throwIfSignalAborted(signal);
2406
+ if (digest.digest("hex") !== source.digest) {
2407
+ throw new LocalPluginBootstrapError(changed);
2408
+ }
2409
+ return { workspace, root };
2410
+ }
2411
+ catch (error) {
2412
+ try {
2413
+ await cleanupSdkDirectory(workspace);
2414
+ }
2415
+ catch (cleanupError) {
2416
+ throwIfSignalAborted(signal);
2417
+ throw new LocalPluginBootstrapError(`${errorMessage(error)}\nCould not remove scan input directory ${workspace}: ${errorMessage(cleanupError)}`, { cause: error });
2418
+ }
2419
+ throwIfSignalAborted(signal);
2420
+ const cause = error instanceof PluginBootstrapError ? error.cause : undefined;
2421
+ if (isRecord(cause) &&
2422
+ cause["code"] === "ENOENT" &&
2423
+ cause["syscall"] === "open" &&
2424
+ cause["path"] === source.path)
2425
+ return;
2426
+ throw error;
2427
+ }
2428
+ }
2100
2429
  export async function createMarketplace(codexHome, pluginRoot, signal) {
2101
2430
  try {
2102
2431
  throwIfSignalAborted(signal);
@@ -2149,6 +2478,20 @@ async function writeMarketplaceManifest(marketplace, signal) {
2149
2478
  await rm(temporary, { force: true });
2150
2479
  }
2151
2480
  }
2481
+ // Private handoff to the staged SDK launcher and shell-invoked helpers.
2482
+ export const SDK_NODE_SEARCH_PATH = "_CODEX_SECURITY_SDK_NODE_SEARCH_PATH";
2483
+ export async function sdkNodeSearchPath(roots) {
2484
+ let fallback = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin";
2485
+ const current = dirname(process.execPath);
2486
+ if (process.release.name === "node" &&
2487
+ !process.versions["bun"] &&
2488
+ !process.versions["electron"] &&
2489
+ basename(process.execPath) === "node" &&
2490
+ !current.includes(":"))
2491
+ fallback += `:${current}`;
2492
+ const inspected = await inspectTrustedExecutable("node", { PATH: fallback }, roots);
2493
+ return inspected.environment["PATH"] ?? "";
2494
+ }
2152
2495
  async function pluginRuntimeProjection(root, signal) {
2153
2496
  const path = join(root, ".mcp.json");
2154
2497
  // Keep the source link checks ahead of any configuration read.
@@ -2167,13 +2510,10 @@ async function pluginRuntimeProjection(root, signal) {
2167
2510
  const environment = server["env_vars"];
2168
2511
  if (environment !== undefined && !Array.isArray(environment))
2169
2512
  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
- }
2513
+ server["env_vars"] = [
2514
+ ...(environment ?? []),
2515
+ ...["CODEX_SECURITY_PLUGIN_ROOT", "CODEX_SECURITY_REPOSITORY"].filter((name) => !environment?.includes(name)),
2516
+ ];
2177
2517
  const files = new Map();
2178
2518
  server["command"] =
2179
2519
  server["command"] === "./scripts/launch_codex_security_mcp.cmd"
@@ -2184,7 +2524,7 @@ async function pluginRuntimeProjection(root, signal) {
2184
2524
  'if [ -n "${CODEX_SECURITY_PLUGIN_ROOT:-}" ]; then\n' +
2185
2525
  ' exec "$CODEX_SECURITY_PLUGIN_ROOT/scripts/launch_codex_security_mcp" "$@"\n' +
2186
2526
  "fi\n" +
2187
- 'exec "$(dirname "$0")/launch_codex_security_mcp" "$@"\n'),
2527
+ 'exec "$(command -p dirname "$0")/launch_codex_security_mcp" "$@"\n'),
2188
2528
  mode: 0o755,
2189
2529
  });
2190
2530
  files.set("scripts/launch_codex_security_mcp_sdk.cmd", {
@@ -2201,10 +2541,10 @@ async function pluginRuntimeProjection(root, signal) {
2201
2541
  return { root, files };
2202
2542
  }
2203
2543
  export function resolveCodexCommand(environment = process.env) {
2204
- const configured = environmentValue(environment, "CODEX_CLI_PATH");
2544
+ const configured = configuredExecutableValue(environmentValue(environment, "CODEX_CLI_PATH", true), process.platform, (value) => isExecutableFile(expandHomeForLookup(value, environment)));
2205
2545
  const expanded = configured === undefined
2206
2546
  ? undefined
2207
- : expandExecutableHome(configured, environment);
2547
+ : expandHomeForLookup(configured, environment);
2208
2548
  if (expanded &&
2209
2549
  (process.platform !== "win32" || /\.(?:exe|com)$/iu.test(expanded))) {
2210
2550
  return {
@@ -2265,8 +2605,22 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2265
2605
  ? null
2266
2606
  : await pluginMetadata(join(marketplace, "plugins", PLUGIN_NAME)).catch(() => null);
2267
2607
  const stagedRoot = join(marketplace, "plugins", PLUGIN_NAME);
2268
- const stagedMatches = staged?.version === version &&
2269
- (await pluginContentsMatch(root, stagedRoot, options.signal, false, projection));
2608
+ const matchesSelected = (destination, allowExtraFiles = false, generatedDirectory) => pluginContentsMatch(root, destination, options.signal, allowExtraFiles, projection, generatedDirectory);
2609
+ const stagedMatches = staged?.version === version && (await matchesSelected(stagedRoot));
2610
+ const matchesNativeInstall = async (installedRoot, allowRuntimeFiles = false) => (await matchesSelected(stagedRoot)) &&
2611
+ // Ordinary reuse permits runtime files when all selected bytes are present.
2612
+ // The native receipt still verifies the complete generated command output.
2613
+ ((allowRuntimeFiles && (await matchesSelected(installedRoot, true))) ||
2614
+ (await matchesSelected(installedRoot, false, migratedCommands(installedRoot))));
2615
+ const nativeMigration = (installedRoot, allowRuntimeFiles = false) => verifiedCommandMigration(installedRoot, (path) => matchesNativeInstall(path, allowRuntimeFiles), options.signal);
2616
+ const matchesReceipt = async (installedRoot, migration) => {
2617
+ if (typeof migration === "string" &&
2618
+ options.runCodex === undefined &&
2619
+ (await isBundledPluginInstaller(command))) {
2620
+ return (await nativeMigration(installedRoot, true)) === migration;
2621
+ }
2622
+ return matchesSelected(installedRoot, true);
2623
+ };
2270
2624
  if (!stagedMatches) {
2271
2625
  if (existing !== null) {
2272
2626
  await rm(marketplace, { recursive: true, force: true });
@@ -2324,7 +2678,7 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2324
2678
  isRecord(previous) &&
2325
2679
  typeof previous["installedPath"] === "string" &&
2326
2680
  previous["version"] === version &&
2327
- (await pluginContentsMatch(root, previous["installedPath"], options.signal, true, projection))) {
2681
+ (await matchesReceipt(previous["installedPath"], previous["nativeCommandMigration"]))) {
2328
2682
  return {
2329
2683
  pluginRoot: root,
2330
2684
  marketplaceRoot: marketplace,
@@ -2334,7 +2688,35 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2334
2688
  version,
2335
2689
  };
2336
2690
  }
2337
- const output = await run(command, ["plugin", "add", "--json", `${PLUGIN_NAME}@${MARKETPLACE_NAME}`], environment, options.signal);
2691
+ const addPlugin = () => run(command, ["plugin", "add", "--json", `${PLUGIN_NAME}@${MARKETPLACE_NAME}`], environment, options.signal);
2692
+ let output;
2693
+ let retried = false;
2694
+ try {
2695
+ output = await addPlugin();
2696
+ }
2697
+ catch (first) {
2698
+ if (!isRolledBackPluginActivation(first))
2699
+ throw first;
2700
+ throwIfSignalAborted(options.signal);
2701
+ if (!(await isBundledPluginInstaller(command)))
2702
+ throw first;
2703
+ // The bundled CLI restored the old cache. A short-lived Windows reader
2704
+ // of the new tree can release it before a fresh installation attempt.
2705
+ try {
2706
+ await delay(100, undefined, { signal: options.signal });
2707
+ throwIfSignalAborted(options.signal);
2708
+ if (!(await matchesSelected(stagedRoot))) {
2709
+ throw new LocalPluginBootstrapError("The selected plugin or its marketplace changed before the native installation could be retried.", { cause: first });
2710
+ }
2711
+ throwIfSignalAborted(options.signal);
2712
+ output = await addPlugin();
2713
+ retried = true;
2714
+ }
2715
+ catch (second) {
2716
+ throwIfSignalAborted(options.signal);
2717
+ throw isRolledBackPluginActivation(second) ? first : second;
2718
+ }
2719
+ }
2338
2720
  let installed;
2339
2721
  try {
2340
2722
  installed = JSON.parse(output);
@@ -2347,9 +2729,25 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2347
2729
  installed["version"] !== version) {
2348
2730
  throw new PluginBootstrapError("Codex plugin install did not return the selected plugin path and version.");
2349
2731
  }
2732
+ // The bundled installer removes stale command skills before regenerating them.
2733
+ const bundledInstaller = retried ||
2734
+ (options.runCodex === undefined &&
2735
+ (await isBundledPluginInstaller(command)));
2736
+ const hasSourceMigration = bundledInstaller &&
2737
+ (await lstat(migratedCommands(root)).catch(nullIfMissingFileError))?.isDirectory() === true;
2738
+ const nativeCommandMigration = hasSourceMigration
2739
+ ? await nativeMigration(installed["installedPath"])
2740
+ : undefined;
2741
+ if (retried &&
2742
+ !(hasSourceMigration
2743
+ ? nativeCommandMigration !== undefined
2744
+ : await matchesNativeInstall(installed["installedPath"]))) {
2745
+ throw new PluginBootstrapError("The retried Codex plugin install did not install the selected plugin contents.");
2746
+ }
2350
2747
  await writeFile(installRecord, JSON.stringify({
2351
2748
  installedPath: installed["installedPath"],
2352
2749
  version,
2750
+ ...(nativeCommandMigration ? { nativeCommandMigration } : {}),
2353
2751
  }), { mode: 0o600, signal: options.signal });
2354
2752
  return {
2355
2753
  pluginRoot: root,
@@ -2360,7 +2758,92 @@ export async function bootstrapPlugin(codexHome, pluginRoot, options = {}) {
2360
2758
  version,
2361
2759
  };
2362
2760
  }
2363
- async function pluginContentsMatch(source, destination, signal, allowExtraFiles = false, projection) {
2761
+ async function isBundledPluginInstaller(command) {
2762
+ try {
2763
+ return await sameFile(command.command, resolveBundledCodexExecutable());
2764
+ }
2765
+ catch {
2766
+ return false;
2767
+ }
2768
+ }
2769
+ function migratedCommands(plugin) {
2770
+ return join(plugin, ".codex-plugin", "migrated-command-skills");
2771
+ }
2772
+ // Bind a receipt to the generated files observed in this installation.
2773
+ // Entry names come from its directories, never from the saved digest.
2774
+ async function verifiedCommandMigration(installedRoot, matchesSelected, signal) {
2775
+ const digest = createHash("sha256");
2776
+ const record = (...fields) => digest.update(JSON.stringify(fields)).update("\n");
2777
+ async function visit(path, name) {
2778
+ throwIfSignalAborted(signal);
2779
+ const metadata = await lstat(path, { bigint: true });
2780
+ if (metadata.isSymbolicLink() ||
2781
+ relative(path, await realpath(path)) !== "")
2782
+ return false;
2783
+ if (metadata.isDirectory()) {
2784
+ record("directory", name);
2785
+ for (const entry of (await readdir(path)).sort()) {
2786
+ const child = join(path, entry);
2787
+ if (!(await visit(child, name ? `${name}/${entry}` : entry)))
2788
+ return false;
2789
+ }
2790
+ return sameInode(metadata, await lstat(path, { bigint: true }));
2791
+ }
2792
+ if (!metadata.isFile())
2793
+ return false;
2794
+ const file = await open(path, constants.O_RDONLY |
2795
+ (constants.O_NOFOLLOW ?? 0) |
2796
+ (constants.O_NONBLOCK ?? 0));
2797
+ try {
2798
+ const opened = await file.stat({ bigint: true });
2799
+ if (!opened.isFile())
2800
+ return false;
2801
+ if (!sameInode(metadata, opened)) {
2802
+ if (process.platform !== "win32")
2803
+ return false;
2804
+ // Some Windows Node versions report a different device on an open handle.
2805
+ const { sameCheckedFileDevice } = await import("./contract.js");
2806
+ if (!(await sameCheckedFileDevice(file, { path, metadata }, opened)))
2807
+ return false;
2808
+ }
2809
+ const contents = createHash("sha256")
2810
+ .update(await file.readFile({ signal }))
2811
+ .digest("hex");
2812
+ record("file", name, Number(opened.mode & 73n), contents);
2813
+ }
2814
+ finally {
2815
+ await file.close();
2816
+ }
2817
+ return true;
2818
+ }
2819
+ throwIfSignalAborted(signal);
2820
+ const installation = await lstat(installedRoot, { bigint: true }).catch(nullIfMissingFileError);
2821
+ if (!installation?.isDirectory() ||
2822
+ installation.ino === 0n ||
2823
+ !(await matchesSelected(installedRoot)))
2824
+ return;
2825
+ try {
2826
+ const directory = migratedCommands(await realpath(installedRoot));
2827
+ const parent = dirname(directory);
2828
+ if (!(await lstat(parent)).isDirectory() ||
2829
+ relative(parent, await realpath(parent)) !== "")
2830
+ return;
2831
+ const root = await lstat(directory, { bigint: true }).catch(nullIfMissingFileError);
2832
+ if (root && (!root.isDirectory() || !(await visit(directory, ""))))
2833
+ return;
2834
+ // Native activation replaces the installed directory even at the same version.
2835
+ if (!sameInode(installation, await lstat(installedRoot, { bigint: true })))
2836
+ return;
2837
+ throwIfSignalAborted(signal);
2838
+ return root ? `sha256:${digest.digest("hex")}` : "absent";
2839
+ }
2840
+ catch (error) {
2841
+ throwIfSignalAborted(signal);
2842
+ if (!["ENOENT", "ENOTDIR", "ELOOP", "EISDIR", "EACCES", "EPERM"].includes(nodeErrorCode(error) ?? ""))
2843
+ throw error;
2844
+ }
2845
+ }
2846
+ async function pluginContentsMatch(source, destination, signal, allowExtraFiles = false, projection, generatedDirectory) {
2364
2847
  throwIfSignalAborted(signal);
2365
2848
  const sourceMetadata = await lstat(source);
2366
2849
  const destinationMetadata = await lstat(destination).catch((error) => {
@@ -2389,15 +2872,39 @@ async function pluginContentsMatch(source, destination, signal, allowExtraFiles
2389
2872
  if (!sourceMetadata.isDirectory() || !destinationMetadata.isDirectory()) {
2390
2873
  return false;
2391
2874
  }
2392
- const entries = await readdir(source);
2875
+ let entries = await readdir(source);
2876
+ let nativeOutputs = 0;
2877
+ if (generatedDirectory) {
2878
+ const parent = dirname(generatedDirectory);
2879
+ if (parent === destination ||
2880
+ (relative(parent, destination) === "" &&
2881
+ (await sameFile(parent, destination)))) {
2882
+ // The installer removes old command output before regenerating it. Resolve
2883
+ // its source spelling on volumes that preserve case but ignore it on lookup.
2884
+ const path = join(source, basename(generatedDirectory));
2885
+ const original = await lstat(path).catch(nullIfMissingFileError);
2886
+ if (original?.isSymbolicLink())
2887
+ return false;
2888
+ if (original) {
2889
+ const name = basename(await realpath(path));
2890
+ entries = entries.filter((entry) => entry !== name);
2891
+ }
2892
+ const installed = await lstat(generatedDirectory).catch(nullIfMissingFileError);
2893
+ if (installed) {
2894
+ if (!installed.isDirectory())
2895
+ return false;
2896
+ nativeOutputs = 1;
2897
+ }
2898
+ }
2899
+ }
2393
2900
  const projectedDirectory = projection === undefined
2394
2901
  ? undefined
2395
2902
  : relative(projection.root, source).split(sep).join("/") || ".";
2396
2903
  const generated = [...(projection?.files ?? [])].filter(([path]) => dirname(path) === projectedDirectory && !entries.includes(basename(path)));
2397
2904
  if (!allowExtraFiles &&
2398
- entries.length + generated.length !== (await readdir(destination)).length) {
2905
+ entries.length + generated.length + nativeOutputs !==
2906
+ (await readdir(destination)).length)
2399
2907
  return false;
2400
- }
2401
2908
  for (const [path, file] of generated) {
2402
2909
  const generatedPath = join(destination, basename(path));
2403
2910
  const metadata = await lstat(generatedPath).catch(nullIfMissingFileError);
@@ -2409,7 +2916,7 @@ async function pluginContentsMatch(source, destination, signal, allowExtraFiles
2409
2916
  }
2410
2917
  }
2411
2918
  for (const entry of entries) {
2412
- if (!(await pluginContentsMatch(join(source, entry), join(destination, entry), signal, allowExtraFiles, projection))) {
2919
+ if (!(await pluginContentsMatch(join(source, entry), join(destination, entry), signal, allowExtraFiles, projection, generatedDirectory))) {
2413
2920
  return false;
2414
2921
  }
2415
2922
  }
@@ -2440,12 +2947,10 @@ export async function pluginMetadata(root) {
2440
2947
  }
2441
2948
  export async function resolvePluginPython(options = {}) {
2442
2949
  const environment = options.environment ?? process.env;
2443
- const requestedRoots = options.protectedRoot ?? process.cwd();
2950
+ const cwd = process.cwd();
2951
+ const requestedRoots = options.protectedRoot ?? cwd;
2444
2952
  const protectedRoot = typeof requestedRoots === "string" ? [requestedRoots] : [...requestedRoots];
2445
- const callerDirectories = [
2446
- process.cwd(),
2447
- options.currentDirectory ?? process.cwd(),
2448
- ];
2953
+ const callerDirectories = new Set([cwd, options.currentDirectory ?? cwd]);
2449
2954
  // Preserve target and enclosing-checkout protection for every interpreter.
2450
2955
  for (const directory of new Set([...callerDirectories, ...protectedRoot])) {
2451
2956
  for (const checkout of await gitProtectionRoots(directory, options.signal))
@@ -2454,20 +2959,59 @@ export async function resolvePluginPython(options = {}) {
2454
2959
  }
2455
2960
  // Named interpreters are ambient PATH discovery, even when PYTHON names one.
2456
2961
  // Explicit trusted paths and managed runtimes retain their existing precedence.
2457
- const discoveryRoots = [...protectedRoot, ...callerDirectories];
2962
+ const discoveryRoots = [
2963
+ ...protectedRoot,
2964
+ ...(options.discoveryProtectedRoots ?? []),
2965
+ ];
2966
+ for (const directory of callerDirectories) {
2967
+ const physical = directory === cwd
2968
+ ? cwd
2969
+ : await realpath(directory).catch(() => undefined);
2970
+ // A filesystem-root launch directory also contains the operator's installed tools.
2971
+ // Explicit scan roots and enclosing checkouts are already in protectedRoot.
2972
+ if (protectedRoot.length === 0 ||
2973
+ physical === undefined ||
2974
+ dirname(physical) !== physical)
2975
+ discoveryRoots.push(directory);
2976
+ }
2977
+ const missingBoundaryMessage = "Could not establish the saved checkout boundary for Python discovery. Set PYTHON to an absolute trusted interpreter.";
2458
2978
  if (options.configuredPath !== undefined) {
2979
+ if (!isPythonPathCandidate(options.configuredPath) &&
2980
+ options.allowPathLookup === false)
2981
+ throw new PluginPythonUnavailableError(missingBoundaryMessage);
2459
2982
  return await requirePython(options.configuredPath, "configured plugin Python", environment, isPythonPathCandidate(options.configuredPath)
2460
2983
  ? protectedRoot
2461
2984
  : discoveryRoots, options.signal);
2462
2985
  }
2463
- const inherited = environmentValue(environment, "PYTHON");
2986
+ const inherited = environmentValue(environment, "PYTHON", true);
2464
2987
  if (inherited) {
2465
- return await requirePython(inherited, "PYTHON", environment, isPythonPathCandidate(inherited) ? protectedRoot : discoveryRoots, options.signal);
2988
+ if (!isPythonPathCandidate(inherited) && options.allowPathLookup === false)
2989
+ throw new PluginPythonUnavailableError(missingBoundaryMessage);
2990
+ const roots = isPythonPathCandidate(inherited)
2991
+ ? protectedRoot
2992
+ : discoveryRoots;
2993
+ // Check an explicit literal path with the same repository protections as the launch.
2994
+ const candidate = isExplicitPathWithTrailingWhitespace(inherited, process.platform) &&
2995
+ (await resolveTrustedExecutable(expandHomeForLookup(inherited, environment), environment, roots))
2996
+ ? inherited
2997
+ : inherited.trim();
2998
+ return await requirePython(candidate, "PYTHON", environment, roots, options.signal);
2999
+ }
3000
+ let managedRoots = options.managedRuntimeRoots;
3001
+ if (managedRoots === undefined) {
3002
+ try {
3003
+ const cache = environmentValue(environment, "XDG_CACHE_HOME", true) ||
3004
+ join(options.homeDirectory ?? homedir(), ".cache");
3005
+ managedRoots = [join(cache, "codex-runtimes", "codex-primary-runtime")];
3006
+ }
3007
+ catch (error) {
3008
+ // A numeric Linux UID can lack a home for the optional managed cache.
3009
+ if (process.platform !== "linux" ||
3010
+ error.info?.code !== "ENOENT")
3011
+ throw error;
3012
+ managedRoots = [];
3013
+ }
2466
3014
  }
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
3015
  const relativeCandidates = process.platform === "win32"
2472
3016
  ? [
2473
3017
  join("dependencies", "python", "python.exe"),
@@ -2486,6 +3030,8 @@ export async function resolvePluginPython(options = {}) {
2486
3030
  return resolved;
2487
3031
  }
2488
3032
  }
3033
+ if (options.allowPathLookup === false)
3034
+ throw new PluginPythonUnavailableError(missingBoundaryMessage);
2489
3035
  for (const candidate of process.platform === "win32"
2490
3036
  ? ["python", "python3", "py"]
2491
3037
  : ["python3", "python"]) {
@@ -2543,35 +3089,46 @@ export function isDisconnectedChildStdin(error) {
2543
3089
  "ERR_STREAM_DESTROYED",
2544
3090
  ].includes(error.code ?? "");
2545
3091
  }
2546
- export async function runCodexCommand(command, args, environment, input, signal, archiveHandshake = false, stdinPrefix) {
2547
- const cancellation = archiveHandshake ? new AbortController() : undefined;
3092
+ export async function runCodexCommand(command, args, environment, input, launchSignal, { registrationHandshake = false, stdinPrefix, cwd, } = {}) {
3093
+ const campaign = campaignExecutable(command.command, environment);
3094
+ const selected = campaign && (await campaign);
3095
+ const executable = selected?.executable ?? command.command;
3096
+ const commandArgs = typeof args === "function" ? args(executable) : args;
3097
+ const signal = typeof launchSignal === "function" ? launchSignal() : launchSignal;
3098
+ const cancellation = registrationHandshake
3099
+ ? new AbortController()
3100
+ : undefined;
2548
3101
  const abort = () => cancellation?.abort(signal?.reason);
2549
3102
  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"],
3103
+ const child = spawn(executablePathForSpawn(executable), [...(command.args ?? []), ...commandArgs], {
3104
+ cwd,
3105
+ env: selected?.environment ?? environment,
3106
+ stdio: registrationHandshake
3107
+ ? ["pipe", "pipe", "pipe", "pipe"]
3108
+ : ["pipe", "pipe", "pipe"],
2554
3109
  windowsHide: true,
2555
3110
  signal: commandSignal,
2556
3111
  });
2557
3112
  let stdout = "";
2558
3113
  let stderr = "";
2559
3114
  let processError;
3115
+ const control = child.stdio[3];
3116
+ control?.once("data", () => {
3117
+ // The helper cannot change the output until the host allows the transaction.
3118
+ signal?.removeEventListener("abort", abort);
3119
+ if (signal?.aborted)
3120
+ abort();
3121
+ else
3122
+ control.end("!");
3123
+ });
3124
+ control?.on("error", (error) => {
3125
+ if (!isDisconnectedChildStdin(error))
3126
+ processError = error;
3127
+ });
2560
3128
  child.stdout.setEncoding("utf8");
2561
3129
  child.stderr.setEncoding("utf8");
2562
3130
  child.stdout.on("data", (chunk) => {
2563
3131
  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
3132
  });
2576
3133
  child.stderr.on("data", (chunk) => {
2577
3134
  stderr += chunk;
@@ -2600,12 +3157,13 @@ export async function runCodexCommand(command, args, environment, input, signal,
2600
3157
  child.stdin.destroy();
2601
3158
  child.stdout.destroy();
2602
3159
  child.stderr.destroy();
3160
+ control?.destroy();
2603
3161
  };
2604
3162
  commandSignal?.addEventListener("abort", settleCanceledChild, { once: true });
2605
3163
  child.once("exit", settleCanceledChild);
2606
3164
  if (commandSignal?.aborted)
2607
3165
  settleCanceledChild();
2608
- if (archiveHandshake) {
3166
+ if (registrationHandshake) {
2609
3167
  signal?.addEventListener("abort", abort, { once: true });
2610
3168
  if (signal?.aborted)
2611
3169
  abort();
@@ -2613,15 +3171,13 @@ export async function runCodexCommand(command, args, environment, input, signal,
2613
3171
  try {
2614
3172
  if (stdinPrefix !== undefined)
2615
3173
  child.stdin.write(stdinPrefix);
2616
- if (archiveHandshake)
2617
- child.stdin.write(`${JSON.stringify(input ?? "")}\n`);
2618
- else
2619
- child.stdin.end(input);
3174
+ child.stdin.end(input);
2620
3175
  return await completion;
2621
3176
  }
2622
3177
  finally {
2623
- if (archiveHandshake)
3178
+ if (registrationHandshake)
2624
3179
  signal?.removeEventListener("abort", abort);
3180
+ control?.destroy();
2625
3181
  clearTimeout(forceTermination);
2626
3182
  commandSignal?.removeEventListener("abort", settleCanceledChild);
2627
3183
  child.removeListener("exit", settleCanceledChild);
@@ -2632,11 +3188,24 @@ export async function probeCodexSandbox(command, environment, signal) {
2632
3188
  if (process.platform === "win32")
2633
3189
  return;
2634
3190
  // 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);
3191
+ const args = (executable) => [
3192
+ "sandbox",
3193
+ "--",
3194
+ executable,
3195
+ "--version",
3196
+ ];
3197
+ signal?.throwIfAborted();
3198
+ let timeout;
2637
3199
  let detail;
2638
3200
  try {
2639
- const result = await runCodexCommand(command, args, environment, undefined, signal === undefined ? timeout : AbortSignal.any([signal, timeout]));
3201
+ const result = await runCodexCommand(command, args, environment, undefined, () => {
3202
+ // Campaign tool selection happens before the sandbox process starts.
3203
+ signal?.throwIfAborted();
3204
+ timeout = AbortSignal.timeout(SANDBOX_PROBE_TIMEOUT_MILLISECONDS);
3205
+ return signal === undefined
3206
+ ? timeout
3207
+ : AbortSignal.any([signal, timeout]);
3208
+ });
2640
3209
  if (result.success)
2641
3210
  return;
2642
3211
  detail =
@@ -2646,22 +3215,49 @@ export async function probeCodexSandbox(command, environment, signal) {
2646
3215
  }
2647
3216
  catch (error) {
2648
3217
  signal?.throwIfAborted();
2649
- if (timeout.aborted)
3218
+ if (timeout?.aborted)
2650
3219
  throw new SandboxUnavailableError(`Codex sandbox probe timed out after ${SANDBOX_PROBE_TIMEOUT_MILLISECONDS / 1000} seconds.`, { cause: error });
2651
3220
  detail = processErrorDetail(error);
2652
3221
  }
2653
3222
  const guidance = process.platform === "linux"
2654
3223
  ? "\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
3224
  : "";
2656
- throw new SandboxUnavailableError(`Codex could not run a command in its sandbox: ${detail}\nTo reproduce, run '${command.command} ${args.join(" ")}'.${guidance}`);
3225
+ throw new SandboxUnavailableError(`Codex could not run a command in its sandbox: ${detail}\nTo reproduce, run '${command.command} ${args(command.command).join(" ")}'.${guidance}`);
3226
+ }
3227
+ class RolledBackPluginActivationError extends Error {
3228
+ }
3229
+ function isRolledBackPluginActivation(error) {
3230
+ return (error instanceof PluginBootstrapError &&
3231
+ error.cause instanceof RolledBackPluginActivationError);
2657
3232
  }
2658
3233
  async function runPluginCommand(command, args, environment, signal) {
2659
3234
  try {
2660
- const { success, exitCode, stdout, stderr } = await runCodexCommand(command, args, environment, undefined, signal);
3235
+ const run = (argv, cwd) => runCodexCommand(command, argv, environment, undefined, signal, { cwd });
3236
+ let result = await run(args);
3237
+ const source = args[1] === "marketplace" ? args[3] : undefined;
3238
+ if (result.exitCode === 1 &&
3239
+ source?.includes("#") &&
3240
+ result.stderr
3241
+ .split(/\r?\n/u)
3242
+ .includes("Error: --ref is only supported for git marketplace sources")) {
3243
+ // Native Codex parsed a literal hash in the local path as a Git ref.
3244
+ result = await run(["plugin", "marketplace", "add", "."], source);
3245
+ }
3246
+ const { success, exitCode, stdout, stderr } = result;
2661
3247
  if (!success) {
2662
- throw new Error(stderr.trim() ||
3248
+ const detail = stderr.trim() ||
2663
3249
  stdout.trim() ||
2664
- `Codex exited with status ${exitCode}.`);
3250
+ `Codex exited with status ${exitCode}.`;
3251
+ // This native headline is emitted only after the previous entry was
3252
+ // restored. The Windows message itself may be localized.
3253
+ if (process.platform === "win32" &&
3254
+ args[0] === "plugin" &&
3255
+ args[1] === "add" &&
3256
+ exitCode === 1 &&
3257
+ /^Error: failed to activate updated plugin cache entry: [^\r\n]+ \(os error 5\)(?:\r?\n|$)/u.test(stderr) &&
3258
+ !stderr.includes("failed to restore previous cache entry"))
3259
+ throw new RolledBackPluginActivationError(detail);
3260
+ throw new Error(detail);
2665
3261
  }
2666
3262
  return stdout;
2667
3263
  }
@@ -2749,7 +3345,7 @@ async function requirePython(candidate, source, environment, protectedRoot, sign
2749
3345
  }
2750
3346
  async function usablePython(candidate, environment = process.env, protectedRoot = process.cwd(), signal) {
2751
3347
  const command = await resolveTrustedExecutable(isPythonPathCandidate(candidate)
2752
- ? expandExecutableHome(candidate, environment)
3348
+ ? expandHomeForLookup(candidate, environment)
2753
3349
  : candidate, environment, protectedRoot);
2754
3350
  if (command === null)
2755
3351
  return null;
@@ -2772,9 +3368,6 @@ async function usablePython(candidate, environment = process.env, protectedRoot
2772
3368
  export function isPythonPathCandidate(candidate) {
2773
3369
  return candidate.includes("/") || candidate.includes("\\");
2774
3370
  }
2775
- async function hasPluginManifest(root) {
2776
- return await lstat(join(root, ".codex-plugin", "plugin.json")).then((metadata) => metadata.isFile(), () => false);
2777
- }
2778
3371
  /** @internal Compare filesystem identity without depending on path spelling. */
2779
3372
  export function sameFile(left, right) {
2780
3373
  // NTFS file IDs can exceed JavaScript's safe integer range.
@@ -2783,7 +3376,39 @@ export function sameFile(left, right) {
2783
3376
  stat(right, { bigint: true }),
2784
3377
  ]).then(([leftMetadata, rightMetadata]) => sameInode(leftMetadata, rightMetadata), () => false);
2785
3378
  }
2786
- function expandExecutableHome(value, environment) {
3379
+ export function resolveInputPath(value, directory = process.cwd(), environment = process.env) {
3380
+ if (value === "~")
3381
+ value = expandHome("~", environment);
3382
+ else if (value.startsWith("~/") || value.startsWith("~\\")) {
3383
+ const home = expandHome("~", environment);
3384
+ const suffix = value.startsWith("~\\")
3385
+ ? value.slice(2).split("\\").filter(Boolean).join(sep)
3386
+ : value.slice(2);
3387
+ value = home === "" ? suffix : `${home}${sep}${suffix}`;
3388
+ }
3389
+ return resolveTargetPath(value, directory);
3390
+ }
3391
+ /** Resolve through the last parent traversal while retaining aliases in the remaining path. */
3392
+ export async function resolveParentTraversal(path, { allowMissing = false } = {}) {
3393
+ const parts = path.split(sep);
3394
+ const parent = parts.lastIndexOf("..");
3395
+ if (parent === -1)
3396
+ return path;
3397
+ const prefix = parts.slice(0, parent + 1).join(sep);
3398
+ // A new output directory can be spelled missing/../scan before its parent exists.
3399
+ if (allowMissing &&
3400
+ (await stat(prefix).catch(nullIfMissingFileError)) === null) {
3401
+ return resolve(path);
3402
+ }
3403
+ // Resolve each directory before moving to its parent. Some runtimes collapse
3404
+ // a literal ".." inside realpath before consulting the filesystem.
3405
+ const before = parts.slice(0, parent).join(sep) || (isAbsolute(path) ? sep : ".");
3406
+ const physical = dirname(await realpath(await resolveParentTraversal(before)));
3407
+ if (!(await sameFile(prefix, physical)))
3408
+ throw new InvalidTargetError(`Repository path changed: ${prefix}`);
3409
+ return join(physical, ...parts.slice(parent + 1));
3410
+ }
3411
+ export function expandHomeForLookup(value, environment = process.env) {
2787
3412
  const path = value.startsWith("~\\") ? value.replaceAll("\\", "/") : value;
2788
3413
  // Expand only the home prefix; joining the suffix would collapse symlink/.. paths.
2789
3414
  return path.startsWith("~/")