@bitkyc08/opencodex 2.93.0-preview.20261027 → 2.94.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 (435) hide show
  1. package/README.md +27 -8
  2. package/bin/ocx.mjs +215 -63
  3. package/gui/dist/assets/App-DmvwlhQq.js +58 -0
  4. package/gui/dist/assets/Tray-CZatQdoF.js +1 -0
  5. package/gui/dist/assets/index-3EPO_KbX.js +94 -0
  6. package/gui/dist/assets/index-CHWwDo9L.css +1 -0
  7. package/gui/dist/assets/{quota-summary-DxToX1rV.js → quota-summary-BHvWg9mi.js} +1 -1
  8. package/gui/dist/index.html +2 -2
  9. package/gui/dist/provider-icons/t3code.svg +4 -0
  10. package/package.json +7 -4
  11. package/src/adapters/anthropic/account-metadata.ts +34 -3
  12. package/src/adapters/anthropic/beta-allowlist.ts +5 -5
  13. package/src/adapters/anthropic/passthrough.ts +5 -2
  14. package/src/adapters/anthropic.ts +17 -4
  15. package/src/adapters/antigravity-refusal.ts +29 -0
  16. package/src/adapters/base.ts +11 -1
  17. package/src/adapters/client-fingerprint.ts +43 -9
  18. package/src/adapters/coding-agent/protocol.ts +19 -9
  19. package/src/adapters/command-code.ts +4 -5
  20. package/src/adapters/cursor/catalog.ts +5 -3
  21. package/src/adapters/cursor/claude-id.ts +30 -19
  22. package/src/adapters/cursor/cursor-errors.ts +5 -2
  23. package/src/adapters/cursor/h2-pool.ts +9 -7
  24. package/src/adapters/cursor/http1-bidi.ts +1 -0
  25. package/src/adapters/cursor/live-models.ts +4 -2
  26. package/src/adapters/cursor.ts +4 -1
  27. package/src/adapters/devin/cloud-direct/chat.ts +18 -2
  28. package/src/adapters/google-antigravity-replay.ts +13 -2
  29. package/src/adapters/google-antigravity-wire.ts +8 -3
  30. package/src/adapters/google-errors.ts +33 -0
  31. package/src/adapters/google-http.ts +41 -16
  32. package/src/adapters/google-wire-compiler.ts +4 -0
  33. package/src/adapters/google.ts +21 -10
  34. package/src/adapters/kiro/adapter.ts +3 -0
  35. package/src/adapters/kiro/stream.ts +18 -13
  36. package/src/adapters/openai-chat/completed-tool-blocks.ts +65 -0
  37. package/src/adapters/openai-chat/messages.ts +22 -10
  38. package/src/adapters/openai-chat/required-tool-result.ts +3 -3
  39. package/src/adapters/openai-chat/serialized-tool-call-content.ts +5 -0
  40. package/src/adapters/openai-chat/wire.ts +9 -0
  41. package/src/adapters/openai-chat.ts +18 -17
  42. package/src/adapters/openai-responses/image-gen.ts +15 -1
  43. package/src/adapters/openai-responses/passthrough.ts +11 -34
  44. package/src/adapters/openai-responses/transport.ts +20 -2
  45. package/src/adapters/openai-responses/usage.ts +34 -0
  46. package/src/adapters/qoder/adapter.ts +9 -15
  47. package/src/adapters/qoder/image-input.ts +52 -0
  48. package/src/adapters/unique-tool-call-ids.ts +2 -2
  49. package/src/adapters/zed-additional-tools.ts +51 -0
  50. package/src/adapters/zed-diagnostic-usage.ts +22 -0
  51. package/src/adapters/zed-json-tokens.ts +166 -0
  52. package/src/adapters/zed-openai-stream.ts +723 -0
  53. package/src/adapters/zed-tool-arguments.ts +79 -0
  54. package/src/adapters/zed.ts +53 -3
  55. package/src/advisor/consult.ts +22 -0
  56. package/src/advisor/runtime.ts +3 -0
  57. package/src/bridge/errors.ts +22 -1
  58. package/src/bridge/response-json.ts +4 -1
  59. package/src/bridge/sse.ts +21 -12
  60. package/src/chat/inbound.ts +13 -2
  61. package/src/chatgpt/app-server-shim/bundle-trust-async.ts +111 -0
  62. package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +83 -0
  63. package/src/chatgpt/app-server-shim/bundle-trust.ts +15 -72
  64. package/src/claude/desktop-first-party.ts +16 -5
  65. package/src/claude/desktop-gateway-state.ts +4 -0
  66. package/src/claude/inbound-tool-loading.ts +93 -0
  67. package/src/claude/intercept/picker-listener.ts +33 -1
  68. package/src/claude/model-info.ts +29 -4
  69. package/src/claude/outbound.ts +33 -13
  70. package/src/cli/account-main.ts +43 -5
  71. package/src/cli/capabilities-base.ts +22 -5
  72. package/src/cli/capabilities-integrations.ts +4 -4
  73. package/src/cli/claude-desktop.ts +139 -98
  74. package/src/cli/codex-cli-update.ts +102 -48
  75. package/src/cli/codex-launch-auth.ts +93 -0
  76. package/src/cli/codex-launch-command.ts +32 -0
  77. package/src/cli/codex-launch-diagnostics.ts +37 -0
  78. package/src/cli/codex-launch-ownership.ts +307 -0
  79. package/src/cli/codex-launch-policy.ts +84 -0
  80. package/src/cli/codex-launcher.ts +310 -0
  81. package/src/cli/codex-shim-autorestore.ts +2 -0
  82. package/src/cli/config-command.ts +9 -4
  83. package/src/cli/config-mutation.ts +13 -0
  84. package/src/cli/dispatch.ts +13 -7
  85. package/src/cli/effort.ts +19 -14
  86. package/src/cli/ensure-desired-integrations.ts +21 -14
  87. package/src/cli/ensure-desktop-cold-start.ts +41 -10
  88. package/src/cli/export-command.ts +8 -4
  89. package/src/cli/help.ts +3 -1
  90. package/src/cli/index.ts +58 -64
  91. package/src/cli/integration-input.ts +12 -0
  92. package/src/cli/integration-plan-dto.ts +2 -0
  93. package/src/cli/integration-preview.ts +6 -3
  94. package/src/cli/integrations.ts +2 -1
  95. package/src/cli/link-cleanup.ts +8 -23
  96. package/src/cli/link-enrollment.ts +1 -4
  97. package/src/cli/link.ts +1 -1
  98. package/src/cli/loopback-family.ts +2 -31
  99. package/src/cli/models.ts +62 -49
  100. package/src/cli/provider.ts +146 -139
  101. package/src/cli/registry.ts +34 -3
  102. package/src/cli/root.ts +2 -0
  103. package/src/cli/start-owner-fence.ts +22 -3
  104. package/src/cli/status-link.ts +28 -0
  105. package/src/cli/status.ts +15 -0
  106. package/src/cli/stop-restore-guard.ts +48 -0
  107. package/src/cli/stop-restore.ts +117 -36
  108. package/src/cli/system-command.ts +2 -0
  109. package/src/cli/v2.ts +17 -4
  110. package/src/client/lifecycle-lock.ts +1 -1
  111. package/src/client/link-connection.ts +19 -0
  112. package/src/client/link-relay-transport.ts +25 -3
  113. package/src/client/link-tunnel.ts +10 -0
  114. package/src/client/machine-listener.ts +7 -1
  115. package/src/client/restore-ownership.ts +45 -0
  116. package/src/client/runtime.ts +13 -1
  117. package/src/client/state.ts +1 -1
  118. package/src/clients/client-ids.ts +7 -0
  119. package/src/clients/client-path.ts +13 -5
  120. package/src/clients/config-export/agent-clients.ts +3 -6
  121. package/src/clients/config-export/alias-selectors.ts +85 -0
  122. package/src/clients/config-export/contracts.ts +6 -25
  123. package/src/clients/config-export/dsh.ts +8 -1
  124. package/src/clients/config-export/model-metadata.ts +19 -0
  125. package/src/clients/config-export/model-names.ts +31 -0
  126. package/src/clients/config-export/qoder.ts +3 -11
  127. package/src/clients/config-export/t3code.ts +141 -0
  128. package/src/clients/config-export.ts +51 -15
  129. package/src/clients/gentle-shell-path.ts +3 -3
  130. package/src/codex/account-lifecycle.ts +27 -13
  131. package/src/codex/account-store.ts +32 -6
  132. package/src/codex/app-server-processes.ts +84 -1
  133. package/src/codex/auth-api/main-account-probe.ts +50 -11
  134. package/src/codex/auth-api/pool-mode-gate.ts +16 -8
  135. package/src/codex/auth-context.ts +45 -4
  136. package/src/codex/catalog/antigravity-discovery.ts +59 -0
  137. package/src/codex/catalog/build-entries.ts +12 -13
  138. package/src/codex/catalog/bundled.ts +59 -9
  139. package/src/codex/catalog/derive-entry.ts +2 -0
  140. package/src/codex/catalog/gather-capture.ts +3 -0
  141. package/src/codex/catalog/metadata.ts +6 -5
  142. package/src/codex/catalog/model-hints.ts +36 -4
  143. package/src/codex/catalog/native-priority.ts +63 -0
  144. package/src/codex/catalog/provider-models.ts +20 -4
  145. package/src/codex/catalog/retained-sync.ts +1 -1
  146. package/src/codex/chatgpt-refresh-failure.ts +2 -2
  147. package/src/codex/cli-install-provenance.ts +57 -29
  148. package/src/codex/cli-installation-identity.ts +1 -1
  149. package/src/codex/cli-installation-limits.ts +7 -0
  150. package/src/codex/cli-update-apply.ts +391 -0
  151. package/src/codex/cli-update-artifacts.ts +257 -0
  152. package/src/codex/cli-update-files.ts +100 -0
  153. package/src/codex/cli-update-inspection-context.ts +49 -0
  154. package/src/codex/cli-update-job-execution.ts +77 -0
  155. package/src/codex/cli-update-job-store-windows.ts +1010 -0
  156. package/src/codex/cli-update-job-worker.ts +393 -0
  157. package/src/codex/cli-update-job.ts +369 -0
  158. package/src/codex/cli-update-lease.ts +71 -0
  159. package/src/codex/cli-update-paths.ts +76 -0
  160. package/src/codex/cli-update-plan.ts +180 -47
  161. package/src/codex/cli-update-recovery.ts +236 -0
  162. package/src/codex/cli-update-selection-gate.ts +235 -0
  163. package/src/codex/cli-update-windows-apply.ts +308 -0
  164. package/src/codex/cli-update-windows-layout.ts +110 -0
  165. package/src/codex/cli-update-windows-observation.ts +91 -0
  166. package/src/codex/cli-update-windows-paths.ts +26 -0
  167. package/src/codex/cli-update-worker-recovery.ts +32 -0
  168. package/src/codex/cli-update-worker.ts +185 -0
  169. package/src/codex/cli-windows-plan-provenance.ts +250 -0
  170. package/src/codex/desktop-app-restart.ts +22 -3
  171. package/src/codex/exec-boundary.ts +208 -0
  172. package/src/codex/forward-transport-headers.ts +80 -0
  173. package/src/codex/history-job.ts +7 -0
  174. package/src/codex/history-provider.ts +5 -2
  175. package/src/codex/history-worker.ts +20 -1
  176. package/src/codex/inject/restore.ts +57 -25
  177. package/src/codex/internal/history-writer.ts +2 -1
  178. package/src/codex/mac-app-bundle.ts +52 -0
  179. package/src/codex/main-account.ts +161 -23
  180. package/src/codex/native-main-auth-temp.ts +3 -2
  181. package/src/codex/native-main-refresh-mode.ts +18 -3
  182. package/src/codex/native-profile-manager.ts +8 -6
  183. package/src/codex/native-profile-store.ts +9 -0
  184. package/src/codex/ocx-compaction-history.ts +3 -2
  185. package/src/codex/prompt-text-probe.ts +211 -69
  186. package/src/codex/quota.ts +9 -0
  187. package/src/codex/role-model-history.ts +253 -0
  188. package/src/codex/runtime.ts +120 -71
  189. package/src/codex/shim-overlay.ts +22 -3
  190. package/src/codex/shim-templates.ts +5 -2
  191. package/src/codex/shim-wrapper-write.ts +136 -0
  192. package/src/codex/shim.ts +24 -125
  193. package/src/codex/windows-cli-child-native.ts +119 -0
  194. package/src/codex/windows-cli-child-pipe.ts +87 -0
  195. package/src/codex/windows-cli-child.ts +260 -0
  196. package/src/codex/windows-cli-recovery-guardian.ts +89 -0
  197. package/src/codex/windows-cli-recovery.ts +39 -0
  198. package/src/codex/windows-installation-files.ts +52 -6
  199. package/src/codex/windows-npm-execution.ts +25 -0
  200. package/src/combos/failover.ts +84 -5
  201. package/src/combos/index.ts +1 -0
  202. package/src/combos/resolve.ts +60 -22
  203. package/src/config/atomic-write.ts +75 -22
  204. package/src/config/diagnostics.ts +18 -10
  205. package/src/config/live-reconcile.ts +11 -3
  206. package/src/config/owner-registry.ts +5 -4
  207. package/src/config/persist-unlocked.ts +34 -8
  208. package/src/config/persisted-mutation.ts +7 -0
  209. package/src/config/process-state.ts +9 -5
  210. package/src/config/removed-opencode-free-backup.ts +99 -0
  211. package/src/config/removed-opencode-free.ts +4 -8
  212. package/src/config/salvage.ts +1 -0
  213. package/src/config/schema/config-schema.ts +16 -1
  214. package/src/config/schema/leaf-validators.ts +15 -0
  215. package/src/config.ts +4 -4
  216. package/src/generated/compatibility-version.json +743 -315
  217. package/src/grok/inject.ts +2 -1
  218. package/src/grok/sync.ts +5 -2
  219. package/src/images/loop.ts +14 -5
  220. package/src/integrations/catalog-refresh.ts +1 -1
  221. package/src/integrations/hermes-refresh.ts +28 -0
  222. package/src/integrations/model-name-guard.ts +31 -0
  223. package/src/integrations/mutation-plan.ts +17 -4
  224. package/src/integrations/ownership.ts +3 -0
  225. package/src/integrations/registry.ts +10 -1
  226. package/src/integrations/state.ts +6 -0
  227. package/src/integrations/writer.ts +64 -59
  228. package/src/lib/abort.ts +8 -4
  229. package/src/lib/bounded-body.ts +7 -1
  230. package/src/lib/config-ownership.ts +4 -0
  231. package/src/lib/errors.ts +2 -0
  232. package/src/lib/eventstream-decoder.ts +3 -2
  233. package/src/lib/http-response-semantics.ts +9 -6
  234. package/src/lib/inbound-body-policy.ts +11 -0
  235. package/src/lib/jsonc.ts +7 -2
  236. package/src/lib/local-management-capability.ts +3 -1
  237. package/src/lib/local-upstream.ts +22 -26
  238. package/src/lib/loopback-family.ts +31 -0
  239. package/src/lib/plain-data.ts +7 -5
  240. package/src/lib/process-control.ts +30 -5
  241. package/src/lib/shadow-call.ts +55 -1
  242. package/src/lib/tool-argument-integers.ts +99 -7
  243. package/src/lib/upstream-retry.ts +6 -1
  244. package/src/lib/windows-elevation.ts +34 -11
  245. package/src/lib/windows-owner-acl.ts +272 -32
  246. package/src/lib/windows-secret-acl.ts +310 -44
  247. package/src/lib/windows-service-wrappers.ts +10 -7
  248. package/src/lib/winsw.ts +8 -4
  249. package/src/link/relay-auth.ts +38 -1
  250. package/src/link/remote-platform.ts +11 -23
  251. package/src/link/remote-probe.ts +3 -1
  252. package/src/link/remote-windows.ts +150 -0
  253. package/src/link/ssh-argv.ts +13 -5
  254. package/src/link/store.ts +4 -1
  255. package/src/link/supervisor.ts +9 -0
  256. package/src/local-credentials/generation.ts +238 -0
  257. package/src/local-credentials/inventory.ts +281 -0
  258. package/src/local-credentials/observation-lease.ts +83 -0
  259. package/src/local-credentials/publication-fence.ts +81 -0
  260. package/src/local-credentials/references.ts +36 -0
  261. package/src/local-credentials/runtime-observation.ts +28 -0
  262. package/src/oauth/account-auto-pause-policy.ts +11 -0
  263. package/src/oauth/anthropic-account-refusal.ts +1 -0
  264. package/src/oauth/anthropic-rate-limit-policy.ts +26 -2
  265. package/src/oauth/anthropic-routing.ts +34 -44
  266. package/src/oauth/anthropic-session-affinity-store.ts +177 -0
  267. package/src/oauth/chatgpt.ts +11 -9
  268. package/src/oauth/cursor.ts +8 -2
  269. package/src/oauth/generic-account-failover.ts +33 -2
  270. package/src/oauth/generic-session-affinity.ts +7 -0
  271. package/src/oauth/google-antigravity.ts +29 -5
  272. package/src/oauth/index.ts +1 -0
  273. package/src/oauth/store.ts +32 -4
  274. package/src/protocols/encoders/adapter-events.ts +7 -4
  275. package/src/protocols/encoders/messages.ts +1 -1
  276. package/src/providers/antigravity-account-roster.ts +73 -7
  277. package/src/providers/antigravity-models.ts +8 -4
  278. package/src/providers/api-key-resolve.ts +16 -3
  279. package/src/providers/claude-cli-identity.ts +2 -0
  280. package/src/providers/codex-capacity.ts +3 -2
  281. package/src/providers/free-directory.ts +10 -2
  282. package/src/providers/key-store.ts +7 -2
  283. package/src/providers/provider-id-rewrite.ts +3 -0
  284. package/src/providers/quota/antigravity.ts +6 -4
  285. package/src/providers/quota/vendor-probes-oauth.ts +0 -1
  286. package/src/providers/stale-model-roster-migration.ts +3 -0
  287. package/src/quota-pool/assemble.ts +51 -21
  288. package/src/quota-pool/pooled.ts +162 -0
  289. package/src/remote-control/workspace-codex-runtime.ts +63 -20
  290. package/src/responses/apply-patch-envelope.ts +35 -0
  291. package/src/responses/compaction-history-framing.ts +15 -4
  292. package/src/responses/turn-membership.ts +111 -0
  293. package/src/server/advisor-admission-scope.ts +43 -0
  294. package/src/server/audio-upstream.ts +10 -2
  295. package/src/server/auth-cors.ts +23 -0
  296. package/src/server/bind-host.ts +5 -0
  297. package/src/server/chat-completions.ts +17 -2
  298. package/src/server/chat-native.ts +16 -11
  299. package/src/server/claude-messages.ts +9 -1
  300. package/src/server/codex-model-list.ts +46 -0
  301. package/src/server/gui-session.ts +5 -2
  302. package/src/server/inbound-body-admission.ts +21 -13
  303. package/src/server/inbound-body-budget.ts +128 -0
  304. package/src/server/index/link-listener.ts +3 -1
  305. package/src/server/index/link-relay-sessions.ts +9 -2
  306. package/src/server/index/optional-listeners.ts +1 -0
  307. package/src/server/index/serve-options.ts +9 -43
  308. package/src/server/index/websocket-handler.ts +7 -0
  309. package/src/server/index.ts +6 -5
  310. package/src/server/inference/client-encoder-delivery.ts +3 -1
  311. package/src/server/lifecycle.ts +8 -1
  312. package/src/server/management/advisor-routes.ts +26 -9
  313. package/src/server/management/agent-settings-routes.ts +424 -543
  314. package/src/server/management/anthropic-reset-grant-routes.ts +2 -1
  315. package/src/server/management/claude-code-settings-patch.ts +211 -0
  316. package/src/server/management/claude-desktop-config-writers.ts +78 -0
  317. package/src/server/management/codex-agent-role-routes.ts +79 -2
  318. package/src/server/management/codex-cli-update-routes.ts +55 -0
  319. package/src/server/management/codex-prompt-routes.ts +2 -1
  320. package/src/server/management/config-routes.ts +444 -380
  321. package/src/server/management/consent-session.ts +6 -0
  322. package/src/server/management/desktop-compatibility-authorization.ts +12 -0
  323. package/src/server/management/desktop-compatibility-routes.ts +3 -2
  324. package/src/server/management/desktop-compatibility-runtime-routes.ts +2 -1
  325. package/src/server/management/desktop-compatibility-settings-routes.ts +2 -1
  326. package/src/server/management/integration-routes.ts +45 -5
  327. package/src/server/management/link-enrollment.ts +21 -32
  328. package/src/server/management/link-route-state.ts +1 -0
  329. package/src/server/management/link-routes.ts +4 -1
  330. package/src/server/management/model-routes.ts +22 -6
  331. package/src/server/management/model-rows.ts +3 -1
  332. package/src/server/management/native-integration-routes.ts +90 -38
  333. package/src/server/management/oauth-account-routes.ts +8 -7
  334. package/src/server/management/route-registry.ts +8 -3
  335. package/src/server/management/session-routes.ts +20 -2
  336. package/src/server/management/shadow-call-validation.ts +43 -2
  337. package/src/server/management/sidebar-routes.ts +2 -1
  338. package/src/server/management/system-restart.ts +47 -7
  339. package/src/server/management-api.ts +61 -51
  340. package/src/server/management-auth.ts +11 -3
  341. package/src/server/messages-native.ts +21 -7
  342. package/src/server/messages-shared.ts +110 -18
  343. package/src/server/persistent-gui-session.ts +155 -0
  344. package/src/server/port-reclaim.ts +29 -5
  345. package/src/server/proxy-liveness.ts +110 -33
  346. package/src/server/request-decompress.ts +5 -1
  347. package/src/server/responses/account-change-state.ts +14 -2
  348. package/src/server/responses/adapter-continuation.ts +5 -4
  349. package/src/server/responses/adapter-delivery.ts +20 -5
  350. package/src/server/responses/adapter-dispatch.ts +39 -45
  351. package/src/server/responses/advisor-plan-slot.ts +3 -0
  352. package/src/server/responses/advisor-slot.ts +4 -2
  353. package/src/server/responses/antigravity-model-denial-recovery.ts +70 -0
  354. package/src/server/responses/antigravity-validation-refusal.ts +6 -0
  355. package/src/server/responses/combo-required-tool-contract.ts +2 -1
  356. package/src/server/responses/combo-required-tool-fulfillments.ts +58 -0
  357. package/src/server/responses/combo-required-tool-stream.ts +119 -0
  358. package/src/server/responses/combo-stream-preflight.ts +47 -7
  359. package/src/server/responses/compact.ts +14 -7
  360. package/src/server/responses/compaction-recovery.ts +2 -1
  361. package/src/server/responses/core-auth.ts +2 -1
  362. package/src/server/responses/core-codex-account.ts +1 -0
  363. package/src/server/responses/core-combo-failure.ts +11 -6
  364. package/src/server/responses/core-combo-native.ts +6 -5
  365. package/src/server/responses/core-combo.ts +93 -20
  366. package/src/server/responses/core-options.ts +7 -0
  367. package/src/server/responses/fetch-helpers.ts +5 -1
  368. package/src/server/responses/jev-model-invoke.ts +8 -3
  369. package/src/server/responses/memory-models.ts +3 -2
  370. package/src/server/responses/passthrough-delivery.ts +36 -8
  371. package/src/server/responses/passthrough-dispatch.ts +12 -12
  372. package/src/server/responses/request-prepare.ts +10 -1
  373. package/src/server/responses/request-transport.ts +41 -6
  374. package/src/server/responses/run-turn-execution.ts +11 -3
  375. package/src/server/responses/sidecar-execution.ts +5 -0
  376. package/src/server/responses/turn-membership.ts +30 -0
  377. package/src/server/responses-custom-tool-repair.ts +86 -11
  378. package/src/server/responses-image-gen-repair.ts +1 -1
  379. package/src/server/restart-parent-ownership.ts +49 -0
  380. package/src/server/stop-teardown.ts +46 -9
  381. package/src/server/windows-tcp-drop.ts +4 -2
  382. package/src/service/desktop-recovery-process.ts +341 -0
  383. package/src/service/desktop-recovery.ts +172 -0
  384. package/src/service/windows-ops.ts +6 -3
  385. package/src/service/windows-scheduler.ts +29 -6
  386. package/src/stall-timeout.ts +47 -0
  387. package/src/tray/windows.ts +6 -4
  388. package/src/types/config.ts +61 -10
  389. package/src/types/request.ts +1 -1
  390. package/src/types.ts +1 -0
  391. package/src/update/async-check.ts +4 -3
  392. package/src/update/bind-probe.ts +2 -2
  393. package/src/update/codex-cli-update-launch-policy.mjs +9 -0
  394. package/src/update/guarded-port-reclaim.ts +14 -0
  395. package/src/update/guarded-runtime-ops.ts +58 -0
  396. package/src/update/guarded-tray-ops.ts +9 -0
  397. package/src/update/index.ts +196 -58
  398. package/src/update/job-pinned-start.ts +53 -0
  399. package/src/update/job-supervised-restart.ts +23 -6
  400. package/src/update/job-update-home.ts +62 -0
  401. package/src/update/job-update-tray.ts +29 -0
  402. package/src/update/job-windows-restart.ts +39 -0
  403. package/src/update/job.ts +179 -193
  404. package/src/update/mutation-guard.d.mts +30 -0
  405. package/src/update/mutation-guard.mjs +103 -0
  406. package/src/update/notify.ts +2 -2
  407. package/src/update/npm-cache-preflight.mjs +4 -4
  408. package/src/update/npm-install.mjs +5 -3
  409. package/src/update/pnpm-read-policy.mjs +3 -2
  410. package/src/update/proxy-liveness-probe.mjs +2 -2
  411. package/src/update/service-home-authority.ts +35 -0
  412. package/src/update/service-home-package-only-protocol.json +1 -0
  413. package/src/update/service-home-policy.d.mts +25 -0
  414. package/src/update/service-home-policy.mjs +112 -0
  415. package/src/update/service-home-probe-entry.ts +9 -0
  416. package/src/update/service-home-probe.d.mts +15 -0
  417. package/src/update/service-home-probe.mjs +79 -0
  418. package/src/update/service-home-protocol.json +1 -0
  419. package/src/update/supervised-recovery.d.mts +2 -2
  420. package/src/update/supervised-recovery.mjs +14 -7
  421. package/src/update/transactional-install.d.mts +3 -1
  422. package/src/update/transactional-install.mjs +29 -19
  423. package/src/update/update-failure-guidance.mjs +1 -1
  424. package/src/update/worker-launch.ts +3 -3
  425. package/src/vision/anthropic-describe.ts +2 -1
  426. package/src/web-search/anthropic-executor.ts +2 -1
  427. package/src/web-search/anthropic-history.ts +1 -0
  428. package/src/web-search/format-result.ts +3 -2
  429. package/src/web-search/header-deadline.ts +3 -2
  430. package/src/web-search/loop.ts +10 -4
  431. package/src/web-search/parse.ts +191 -38
  432. package/gui/dist/assets/App-CJZoq-uF.js +0 -58
  433. package/gui/dist/assets/Tray-BWQPcgZn.js +0 -1
  434. package/gui/dist/assets/index-DRe8Hhfz.css +0 -1
  435. package/gui/dist/assets/index-Xfct8owH.js +0 -94
@@ -0,0 +1,1010 @@
1
+ /**
2
+ * Windows backend for the Codex CLI update job ledger.
3
+ *
4
+ * Parallel contract to the POSIX primitives in cli-update-job.ts, mapped onto NTFS
5
+ * handle semantics instead of uid/mode/O_NOFOLLOW:
6
+ *
7
+ * - Ancestry: the volume root is opened through its GUID mount path and pinned
8
+ * as the trust anchor; its own ACL is not part of the batch — the held handle,
9
+ * not a policy verdict, is what anchors the chain. Every directory below it
10
+ * down to the config parent is opened handle-relative from the already-held
11
+ * parent (never a re-parsed path), held with FILE_SHARE_READ|FILE_SHARE_WRITE
12
+ * so nothing can rename or delete it while held, and refused on any reparse
13
+ * attribute. Each of those directories has its ACL read once per phase through
14
+ * the shared PowerShell protocol under the "trusted-ancestry" policy: the
15
+ * owner must be the serving token or a kernel-equivalent owner
16
+ * (SYSTEM, Administrators, TrustedInstaller — each can already take ownership
17
+ * of any object, so an ACL entry grants them nothing they lack), and no other
18
+ * grantee may hold write, create-inside, delete or DACL/owner control. Broad
19
+ * create-only grants are accepted only on admin-owned ancestors, which is the
20
+ * NTFS analog of a root-owned sticky directory: the stock C:\ ACL grants
21
+ * Authenticated Users add-subdirectory and nothing else.
22
+ * - The config root's parent must be owned by the serving token and grant no
23
+ * untrusted write access ("write-private", the POSIX mode&022==0 analog). A
24
+ * pre-existing config root is verified only — never rehardened — under the
25
+ * same policy. A config root or store directory created by this call is
26
+ * icacls-hardened and then held to the strict "private" rule.
27
+ * - The store directory and every ledger file must satisfy strict "private":
28
+ * a protected DACL owned by the serving token with grantees limited to the
29
+ * user plus SYSTEM/Administrators — the same shape the POSIX 0700/0600 modes
30
+ * express.
31
+ * - File identity is the NTFS volume serial + 128-bit file ID (the dev:ino
32
+ * analog), with NumberOfLinks == 1 and DeletePending clear, mirroring the
33
+ * POSIX nlink and lstat-vs-fstat checks.
34
+ * - Writes go through a private temp file: exclusive create, harden, fsync,
35
+ * identity+ACL+byte verify, handle-bound rename, then identity/ACL/byte
36
+ * readback on the renamed object and a directory flush. The temp handle
37
+ * denies foreign write/delete opens, so the object renamed is provably the
38
+ * one written — and the destination is never opened deny-delete, which would
39
+ * otherwise block the rename itself.
40
+ * - The admission lock is a mkdir mutex like POSIX: EEXIST maps to
41
+ * job_store_busy with no reclamation. owner.json is written under the held
42
+ * lock pin; release deletes the owner file and lock directory only through
43
+ * the pins whose identity and content still match what this call created,
44
+ * so a replacement is never removed by this process and a leftover lock
45
+ * blocks later admission, exactly like POSIX.
46
+ *
47
+ * Honesty notes: pins bind each object to its verified state for the length of
48
+ * the operation and the private DACL restricts writers to the trusted set; that
49
+ * is the strongest binding Windows affords, but it is not a proof against
50
+ * concurrent mutation by the serving account or an elevated process, which sit
51
+ * inside the trust boundary exactly as on POSIX. Each mutation step is bracketed
52
+ * by a fresh identity observation or ACL read rather than claimed TOCTOU-free.
53
+ * x64 only: the FFI layouts below are the x64 ABI. Cross-account (other-SID)
54
+ * behavior is unverified: the DACL policy is the enforcement claim, not an
55
+ * empirical cross-user proof.
56
+ */
57
+ import { createHash, randomUUID } from "node:crypto";
58
+ import { closeSync, fsyncSync, mkdirSync, openSync, readdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
59
+ import { basename, join, resolve, toNamespacedPath } from "node:path";
60
+ import type { Library, Symbols } from "bun:ffi";
61
+ import * as recoveryFfi from "bun:ffi";
62
+ import { getConfigDir } from "../config/paths";
63
+ import { assertNotRealHomeUnderTest } from "../lib/test-home-guard";
64
+ import { forgetEphemeralSecretPath, hardenSecretDir, hardenSecretPath, hardenSecretDirAsync, hardenSecretPathAsync } from "../lib/windows-secret-acl";
65
+ import { verifyWindowsEntriesAcl, verifyWindowsEntriesAclAsync, type WindowsAclEntry } from "../lib/windows-owner-acl";
66
+ import { retryWindowsFileOperation } from "../lib/windows-atomic-replace";
67
+ import {
68
+ CODEX_CLI_JOB_STORE_DIR, CODEX_CLI_JOB_STORE_FILE, CODEX_CLI_JOB_STORE_LOCK,
69
+ CODEX_CLI_JOB_STORE_MAX_BYTES, CodexCliJobStoreBusyError,
70
+ } from "./cli-update-job-execution";
71
+ import { windowsCanonicalPathMatches } from "./windows-installation-files";
72
+
73
+ const KERNEL_SYMBOLS = {
74
+ GetDriveTypeW: { args: ["ptr"], returns: "u32" },
75
+ GetVolumeNameForVolumeMountPointW: { args: ["ptr", "ptr", "u32"], returns: "i32" },
76
+ CreateFileW: { args: ["ptr", "u32", "u32", "ptr", "u32", "u32", "u64"], returns: "u64" },
77
+ GetFileInformationByHandleEx: { args: ["u64", "i32", "ptr", "u32"], returns: "i32" },
78
+ SetFileInformationByHandle: { args: ["u64", "i32", "ptr", "u32"], returns: "i32" },
79
+ GetFileType: { args: ["u64"], returns: "u32" },
80
+ GetFinalPathNameByHandleW: { args: ["u64", "ptr", "u32", "u32"], returns: "u32" },
81
+ ReadFile: { args: ["u64", "ptr", "u32", "ptr", "ptr"], returns: "i32" },
82
+ SetFilePointerEx: { args: ["u64", "i64", "ptr", "u32"], returns: "i32" },
83
+ FlushFileBuffers: { args: ["u64"], returns: "i32" },
84
+ CloseHandle: { args: ["u64"], returns: "i32" },
85
+ } as const satisfies Symbols;
86
+ const NT_SYMBOLS = {
87
+ NtCreateFile: { args: ["ptr", "u32", "ptr", "ptr", "ptr", "u32", "u32", "u32", "u32", "ptr", "u32"], returns: "i32" },
88
+ } as const satisfies Symbols;
89
+
90
+ const REPARSE = 0x400;
91
+ const DIRECTORY_ATTR = 0x10;
92
+ const INVALID_HANDLE = 0xffffffffffffffffn;
93
+ /** Directory pins deny delete (and therefore rename) but allow read/write opens. */
94
+ const SHARE_DIR = 0x3; // FILE_SHARE_READ | FILE_SHARE_WRITE
95
+ /** Ledger-file pins deny write and delete opens; only reads are shared. */
96
+ const SHARE_LEAF = 0x1; // FILE_SHARE_READ
97
+ /** Read-verify opens must also permit a held delete-capable sibling pin to coexist. */
98
+ const SHARE_LEAF_VERIFY = 0x5; // FILE_SHARE_READ | FILE_SHARE_DELETE
99
+ // SYNCHRONIZE | FILE_READ_ATTRIBUTES | FILE_READ_DATA — ancestors and read-only anchors.
100
+ const ACCESS_READ = 0x100081;
101
+ // SYNCHRONIZE | READ_CONTROL | DELETE | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES
102
+ // | FILE_DELETE_CHILD | FILE_ADD_SUBDIRECTORY | FILE_ADD_FILE | FILE_LIST_DIRECTORY
103
+ // Owned directories we may flush or remove; the DACL we verified grants them anyway.
104
+ const ACCESS_DIR_WRITE = 0x100000 | 0x20000 | 0x10000 | 0x100 | 0x80 | 0x40 | 0x4 | 0x2 | 0x1;
105
+ // The store directory pin needs the same write side minus DELETE: it is flushed and
106
+ // used as a rename root but is never itself deleted. Holding DELETE would force every
107
+ // coexisting opener (e.g., a concurrent status reader) to offer share-delete.
108
+ const ACCESS_DIR_PIN = ACCESS_DIR_WRITE & ~0x10000;
109
+ // SYNCHRONIZE | READ_CONTROL | DELETE | FILE_READ_ATTRIBUTES | FILE_READ_DATA — ledger
110
+ // files held for read/verify/disposition-delete.
111
+ const ACCESS_LEAF = 0x130081;
112
+ const ACL_VERIFY_TIMEOUT_MS = 5_000;
113
+ const FILE_OPEN = 1;
114
+ // FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT, plus the object-kind bit.
115
+ const DIR_OPTIONS = 0x200020 | 0x1;
116
+ const FILE_OPTIONS = 0x200020 | 0x40;
117
+
118
+ interface StoreIdentity { readonly volumeSerial: string; readonly fileId: string }
119
+ interface StoreInspection extends StoreIdentity {
120
+ readonly size: number;
121
+ readonly links: number;
122
+ readonly deletePending: boolean;
123
+ }
124
+
125
+ interface Native {
126
+ ffi: typeof import("bun:ffi");
127
+ kernel: Library<typeof KERNEL_SYMBOLS>;
128
+ nt: Library<typeof NT_SYMBOLS>;
129
+ }
130
+
131
+ let nativePromise: Promise<Native> | undefined;
132
+ function loadNative(): Promise<Native> {
133
+ if (process.platform !== "win32" || process.arch !== "x64") {
134
+ return Promise.reject(new Error("unsupported_store"));
135
+ }
136
+ nativePromise ??= (async () => {
137
+ const ffi = await import("bun:ffi");
138
+ return { ffi, kernel: ffi.dlopen("kernel32.dll", KERNEL_SYMBOLS), nt: ffi.dlopen("ntdll.dll", NT_SYMBOLS) };
139
+ })().catch(() => { nativePromise = undefined; throw new Error("unsupported_store"); });
140
+ return nativePromise;
141
+ }
142
+
143
+ const unsafe = (): Error => new Error("unsafe_store");
144
+ const enoent = (): NodeJS.ErrnoException => Object.assign(new Error("ENOENT"), { code: "ENOENT" });
145
+
146
+ // General ledger callers retain their existing best-effort close contract.
147
+ class PinSet {
148
+ private readonly handles: bigint[] = [];
149
+ keep(handle: bigint): bigint { this.handles.push(handle); return handle; }
150
+ release(handle: bigint, kernel: Library<typeof KERNEL_SYMBOLS>): void {
151
+ const index = this.handles.lastIndexOf(handle);
152
+ if (index >= 0) this.handles.splice(index, 1);
153
+ kernel.symbols.CloseHandle(handle);
154
+ }
155
+ closeAll(kernel: Library<typeof KERNEL_SYMBOLS>): void {
156
+ for (const handle of this.handles.splice(0).reverse()) kernel.symbols.CloseHandle(handle);
157
+ }
158
+ }
159
+
160
+ /** Strict disposal is scoped to apply authority, not ordinary ledger/status I/O. */
161
+ export class WindowsApplyAuthorityPins extends PinSet {
162
+ private readonly authorityHandles: bigint[] = [];
163
+ private readonly failedCloses = new Set<bigint>();
164
+ get remaining(): number { return this.authorityHandles.length; }
165
+ override keep(handle: bigint): bigint { this.authorityHandles.push(handle); return handle; }
166
+ override release(handle: bigint, kernel: Library<typeof KERNEL_SYMBOLS>): boolean {
167
+ const index = this.authorityHandles.lastIndexOf(handle);
168
+ if (index < 0) return true; // Already released; never close a reused native handle.
169
+ try {
170
+ if (!kernel.symbols.CloseHandle(handle)) { this.failedCloses.add(handle); return false; }
171
+ } catch { this.failedCloses.add(handle); return false; }
172
+ this.authorityHandles.splice(index, 1);
173
+ this.failedCloses.delete(handle);
174
+ return true;
175
+ }
176
+ override closeAll(kernel: Library<typeof KERNEL_SYMBOLS>): void {
177
+ // One attempt per disposal. A failed explicit release must not be retried
178
+ // invisibly by a later finally/closeAll in the same ownership lifecycle.
179
+ for (const handle of [...this.authorityHandles].reverse()) {
180
+ if (!this.failedCloses.has(handle)) this.release(handle, kernel);
181
+ }
182
+ }
183
+ }
184
+
185
+ /** Internal acquisition root; never serialized into job/HTTP DTOs. */
186
+ export class WindowsApplyAcquisition {
187
+ constructor(readonly resources: object, private readonly pins: WindowsApplyAuthorityPins) {}
188
+ releaseIfClean(token?: { release(): void }): boolean {
189
+ if (this.pins.remaining !== 0) return false;
190
+ token?.release();
191
+ return true;
192
+ }
193
+ }
194
+
195
+ export class WindowsCliToolchainCleanupError extends Error {
196
+ constructor(readonly acquisition: WindowsApplyAcquisition) { super("toolchain_cleanup_unverified"); }
197
+ }
198
+ // Failed native closes remain strongly owned even when acquisition rejects.
199
+ const retainedToolchains = new Set<WindowsApplyAcquisition>();
200
+
201
+ interface Prepared {
202
+ readonly config: string;
203
+ readonly dir: string;
204
+ readonly file: string;
205
+ readonly lock: string;
206
+ /** Write-access handle on the store directory; anchors leaf opens and the rename flush. */
207
+ readonly jobdir: bigint;
208
+ }
209
+
210
+ function components(path: string): { drive: string; names: string[] } | null {
211
+ if (typeof path !== "string" || path.length > 8192 || !/^[A-Za-z]:[\\/]/.test(path)) return null;
212
+ const names = path.slice(3).split(/[\\/]/);
213
+ if (!names.length || names.length > 64 || names.some(name => !name || name === "." || name === ".."
214
+ || /[\x00-\x1f<>:"|?*]/.test(name) || /[. ]$/.test(name)
215
+ || /^(?:con|prn|aux|nul|com[1-9\xb9\xb2\xb3]|lpt[1-9\xb9\xb2\xb3])(?:\.|$)/i.test(name))) return null;
216
+ return { drive: path.slice(0, 2).toUpperCase() + "\\", names };
217
+ }
218
+
219
+ interface Ctx {
220
+ readonly ffi: typeof import("bun:ffi");
221
+ readonly kernel: Library<typeof KERNEL_SYMBOLS>;
222
+ readonly nt: Library<typeof NT_SYMBOLS>;
223
+ readonly pins: PinSet;
224
+ }
225
+
226
+ const wide = (text: string): Buffer => Buffer.from(text + "\0", "utf16le");
227
+ // OBJECT_ATTRIBUTES contains unmanaged pointers to UNICODE_STRING and its text.
228
+ // Root every backing buffer through NtCreateFile, including across GC/JIT pressure.
229
+ const activeRelativeOpenBuffers = new Set<Buffer>();
230
+
231
+ function keep(ctx: Ctx, handle: bigint): bigint {
232
+ if (handle === 0n || handle === INVALID_HANDLE) throw unsafe();
233
+ return ctx.pins.keep(handle);
234
+ }
235
+
236
+ function info(ctx: Ctx, handle: bigint, infoClass: number, length: number): Buffer {
237
+ const buffer = Buffer.alloc(length);
238
+ if (!ctx.kernel.symbols.GetFileInformationByHandleEx!(handle, infoClass, ctx.ffi.ptr(buffer), length)) {
239
+ throw unsafe();
240
+ }
241
+ return buffer;
242
+ }
243
+
244
+ /** Full identity/type observation for one held handle; kind is asserted by the caller. */
245
+ function inspect(ctx: Ctx, handle: bigint, directory: boolean): StoreInspection {
246
+ if (ctx.kernel.symbols.GetFileType!(handle) !== 1) throw unsafe(); // FILE_TYPE_DISK
247
+ const basic = info(ctx, handle, 0, 40); // FILE_BASIC_INFO: 4 LARGE_INTEGERs, attributes.
248
+ const attributes = basic.readUInt32LE(32);
249
+ if (attributes & REPARSE) throw unsafe();
250
+ if (Boolean(attributes & DIRECTORY_ATTR) !== directory) throw unsafe();
251
+ const id = info(ctx, handle, 18, 24); // FILE_ID_INFO: volume serial and 128-bit file ID.
252
+ const standard = info(ctx, handle, 1, 24); // FILE_STANDARD_INFO.
253
+ const size = standard.readBigInt64LE(8);
254
+ if (size < 0n || size > BigInt(Number.MAX_SAFE_INTEGER)) throw unsafe();
255
+ if (standard.readUInt8(20) !== 0) throw unsafe(); // DeletePending is one byte; offset 21 is Directory.
256
+ return { volumeSerial: id.readBigUInt64LE(0).toString(16), fileId: id.subarray(8, 24).toString("hex"),
257
+ size: Number(size), links: standard.readUInt32LE(16), deletePending: false };
258
+ }
259
+
260
+ function sameIdentity(a: StoreIdentity, b: StoreIdentity): boolean {
261
+ return a.volumeSerial === b.volumeSerial && a.fileId === b.fileId;
262
+ }
263
+
264
+ function assertCanonicalPath(ctx: Ctx, handle: bigint, path: string): void {
265
+ const output = Buffer.alloc(32768 * 2);
266
+ const length = ctx.kernel.symbols.GetFinalPathNameByHandleW!(handle, ctx.ffi.ptr(output), 32768, 0);
267
+ if (!length || length >= 32768
268
+ || !windowsCanonicalPathMatches(path, output.toString("utf16le", 0, length * 2))) throw unsafe();
269
+ }
270
+
271
+ /** Handle-relative open of one component below an already-pinned parent. */
272
+ function relOpen(
273
+ ctx: Ctx,
274
+ parent: bigint,
275
+ component: string,
276
+ directory: boolean,
277
+ access: number,
278
+ share: number,
279
+ ): bigint {
280
+ const name = wide(component);
281
+ const unicode = Buffer.alloc(16);
282
+ const attributes = Buffer.alloc(48);
283
+ const output = Buffer.alloc(8);
284
+ const status = Buffer.alloc(16);
285
+ const borrowed = [name, unicode, attributes, output, status];
286
+ for (const buffer of borrowed) activeRelativeOpenBuffers.add(buffer);
287
+ try {
288
+ unicode.writeUInt16LE(name.length - 2, 0);
289
+ unicode.writeUInt16LE(name.length, 2);
290
+ unicode.writeBigUInt64LE(BigInt(ctx.ffi.ptr(name)), 8);
291
+ attributes.writeUInt32LE(48, 0);
292
+ attributes.writeBigUInt64LE(parent, 8);
293
+ attributes.writeBigUInt64LE(BigInt(ctx.ffi.ptr(unicode)), 16);
294
+ attributes.writeUInt32LE(0x40, 24); // OBJ_CASE_INSENSITIVE; one component only.
295
+ const result = ctx.nt.symbols.NtCreateFile!(ctx.ffi.ptr(output), access, ctx.ffi.ptr(attributes),
296
+ ctx.ffi.ptr(status), null, 0, share, FILE_OPEN, directory ? DIR_OPTIONS : FILE_OPTIONS, null, 0);
297
+ if (result < 0) {
298
+ const status32 = result >>> 0;
299
+ if (status32 === 0xc0000034 || status32 === 0xc000003a) throw enoent(); // object/path not found
300
+ throw new Error("unsafe_store", { cause: { nativeStatus: status32 } });
301
+ }
302
+ const handle = keep(ctx, output.readBigUInt64LE(0));
303
+ return handle;
304
+ } finally { for (const buffer of borrowed) activeRelativeOpenBuffers.delete(buffer); }
305
+ }
306
+
307
+ /** Volume root via the strict GUID mount path; remote or absent volumes refuse. */
308
+ function openVolumeRoot(ctx: Ctx, drive: string): bigint {
309
+ const mount = wide(drive);
310
+ const name = Buffer.alloc(100 * 2);
311
+ if (![2, 3, 5, 6].includes(Number(ctx.kernel.symbols.GetDriveTypeW!(ctx.ffi.ptr(mount))))) {
312
+ throw unsafe();
313
+ }
314
+ if (!ctx.kernel.symbols.GetVolumeNameForVolumeMountPointW!(ctx.ffi.ptr(mount), ctx.ffi.ptr(name), 100)) {
315
+ throw unsafe();
316
+ }
317
+ const guid = name.toString("utf16le").split("\0", 1)[0]!;
318
+ if (!/^\\\\\?\\Volume\{[0-9a-f-]{36}\}\\$/i.test(guid)) throw unsafe();
319
+ const path = wide(guid);
320
+ const handle = keep(ctx, BigInt(ctx.kernel.symbols.CreateFileW!(ctx.ffi.ptr(path), ACCESS_READ,
321
+ SHARE_DIR, null, 3, 0x02200000, 0n)));
322
+ inspect(ctx, handle, true);
323
+ return handle;
324
+ }
325
+
326
+ /** Read up to limit bytes from a held file handle, then require exact end-of-file. */
327
+ function readAll(ctx: Ctx, handle: bigint, limit: number): Buffer {
328
+ // Held pins are re-read across phases — owner.json is re-read at release after
329
+ // the acquire-time read left the position at EOF — so rewind first, or a second
330
+ // readAll on the same handle sees an empty file and fails closed.
331
+ if (!ctx.kernel.symbols.SetFilePointerEx!(handle, 0n, null, 0)) throw unsafe(); // FILE_BEGIN
332
+ const bytes = Buffer.alloc(limit);
333
+ const chunk = Buffer.alloc(Math.min(1024 * 1024, Math.max(1, limit)));
334
+ const read = Buffer.alloc(4);
335
+ let offset = 0;
336
+ while (offset < limit) {
337
+ const length = Math.min(chunk.length, limit - offset);
338
+ if (!ctx.kernel.symbols.ReadFile!(handle, ctx.ffi.ptr(chunk), length, ctx.ffi.ptr(read), null)) {
339
+ throw unsafe();
340
+ }
341
+ const count = read.readUInt32LE(0);
342
+ if (!count || count > length) throw unsafe();
343
+ chunk.copy(bytes, offset, 0, count);
344
+ offset += count;
345
+ }
346
+ // Any byte past the bound means the file changed while held open.
347
+ if (!ctx.kernel.symbols.ReadFile!(handle, ctx.ffi.ptr(chunk), 1, ctx.ffi.ptr(read), null)
348
+ || read.readUInt32LE(0) !== 0) throw unsafe();
349
+ return bytes;
350
+ }
351
+
352
+ function flushDir(ctx: Ctx, handle: bigint): void {
353
+ if (!ctx.kernel.symbols.FlushFileBuffers!(handle)) throw unsafe();
354
+ }
355
+
356
+ /** Mark a held object delete-pending; removal completes when the handle closes. */
357
+ function markDelete(ctx: Ctx, handle: bigint): void {
358
+ const d = Buffer.alloc(1);
359
+ d.writeUInt8(1, 0);
360
+ if (!ctx.kernel.symbols.SetFileInformationByHandle!(handle, 4, ctx.ffi.ptr(d), 1)) throw unsafe();
361
+ }
362
+
363
+ /**
364
+ * Rename the held file to an absolute destination. Handle-bound, so the object
365
+ * moved is provably the one verified; the verbatim \?\ path is the fully
366
+ * qualified form the API parses unambiguously. FileNameLength counts the string
367
+ * INCLUDING its terminator — this API reads the NUL inside the counted span,
368
+ * and a shorter count makes it read past the buffer into adjacent memory.
369
+ * ReplaceIfExists matches POSIX rename. A sharing-violation blink (scanner/AV
370
+ * indexing) retries through the shared bounded helper; a foreign deny-delete
371
+ * pin on the destination fails closed.
372
+ */
373
+ function renamePinned(ctx: Ctx, handle: bigint, destination: string): void {
374
+ const run = () => {
375
+ const name = wide("\\\\?\\" + destination);
376
+ const buffer = Buffer.alloc(20 + name.length);
377
+ buffer.writeUInt32LE(1, 0); // ReplaceIfExists
378
+ buffer.writeBigUInt64LE(0n, 8); // RootDirectory: NULL means absolute FileName.
379
+ buffer.writeUInt32LE(name.length, 16); // Terminator-inclusive length.
380
+ name.copy(buffer, 20);
381
+ if (!ctx.kernel.symbols.SetFileInformationByHandle!(handle, 3, ctx.ffi.ptr(buffer), buffer.length)) {
382
+ const error = unsafe() as NodeJS.ErrnoException;
383
+ error.code = "EBUSY";
384
+ throw error;
385
+ }
386
+ };
387
+ retryWindowsFileOperation({ run });
388
+ }
389
+
390
+ async function verifyAcl(entries: readonly WindowsAclEntry[]): Promise<void> {
391
+ if (!await verifyWindowsEntriesAclAsync(aclTargets(entries), ACL_VERIFY_TIMEOUT_MS)) throw unsafe();
392
+ }
393
+
394
+ // External ACL tools need extended-length names even though native pins and
395
+ // canonical/alias checks continue to use the original normalized long DOS paths.
396
+ function aclTargets(entries: readonly WindowsAclEntry[]): WindowsAclEntry[] {
397
+ return entries.map(entry => ({ ...entry, path: toNamespacedPath(entry.path) }));
398
+ }
399
+
400
+ interface ChainEntry {
401
+ readonly path: string;
402
+ readonly handle: bigint;
403
+ readonly inspection: StoreInspection;
404
+ }
405
+
406
+ /**
407
+ * Pin every component of an absolute path, volume root down, each opened relative
408
+ * to the held parent so no checked-then-reopened gap exists. leafAccess applies
409
+ * to the final component; all ancestors are read-pinned deny-delete.
410
+ */
411
+ function pinChain(ctx: Ctx, absolutePath: string, leafAccess: number): ChainEntry[] {
412
+ const parsed = components(absolutePath);
413
+ if (!parsed) throw unsafe();
414
+ const chain: ChainEntry[] = [];
415
+ let parent = openVolumeRoot(ctx, parsed.drive);
416
+ let current = parsed.drive;
417
+ for (let index = 0; index < parsed.names.length; index++) {
418
+ const access = index === parsed.names.length - 1 ? leafAccess : ACCESS_READ;
419
+ const handle = relOpen(ctx, parent, parsed.names[index]!, true, access, SHARE_DIR);
420
+ const inspection = inspect(ctx, handle, true);
421
+ current = join(current, parsed.names[index]!);
422
+ assertCanonicalPath(ctx, handle, current);
423
+ chain.push({ path: current, handle, inspection });
424
+ parent = handle;
425
+ }
426
+ return chain;
427
+ }
428
+
429
+ /**
430
+ * Open and trust the ledger tree: trusted ancestry to the config parent, the
431
+ * write-private parent and config root, then the strict-private store directory.
432
+ * Ancestors are verified before anything is created; EEXIST never rehardens —
433
+ * only objects this call creates get hardened, everything else is verify-only.
434
+ * Returns null only for a read flow whose store does not exist yet.
435
+ */
436
+ async function prepareStore(
437
+ ctx: Ctx,
438
+ absoluteConfig: string,
439
+ opts: { createJobDir: boolean; createConfigRoot: boolean },
440
+ ): Promise<Prepared | null> {
441
+ const config = absoluteConfig;
442
+ const dir = join(config, CODEX_CLI_JOB_STORE_DIR);
443
+ const file = join(dir, CODEX_CLI_JOB_STORE_FILE);
444
+ const lock = join(dir, CODEX_CLI_JOB_STORE_LOCK);
445
+ const parentPath = join(config, "..");
446
+ const chain = pinChain(ctx, resolve(parentPath), ACCESS_READ);
447
+ const ancestry: WindowsAclEntry[] = chain.map((entry, index) => ({
448
+ path: entry.path,
449
+ directory: true,
450
+ policy: index === chain.length - 1 ? "write-private" : "trusted-ancestry",
451
+ }));
452
+ // Trust the ancestry before any write, matching the POSIX order.
453
+ await verifyAcl(ancestry);
454
+ const parentPin = chain.at(-1);
455
+ if (!parentPin) throw unsafe();
456
+ const configName = config.slice(parentPath.length + 1);
457
+ let configPin: bigint;
458
+ let configPrivate = false;
459
+ try {
460
+ configPin = relOpen(ctx, parentPin.handle, configName, true, ACCESS_READ, SHARE_DIR);
461
+ inspect(ctx, configPin, true);
462
+ } catch (error) {
463
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" || !opts.createConfigRoot) {
464
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && !opts.createJobDir) return null;
465
+ throw error;
466
+ }
467
+ // Only a confirmed apply admission may create one absent config-root level.
468
+ mkdirSync(config);
469
+ configPin = relOpen(ctx, parentPin.handle, configName, true, ACCESS_READ, SHARE_DIR);
470
+ inspect(ctx, configPin, true);
471
+ await hardenSecretDirAsync(toNamespacedPath(config), { required: true });
472
+ configPrivate = true;
473
+ }
474
+ assertCanonicalPath(ctx, configPin, config);
475
+ await verifyAcl([{ path: config, directory: true, policy: configPrivate ? "private" : "write-private" }]);
476
+ const jobdirAccess = opts.createJobDir ? ACCESS_DIR_PIN : ACCESS_READ;
477
+ let jobdir: bigint;
478
+ try {
479
+ jobdir = relOpen(ctx, configPin, CODEX_CLI_JOB_STORE_DIR, true, jobdirAccess, SHARE_DIR);
480
+ inspect(ctx, jobdir, true);
481
+ await verifyAcl([{ path: dir, directory: true, policy: "private" }]);
482
+ } catch (error) {
483
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" || !opts.createJobDir) {
484
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && !opts.createJobDir) return null;
485
+ throw error;
486
+ }
487
+ mkdirSync(dir);
488
+ jobdir = relOpen(ctx, configPin, CODEX_CLI_JOB_STORE_DIR, true, jobdirAccess, SHARE_DIR);
489
+ inspect(ctx, jobdir, true);
490
+ await hardenSecretDirAsync(toNamespacedPath(dir), { required: true });
491
+ await verifyAcl([{ path: dir, directory: true, policy: "private" }]);
492
+ }
493
+ return { config, dir, file, lock, jobdir };
494
+ }
495
+
496
+ /** Read the ledger body through a held leaf pin; null when the file is absent. */
497
+ async function readStoreBody(ctx: Ctx, prepared: Prepared): Promise<string | null> {
498
+ let leaf: bigint;
499
+ try {
500
+ // Verify-only opens stay read-only: ACCESS_LEAF carries DELETE, which a
501
+ // read-only-shared pin cannot admit; share-delete is offered so a held
502
+ // delete-capable pin (this process or another trusted writer) can coexist.
503
+ leaf = relOpen(ctx, prepared.jobdir, CODEX_CLI_JOB_STORE_FILE, false, ACCESS_READ, SHARE_LEAF_VERIFY);
504
+ } catch (error) {
505
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
506
+ throw error;
507
+ }
508
+ try {
509
+ const stat = inspect(ctx, leaf, false);
510
+ if (stat.links !== 1 || stat.size > CODEX_CLI_JOB_STORE_MAX_BYTES) throw unsafe();
511
+ await verifyAcl([{ path: prepared.file, directory: false, policy: "private" }]);
512
+ return readAll(ctx, leaf, stat.size).toString("utf8");
513
+ } finally {
514
+ ctx.pins.release(leaf, ctx.kernel);
515
+ }
516
+ }
517
+
518
+ /**
519
+ * Publish the ledger body through a private temp. The held temp handle binds the
520
+ * verified object through harden, ACL read, byte readback and the rename itself;
521
+ * after the rename a fresh name-open proves the published name resolves to the
522
+ * identical object before the directory is flushed.
523
+ */
524
+ async function writeStoreBody(ctx: Ctx, prepared: Prepared, body: string): Promise<void> {
525
+ const bytes = Buffer.byteLength(body);
526
+ if (bytes > CODEX_CLI_JOB_STORE_MAX_BYTES) throw new Error("store_full");
527
+ const tempName = ".jobs-" + randomUUID() + ".tmp";
528
+ const temp = join(prepared.dir, tempName);
529
+ let leaf: bigint | undefined;
530
+ let tempIdentity: StoreIdentity | undefined;
531
+ let publishedName = false;
532
+ try {
533
+ const fd = openSync(temp, "wx", 0o600);
534
+ try { writeFileSync(fd, body); fsyncSync(fd); } finally { closeSync(fd); }
535
+ leaf = relOpen(ctx, prepared.jobdir, tempName, false, ACCESS_LEAF, SHARE_LEAF);
536
+ const stat = inspect(ctx, leaf, false);
537
+ if (stat.links !== 1 || stat.size !== bytes) throw unsafe();
538
+ if (!readAll(ctx, leaf, stat.size).equals(Buffer.from(body))) throw unsafe();
539
+ tempIdentity = stat;
540
+ await hardenSecretPathAsync(toNamespacedPath(temp), { required: true, timeoutMemoKey: prepared.file });
541
+ await verifyAcl([{ path: temp, directory: false, policy: "private" }]);
542
+ renamePinned(ctx, leaf, prepared.file);
543
+ publishedName = true;
544
+ // The held handle now names jobs.json. A fresh name-open proves the published
545
+ // path resolves to the identical object while the original handle is still held.
546
+ let published: bigint | undefined;
547
+ try {
548
+ // The renamed object is still held by `leaf` with share-read: only a
549
+ // read-access reopen can coexist, which is all the identity/byte proof needs.
550
+ published = relOpen(ctx, prepared.jobdir, CODEX_CLI_JOB_STORE_FILE, false,
551
+ ACCESS_READ, SHARE_LEAF_VERIFY);
552
+ const fresh = inspect(ctx, published, false);
553
+ if (!sameIdentity(fresh, stat) || fresh.links !== 1 || fresh.size !== bytes) throw unsafe();
554
+ await verifyAcl([{ path: prepared.file, directory: false, policy: "private" }]);
555
+ if (!readAll(ctx, published, bytes).equals(Buffer.from(body))) throw unsafe();
556
+ } finally {
557
+ if (published !== undefined) ctx.pins.release(published, ctx.kernel);
558
+ }
559
+ flushDir(ctx, prepared.jobdir);
560
+ } finally {
561
+ // A published leaf is jobs.json even if readback/flush subsequently fails.
562
+ // Only the verified unpublished object may be marked for delete-on-close.
563
+ if (!publishedName) {
564
+ try {
565
+ if (leaf !== undefined && tempIdentity !== undefined) {
566
+ if (sameIdentity(inspect(ctx, leaf, false), tempIdentity)) markDelete(ctx, leaf);
567
+ } else if (leaf === undefined) unlinkSync(temp);
568
+ } catch { /* unprovable cleanup stays fail-closed */ }
569
+ }
570
+ forgetEphemeralSecretPath(toNamespacedPath(temp));
571
+ if (leaf !== undefined) ctx.pins.release(leaf, ctx.kernel);
572
+ }
573
+ }
574
+
575
+ interface HeldLock {
576
+ readonly dir: bigint;
577
+ readonly dirIdentity: StoreInspection;
578
+ readonly owner: bigint;
579
+ readonly ownerIdentity: StoreInspection;
580
+ readonly record: string;
581
+ readonly ownerPath: string;
582
+ readonly lockPath: string;
583
+ }
584
+
585
+ /**
586
+ * Prove-and-delete the objects this call created during lock initialization.
587
+ * A held pin IS the created object — its identity cannot change underneath —
588
+ * so a verified pin may be marked delete-pending. An object that never got a
589
+ * proven pin stays behind, which keeps the lock directory occupied and leaves
590
+ * later admission fail-closed, exactly like the POSIX rollback.
591
+ */
592
+ function rollbackInitializingLock(
593
+ ctx: Ctx,
594
+ lockDir: bigint,
595
+ lockIdentity: StoreInspection,
596
+ owner: bigint | undefined,
597
+ ownerIdentity: StoreInspection | undefined,
598
+ ): void {
599
+ try {
600
+ if (owner !== undefined && ownerIdentity !== undefined) {
601
+ try {
602
+ if (sameIdentity(inspect(ctx, owner, false), ownerIdentity)) markDelete(ctx, owner);
603
+ } catch { /* unprovable stays */ }
604
+ ctx.pins.release(owner, ctx.kernel);
605
+ }
606
+ try {
607
+ if (sameIdentity(inspect(ctx, lockDir, true), lockIdentity)) markDelete(ctx, lockDir);
608
+ } catch { /* keep the lock fail-closed */ }
609
+ ctx.pins.release(lockDir, ctx.kernel);
610
+ } catch { /* rollback never masks the original error */ }
611
+ }
612
+
613
+ /**
614
+ * Acquire the admission mutex: mkdir the lock directory, then write owner.json
615
+ * under the held pins. EEXIST means another admission is in flight and maps to
616
+ * job_store_busy; a crashed leftover stays busy forever, like POSIX.
617
+ */
618
+ async function acquireLock(ctx: Ctx, prepared: Prepared): Promise<HeldLock> {
619
+ try { mkdirSync(prepared.lock); }
620
+ catch (error) {
621
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new CodexCliJobStoreBusyError();
622
+ throw error;
623
+ }
624
+ const lockDir = relOpen(ctx, prepared.jobdir, prepared.lock.slice(prepared.dir.length + 1), true,
625
+ ACCESS_DIR_WRITE, SHARE_DIR);
626
+ const lockIdentity = inspect(ctx, lockDir, true);
627
+ const ownerPath = join(prepared.lock, "owner.json");
628
+ const record = JSON.stringify({ version: 1, token: randomUUID() });
629
+ const recordBytes = Buffer.byteLength(record);
630
+ let owner: bigint | undefined;
631
+ let ownerIdentity: StoreInspection | undefined;
632
+ try {
633
+ const fd = openSync(ownerPath, "wx", 0o600);
634
+ try { writeFileSync(fd, record); fsyncSync(fd); } finally { closeSync(fd); }
635
+ owner = relOpen(ctx, lockDir, "owner.json", false, ACCESS_LEAF, SHARE_LEAF);
636
+ ownerIdentity = inspect(ctx, owner, false);
637
+ if (ownerIdentity.links !== 1 || ownerIdentity.size !== recordBytes) throw unsafe();
638
+ if (!readAll(ctx, owner, recordBytes).equals(Buffer.from(record))) throw unsafe();
639
+ await hardenSecretDirAsync(toNamespacedPath(prepared.lock), { required: true });
640
+ await hardenSecretPathAsync(toNamespacedPath(ownerPath), { required: true });
641
+ await verifyAcl([
642
+ { path: prepared.lock, directory: true, policy: "private" },
643
+ { path: ownerPath, directory: false, policy: "private" },
644
+ ]);
645
+ } catch (error) {
646
+ rollbackInitializingLock(ctx, lockDir, lockIdentity, owner, ownerIdentity);
647
+ throw error;
648
+ }
649
+ return { dir: lockDir, dirIdentity: lockIdentity, owner,
650
+ ownerIdentity, record, ownerPath, lockPath: prepared.lock };
651
+ }
652
+
653
+ /**
654
+ * Token-fenced release: the owner file is deleted only while its held pin still
655
+ * shows this call's identity and exact content, and the lock directory only
656
+ * while its pin shows this call's identity. A replaced owner or lock survives,
657
+ * which keeps admission fail-closed on the leftover.
658
+ */
659
+ function releaseLock(ctx: Ctx, held: HeldLock): boolean {
660
+ let ownerDeleted = false, dirDeleted = false;
661
+ try {
662
+ const now = inspect(ctx, held.owner, false);
663
+ if (sameIdentity(now, held.ownerIdentity) && now.links === 1
664
+ && now.size === Buffer.byteLength(held.record)
665
+ && now.size <= 1024
666
+ && readAll(ctx, held.owner, now.size).equals(Buffer.from(held.record))) {
667
+ markDelete(ctx, held.owner);
668
+ ownerDeleted = true;
669
+ }
670
+ } catch { /* fail closed; a leftover owner keeps the lock alive */ }
671
+ ctx.pins.release(held.owner, ctx.kernel);
672
+ try {
673
+ if (sameIdentity(inspect(ctx, held.dir, true), held.dirIdentity)) {
674
+ markDelete(ctx, held.dir);
675
+ dirDeleted = true;
676
+ }
677
+ } catch { /* fail closed; a leftover lock blocks later admission */ }
678
+ ctx.pins.release(held.dir, ctx.kernel);
679
+ return ownerDeleted && dirDeleted;
680
+ }
681
+
682
+ export interface WindowsCliRecoveryIo {
683
+ readonly dir: string;
684
+ names(): string[];
685
+ read(name: string): string;
686
+ withProofHandle<T>(name: string, run: (handle: bigint) => T): T;
687
+ write(name: string, pendingName: string, body: string, adoptPending?: boolean): void;
688
+ }
689
+ /** The shared recovery protocol uses the ledger's native ancestry, no-reparse,
690
+ * identity, private-DACL and rename primitives at synchronous gate boundaries.
691
+ * Restart publication may write an existing pinned store without creating it.
692
+ */
693
+ export function withWindowsCliRecoveryStore<T>(config: string, create: boolean, run: (io: WindowsCliRecoveryIo) => T, publish = false): T {
694
+ if (process.platform !== "win32" || process.arch !== "x64") throw unsafe();
695
+ assertNotRealHomeUnderTest(config);
696
+ const kernel = recoveryFfi.dlopen("kernel32.dll", KERNEL_SYMBOLS);
697
+ const nt = recoveryFfi.dlopen("ntdll.dll", NT_SYMBOLS);
698
+ const ctx: Ctx = { ffi: recoveryFfi, kernel, nt, pins: new PinSet() };
699
+ const verify = (entries: readonly WindowsAclEntry[]) => {
700
+ if (!verifyWindowsEntriesAcl(aclTargets(entries), ACL_VERIFY_TIMEOUT_MS)) throw unsafe();
701
+ };
702
+ try {
703
+ const chain = pinChain(ctx, config, ACCESS_DIR_PIN);
704
+ verify(chain.map((entry, i) => ({ path: entry.path, directory: true,
705
+ policy: i >= chain.length - 2 ? "write-private" : "trusted-ancestry" })));
706
+ const configPin = chain.at(-1);
707
+ if (!configPin) throw unsafe();
708
+ const dir = join(config, "codex-cli-update-recovery");
709
+ try {
710
+ if (create) { mkdirSync(dir); hardenSecretDir(toNamespacedPath(dir), { required: true }); }
711
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
712
+ const directoryPin = relOpen(ctx, configPin.handle, "codex-cli-update-recovery", true,
713
+ create || publish ? ACCESS_DIR_PIN : ACCESS_READ, SHARE_DIR);
714
+ inspect(ctx, directoryPin, true); assertCanonicalPath(ctx, directoryPin, dir);
715
+ verify([{ path: dir, directory: true, policy: "private" }]);
716
+ if (create) flushDir(ctx, configPin.handle);
717
+ const leaf = (name: string, access = ACCESS_READ, sharing = SHARE_LEAF_VERIFY) => {
718
+ if (!/^[0-9a-f-]{36}(?:\.(?:terminal|proof))?(?:\.pending|\.json|\.terminal|\.proof)$/.test(name)) throw unsafe();
719
+ const handle = relOpen(ctx, directoryPin, name, false, access, sharing);
720
+ const stat = inspect(ctx, handle, false);
721
+ if (stat.links !== 1 || stat.size > 1024) throw unsafe();
722
+ verify([{ path: join(dir, name), directory: false, policy: "private" }]);
723
+ return { handle, stat };
724
+ };
725
+ return run({ dir,
726
+ names: () => readdirSync(dir),
727
+ read(name) {
728
+ const file = leaf(name);
729
+ try { return readAll(ctx, file.handle, file.stat.size).toString("utf8"); }
730
+ finally { ctx.pins.release(file.handle, kernel); }
731
+ },
732
+ withProofHandle(name, use) {
733
+ if (!/^[0-9a-f-]{36}\.proof$/.test(name)) throw unsafe();
734
+ const file = leaf(name, 0x40100080, 7);
735
+ try { return use(file.handle); } finally { ctx.pins.release(file.handle, kernel); }
736
+ },
737
+ write(name, pendingName, body, adoptPending = false) {
738
+ if (!(create || publish) || Buffer.byteLength(body) > 1024 || !/^[0-9a-f-]{36}(?:\.terminal|\.proof)?$/.test(name.replace(/\.json$/, ""))
739
+ || pendingName !== name.replace(/\.json$/, "") + ".pending") throw unsafe();
740
+ // Recovery preserves the only durable child identity until atomic rename.
741
+ const temp = join(dir, pendingName), destination = join(dir, name);
742
+ if (!adoptPending) {
743
+ try {
744
+ const old = leaf(pendingName, ACCESS_LEAF, SHARE_LEAF);
745
+ markDelete(ctx, old.handle); ctx.pins.release(old.handle, kernel);
746
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
747
+ const fd = openSync(temp, "wx", 0o600);
748
+ try { writeFileSync(fd, body); fsyncSync(fd); } finally { closeSync(fd); }
749
+ }
750
+ hardenSecretPath(toNamespacedPath(temp), { required: true });
751
+ const file = leaf(pendingName, adoptPending ? ACCESS_LEAF | 0x40000000 : ACCESS_LEAF, SHARE_LEAF);
752
+ try {
753
+ if (!readAll(ctx, file.handle, file.stat.size).equals(Buffer.from(body))) throw unsafe();
754
+ if (adoptPending) flushDir(ctx, file.handle);
755
+ renamePinned(ctx, file.handle, destination);
756
+ // The held adopted pin denies other writers; this reader must share
757
+ // its write/flush access as well as DELETE through identity readback.
758
+ const published = leaf(name, ACCESS_READ, adoptPending ? SHARE_LEAF_VERIFY | 0x2 : SHARE_LEAF_VERIFY);
759
+ try { if (!sameIdentity(file.stat, published.stat)) throw unsafe(); }
760
+ finally { ctx.pins.release(published.handle, kernel); }
761
+ flushDir(ctx, directoryPin);
762
+ } finally { ctx.pins.release(file.handle, kernel); forgetEphemeralSecretPath(toNamespacedPath(temp)); }
763
+ },
764
+ });
765
+ } finally { ctx.pins.closeAll(kernel); nt.close(); kernel.close(); }
766
+ }
767
+
768
+ export interface WindowsJobStoreIo {
769
+ /** Ledger body text; null when the file is absent. */
770
+ readStore(): Promise<string | null>;
771
+ /** Atomically publish a replacement ledger body. */
772
+ writeStore(body: string): Promise<void>;
773
+ }
774
+
775
+ /** Separate installation authority. It does not use the job ledger or repair existing ACLs.
776
+ * Directory pins allow npm's writes but deny replacement of the prefix/ancestry.
777
+ * The serving account and kernel-equivalent principals remain inside the trust boundary.
778
+ */
779
+ export async function openWindowsCliApplyAuthority(prefix: string, acquire: boolean,
780
+ onAcquiring?: (owner: WindowsApplyAcquisition) => void) {
781
+ assertNotRealHomeUnderTest(prefix);
782
+ const { ffi, kernel, nt } = await loadNative();
783
+ const pins = new WindowsApplyAuthorityPins();
784
+ const ctx: Ctx = { ffi, kernel, nt, pins };
785
+ let held: HeldLock | undefined;
786
+ let transferred = false;
787
+ let closed = false;
788
+ let resourcesReleased = false;
789
+ try {
790
+ // Publish the context before the first pin/open or async verification can fail.
791
+ // The caller already holds its Worker token; failed cleanup remains rooted there.
792
+ onAcquiring?.(new WindowsApplyAcquisition(ctx, pins));
793
+ // The prefix is an ancestry pin, not a writable store directory. A write-access
794
+ // pin would prevent the ordinary deny-write installation snapshot from opening
795
+ // it, even though npm's child-file writes do not require that access on our pin.
796
+ const chain = pinChain(ctx, prefix, ACCESS_READ);
797
+ if (chain.length < 2) throw unsafe();
798
+ const prefixDepth = chain.length, prefixPin = chain.at(-1)!;
799
+ let parent = prefixPin.handle, path = prefix;
800
+ for (const component of ["node_modules", "@openai"]) {
801
+ path = join(path, component);
802
+ const handle = relOpen(ctx, parent, component, true, ACCESS_READ, SHARE_DIR);
803
+ chain.push({ path, handle, inspection: inspect(ctx, handle, true) });
804
+ parent = handle;
805
+ }
806
+ const entries: WindowsAclEntry[] = chain.map((entry, index) => ({ path: entry.path, directory: true,
807
+ policy: index >= prefixDepth - 2 ? "write-private" : "trusted-ancestry" }));
808
+ let stage: { path: string; handle: bigint; identity: StoreInspection } | undefined;
809
+ const verifyIdentitySync = () => {
810
+ for (const entry of chain) if (!sameIdentity(entry.inspection, inspect(ctx, entry.handle, true))) throw unsafe();
811
+ if (held && (!sameIdentity(held.dirIdentity, inspect(ctx, held.dir, true))
812
+ || !sameIdentity(held.ownerIdentity, inspect(ctx, held.owner, false))
813
+ || !readAll(ctx, held.owner, Buffer.byteLength(held.record)).equals(Buffer.from(held.record)))) throw unsafe();
814
+ if (stage && !sameIdentity(stage.identity, inspect(ctx, stage.handle, true))) throw unsafe();
815
+ };
816
+ const verifyHeld = async () => {
817
+ verifyIdentitySync();
818
+ await verifyAcl(entries);
819
+ verifyIdentitySync();
820
+ };
821
+ const verify = async () => { if (closed) throw unsafe(); await verifyHeld(); if (closed) throw unsafe(); };
822
+ await verify();
823
+ const lock = join(prefix, ".ocx-codex-cli-apply.lock");
824
+ if (acquire) held = await acquireLock(ctx, { config: prefix, dir: prefix, file: "", lock,
825
+ jobdir: prefixPin.handle });
826
+ transferred = true;
827
+ return {
828
+ lock,
829
+ verify,
830
+ /** Disposal proof is independent of the ACL diagnostic returned by release(). */
831
+ get resourcesReleased() { return resourcesReleased; },
832
+ verifyIdentitySync() { if (closed) throw unsafe(); verifyIdentitySync(); },
833
+ async createStaging(): Promise<string> {
834
+ if (closed || !held || stage) throw unsafe();
835
+ await verify();
836
+ const path = join(lock, "stage");
837
+ mkdirSync(path);
838
+ const handle = relOpen(ctx, held.dir, "stage", true, ACCESS_READ, SHARE_DIR);
839
+ stage = { path, handle, identity: inspect(ctx, handle, true) };
840
+ await hardenSecretDirAsync(toNamespacedPath(path), { required: true });
841
+ await verifyAcl([{ path, directory: true, policy: "private" }]);
842
+ if (closed) throw unsafe();
843
+ return path;
844
+ },
845
+ async removeStaging(): Promise<void> {
846
+ if (closed || !stage) throw unsafe();
847
+ await verify();
848
+ if (!sameIdentity(stage.identity, inspect(ctx, stage.handle, true))) throw unsafe();
849
+ await verifyAcl([{ path: stage.path, directory: true, policy: "private" }]);
850
+ if (closed) throw unsafe();
851
+ if (!pins.release(stage.handle, kernel)) throw unsafe();
852
+ // Ancestors remain pinned and all writers are within the verified trust boundary.
853
+ rmSync(stage.path, { recursive: true });
854
+ stage = undefined;
855
+ },
856
+ async release(): Promise<boolean> {
857
+ if (closed) return false;
858
+ closed = true;
859
+ let aclVerified = true;
860
+ let lockDeleted = !acquire;
861
+ try {
862
+ verifyIdentitySync();
863
+ // An ACL lookup failure must not strand a lock whose original pins
864
+ // still prove ownership. It remains a failed release verdict, even
865
+ // when the independently token/identity-fenced deletion succeeds.
866
+ try { await verifyAcl(entries); } catch { aclVerified = false; }
867
+ verifyIdentitySync();
868
+ if (held) lockDeleted = releaseLock(ctx, held);
869
+ }
870
+ finally { ctx.pins.closeAll(kernel); }
871
+ resourcesReleased = pins.remaining === 0 && !stage && lockDeleted;
872
+ return aclVerified && resourcesReleased;
873
+ },
874
+ };
875
+ } finally { if (!transferred) ctx.pins.closeAll(kernel); }
876
+ }
877
+
878
+ export async function windowsCliApplyPrefixSupported(prefix: string): Promise<boolean> {
879
+ try { const guard = await openWindowsCliApplyAuthority(prefix, false); return await guard.release(); }
880
+ catch { return false; }
881
+ }
882
+
883
+ /** Read-only execution authority: use the same reparse-refusing relative opens and
884
+ * owner/DACL policy as installation authority. No existing object is rehardened.
885
+ * Canonical handle paths make ACL reads identical for long and 8.3 spellings.
886
+ */
887
+ export async function openWindowsCliToolchainAuthority(node: string, npmRoot: string, content: boolean) {
888
+ const { ffi, kernel, nt } = await loadNative();
889
+ const pins = new WindowsApplyAuthorityPins(), ctx: Ctx = { ffi, kernel, nt, pins };
890
+ const acquisition = new WindowsApplyAcquisition(ctx, pins);
891
+ retainedToolchains.add(acquisition);
892
+ let transferred = false, closed = false, total = 0;
893
+ const entries: WindowsAclEntry[] = [], observations: unknown[] = [];
894
+ const canonical = (handle: bigint): string => {
895
+ const buffer = Buffer.alloc(32768 * 2);
896
+ const length = kernel.symbols.GetFinalPathNameByHandleW(handle, ffi.ptr(buffer), 32768, 0);
897
+ if (!length || length >= 32768) throw unsafe();
898
+ const path = buffer.toString("utf16le", 0, length * 2);
899
+ if (!/^\\\\\?\\[a-z]:\\/i.test(path)) throw unsafe();
900
+ return path.slice(4);
901
+ };
902
+ const add = (handle: bigint, directory: boolean, policy: WindowsAclEntry["policy"]) => {
903
+ const identity = inspect(ctx, handle, directory), path = canonical(handle);
904
+ entries.push({ path, directory, policy });
905
+ if (entries.length > 8192) throw unsafe();
906
+ if (!directory) {
907
+ total += identity.size;
908
+ if (identity.links !== 1 || identity.size > 128 * 1024 * 1024 || total > 512 * 1024 * 1024) throw unsafe();
909
+ observations.push([path.toLowerCase(), identity, content ? createHash("sha256").update(readAll(ctx, handle, identity.size)).digest("hex") : ""]);
910
+ } else observations.push([path.toLowerCase(), identity.volumeSerial, identity.fileId]);
911
+ return path;
912
+ };
913
+ try {
914
+ const nodeParent = pinChain(ctx, resolve(node, ".."), ACCESS_READ);
915
+ for (const entry of nodeParent) add(entry.handle, true, "trusted-ancestry");
916
+ const parent = nodeParent.at(-1); if (!parent) throw unsafe();
917
+ // Node's own directory is a module/DLL lookup directory, so broad create grants
918
+ // are forbidden here even when an administrator owns it.
919
+ entries[entries.length - 1] = { path: canonical(parent.handle), directory: true, policy: "write-private" };
920
+ add(relOpen(ctx, parent.handle, basename(node), false, ACCESS_READ, SHARE_LEAF), false, "write-private");
921
+ // Executable-local DLL search happens before the JS resolver guard starts.
922
+ for (const entry of readdirSync(canonical(parent.handle))) if (/\.dll$/i.test(entry)) {
923
+ add(relOpen(ctx, parent.handle, entry, false, ACCESS_READ, SHARE_LEAF), false, "write-private");
924
+ }
925
+ const npmChain = pinChain(ctx, npmRoot, ACCESS_READ);
926
+ for (const entry of npmChain) add(entry.handle, true,
927
+ canonical(entry.handle).length >= canonical(parent.handle).length ? "write-private" : "trusted-ancestry");
928
+ const walk = (handle: bigint) => {
929
+ const path = canonical(handle);
930
+ for (const entry of readdirSync(path, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
931
+ // relOpen + inspect rejects reparse points and all unexpected object kinds.
932
+ const directory = entry.isDirectory();
933
+ const child = relOpen(ctx, handle, entry.name, directory, ACCESS_READ, SHARE_LEAF);
934
+ add(child, directory, "write-private");
935
+ if (directory) walk(child);
936
+ }
937
+ };
938
+ walk(npmChain.at(-1)!.handle);
939
+ // Hold each existing ancestor module lookup directory; absent names are checked
940
+ // again under the already pinned, ACL-confined parents on every acquisition.
941
+ for (const entry of npmChain.slice(0, -1)) {
942
+ try { add(relOpen(ctx, entry.handle, "node_modules", true, ACCESS_READ, SHARE_DIR), true, "write-private"); }
943
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
944
+ }
945
+ for (let i = 0; i < entries.length; i += 512) await verifyAcl(entries.slice(i, i + 512));
946
+ const digest = createHash("sha256").update(JSON.stringify(observations)).digest("hex");
947
+ transferred = true;
948
+ return { digest, async release(): Promise<boolean> {
949
+ if (closed) return false; closed = true;
950
+ pins.closeAll(kernel);
951
+ if (pins.remaining) throw new WindowsCliToolchainCleanupError(acquisition);
952
+ retainedToolchains.delete(acquisition); return true;
953
+ } };
954
+ } finally { if (!transferred) {
955
+ pins.closeAll(kernel);
956
+ if (pins.remaining) throw new WindowsCliToolchainCleanupError(acquisition);
957
+ retainedToolchains.delete(acquisition);
958
+ } }
959
+ }
960
+
961
+ /**
962
+ * Read-only store access outside the mutex, for status. Returns null when the
963
+ * store tree or ledger file does not exist.
964
+ */
965
+ export async function readWindowsJobStore(configDir?: string): Promise<string | null> {
966
+ const absolute = resolve(configDir ?? getConfigDir());
967
+ const { ffi, kernel, nt } = await loadNative();
968
+ const ctx: Ctx = { ffi, kernel, nt, pins: new PinSet() };
969
+ try {
970
+ const prepared = await prepareStore(ctx, absolute, { createJobDir: false, createConfigRoot: false });
971
+ if (prepared === null) return null;
972
+ return await readStoreBody(ctx, prepared);
973
+ } catch (error) {
974
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
975
+ throw error;
976
+ } finally {
977
+ ctx.pins.closeAll(kernel);
978
+ }
979
+ }
980
+
981
+ /**
982
+ * Run fn under the admission mutex with read/write access to the ledger.
983
+ * createConfigRoot is the confirmed-admission privilege to create one absent
984
+ * config-root level; status reads and completion writes never create it.
985
+ */
986
+ export async function withWindowsJobStoreLock<T>(
987
+ configDir: string | undefined,
988
+ createConfigRoot: boolean,
989
+ fn: (io: WindowsJobStoreIo) => T | Promise<T>,
990
+ ): Promise<T> {
991
+ const absolute = resolve(configDir ?? getConfigDir());
992
+ assertNotRealHomeUnderTest(absolute);
993
+ const { ffi, kernel, nt } = await loadNative();
994
+ const ctx: Ctx = { ffi, kernel, nt, pins: new PinSet() };
995
+ try {
996
+ const prepared = await prepareStore(ctx, absolute, { createJobDir: true, createConfigRoot });
997
+ if (prepared === null) throw unsafe(); // unreachable: write flow never returns null
998
+ const held = await acquireLock(ctx, prepared);
999
+ try {
1000
+ return await fn({
1001
+ readStore: () => readStoreBody(ctx, prepared),
1002
+ writeStore: body => writeStoreBody(ctx, prepared, body),
1003
+ });
1004
+ } finally {
1005
+ releaseLock(ctx, held);
1006
+ }
1007
+ } finally {
1008
+ ctx.pins.closeAll(kernel);
1009
+ }
1010
+ }