@bitkyc08/opencodex 2.93.0 → 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-BXu4zE8H.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-CizjBqyk.js +0 -58
  433. package/gui/dist/assets/Tray-DamiMqcX.js +0 -1
  434. package/gui/dist/assets/index-DQsht3vH.js +0 -94
  435. package/gui/dist/assets/index-DRe8Hhfz.css +0 -1
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Wrapper write and ownership fingerprint for the Codex autostart shim.
3
+ *
4
+ * Extracted from shim.ts so the parent module stays inside the file-size
5
+ * ratchet. This cluster is a closed dependency edge: everything here flows
6
+ * from node:fs/node:path, the shim template builders, and the fingerprint
7
+ * probes — nothing imports back into shim.ts.
8
+ */
9
+ import { randomUUID } from "node:crypto";
10
+ import { chmodSync, lstatSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
11
+ import { basename, dirname, join } from "node:path";
12
+ import { durableBunRuntime, type BunRuntimeSource, type DurableBunRuntime } from "../lib/bun-runtime";
13
+ import { serviceApiTokenFilePath } from "../lib/service-secrets";
14
+ import {
15
+ buildUnixCodexShim,
16
+ buildWindowsCodexShim,
17
+ buildWindowsPowerShellCodexShim,
18
+ gitBashPath,
19
+ SHIM_MARKER,
20
+ } from "./shim-templates";
21
+ import {
22
+ sameFingerprint,
23
+ stableShimPathProbe,
24
+ type ShimPathFingerprint,
25
+ type StableShimPathProbe,
26
+ } from "./shim-fingerprint";
27
+
28
+ function cliEntry(runtime: DurableBunRuntime = durableBunRuntime()): { bun: string; bunRuntimeSource: BunRuntimeSource; cli: string } {
29
+ // Bundled Bun path (survives `ocx update`); all three shim builders
30
+ // (Unix / Windows cmd / Windows PowerShell) receive it via this entry.
31
+ // This module lives in src/codex/, the CLI entry in src/cli/index.ts.
32
+ // Path and provenance resolve together so the marker always describes this binary.
33
+ return { bun: runtime.path, bunRuntimeSource: runtime.source, cli: join(import.meta.dir, "..", "cli", "index.ts") };
34
+ }
35
+
36
+ /**
37
+ * Write the wrapper and return the identity of the inode this call created, or
38
+ * `undefined` where the platform still writes the destination in place.
39
+ *
40
+ * Callers must derive ownership from the returned identity rather than from a
41
+ * later `stat` of `wrapperPath`: the shim markers are public, so a concurrent
42
+ * updater's wrapper can carry them, and a replacement landing between the write
43
+ * and the observation is otherwise indistinguishable from our own file.
44
+ */
45
+ /** The Windows wrapper for `wrapperPath`'s flavor (.ps1, .cmd/.bat, or extensionless Git-Bash sh). */
46
+ export function windowsShimContent(wrapperPath: string, realCodexPath: string, runtime?: DurableBunRuntime): string {
47
+ const { bun, bunRuntimeSource, cli } = cliEntry(runtime);
48
+ const lower = wrapperPath.toLowerCase();
49
+ // UTF-8 BOM: Windows PowerShell 5.1 decodes BOM-less .ps1 files in the ANSI
50
+ // codepage, which mangles non-ASCII paths embedded in the shim.
51
+ if (lower.endsWith(".ps1")) return `\uFEFF${buildWindowsPowerShellCodexShim(realCodexPath, bun, cli, bunRuntimeSource)}`;
52
+ if (lower.endsWith(".cmd") || lower.endsWith(".bat")) return buildWindowsCodexShim(realCodexPath, bun, cli, bunRuntimeSource);
53
+ // Extensionless Git-Bash sh launcher: sh shim with forward-slash paths.
54
+ return buildUnixCodexShim(gitBashPath(realCodexPath), gitBashPath(bun), gitBashPath(cli), bunRuntimeSource, gitBashPath(serviceApiTokenFilePath()));
55
+ }
56
+
57
+ export function writeShim(wrapperPath: string, realCodexPath: string, runtime?: DurableBunRuntime): { dev: number; ino: number } | undefined {
58
+ const { bun, bunRuntimeSource, cli } = cliEntry(runtime);
59
+ if (process.platform === "win32") {
60
+ writeFileSync(wrapperPath, windowsShimContent(wrapperPath, realCodexPath, runtime), "utf8");
61
+ return undefined;
62
+ } else {
63
+ // Stage the wrapper as its own inode and rename it into place, so ownership
64
+ // comes from the write itself rather than from observing the path afterwards.
65
+ // Writing the destination directly leaves a window in which a concurrent
66
+ // updater can replace the file between our write and our fingerprint; we would
67
+ // then adopt that replacement as ours and unlink it during rollback, deleting
68
+ // an executable we never wrote.
69
+ // Hidden and non-executable while staged, so a crash between the write and the
70
+ // rename cannot leave an executable `codex*` artifact that a glob or a shell
71
+ // completion would surface.
72
+ const staged = join(dirname(wrapperPath), `.${basename(wrapperPath)}.opencodex-staging.${process.pid}.${randomUUID()}`);
73
+ let renamed = false;
74
+ try {
75
+ // "wx" fails if the staging path somehow exists, so we never inherit a file.
76
+ writeFileSync(staged, buildUnixCodexShim(realCodexPath, bun, cli, bunRuntimeSource), { encoding: "utf8", flag: "wx", mode: 0o600 });
77
+ const stagedStat = lstatSync(staged);
78
+ chmodSync(staged, 0o755);
79
+ renameSync(staged, wrapperPath);
80
+ renamed = true;
81
+ // rename() preserves dev/ino and updates ctime, so identity is the inode
82
+ // pair, captured from the file we created rather than from the destination.
83
+ return { dev: stagedStat.dev, ino: stagedStat.ino };
84
+ } finally {
85
+ if (!renamed) {
86
+ try { unlinkSync(staged); } catch { /* best-effort: nothing to clean up */ }
87
+ }
88
+ }
89
+ }
90
+ }
91
+
92
+ /**
93
+ * The fingerprint to record as "we wrote this", or `undefined` when the file at
94
+ * `wrapperPath` is not the inode `writeShim()` created. Returning `undefined`
95
+ * makes every rollback path treat the file as someone else's and leave it alone.
96
+ */
97
+ export function ownedWrapperFingerprint(
98
+ wrapperPath: string,
99
+ written: { dev: number; ino: number } | undefined,
100
+ ): ShimPathFingerprint | undefined {
101
+ const probe = stableShimPathProbe(wrapperPath);
102
+ if (!probe) return undefined;
103
+ // Platforms that still write in place (Windows) have no staged identity; fall
104
+ // back to the marker check they have always used.
105
+ if (!written) return probe.prefix.includes(SHIM_MARKER) ? probe.fingerprint : undefined;
106
+ if (probe.fingerprint.dev !== written.dev || probe.fingerprint.ino !== written.ino) return undefined;
107
+ return probe.fingerprint;
108
+ }
109
+
110
+ /**
111
+ * Whether the file now at the wrapper path is one this transaction may unlink.
112
+ *
113
+ * The inode our write created is the authority. It stays ours through an in-place
114
+ * truncation — a partial write we must clean up — and stops being ours the moment
115
+ * someone renames a different file over the path, which is exactly the concurrent
116
+ * updater we must not delete. Where no inode was recorded (Windows writes the
117
+ * destination directly), fall back to the exact fingerprint recorded at the time.
118
+ */
119
+ export function wrapperInodeIsOurs(
120
+ wrapper: StableShimPathProbe,
121
+ written: { dev: number; ino: number } | undefined,
122
+ recorded: ShimPathFingerprint | undefined,
123
+ ): boolean {
124
+ // A different inode is conclusive: someone renamed their own file over ours.
125
+ if (written && (wrapper.fingerprint.dev !== written.dev || wrapper.fingerprint.ino !== written.ino)) {
126
+ return false;
127
+ }
128
+ // Same inode is not sufficient on its own — an in-place truncation (shell `>`,
129
+ // writeFileSync) keeps it while replacing the contents. When we recorded a full
130
+ // fingerprint, require it to still match; that covers our own partial write,
131
+ // whose fingerprint we record before anything can fail.
132
+ if (recorded !== undefined) return sameFingerprint(wrapper.fingerprint, recorded);
133
+ // No recorded fingerprint: only the inode identity we captured at write time can
134
+ // speak for us, and there is nothing else to distinguish this file.
135
+ return written !== undefined;
136
+ }
package/src/codex/shim.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { beginCodexCliSelectionParentWrite } from "./cli-update-selection-gate";
2
3
  import {
3
- chmodSync,
4
4
  existsSync,
5
5
  lstatSync,
6
6
  readFileSync,
@@ -8,22 +8,13 @@ import {
8
8
  unlinkSync,
9
9
  writeFileSync,
10
10
  } from "node:fs";
11
- import { basename, delimiter, dirname, extname, join, posix, win32 } from "node:path";
11
+ import { delimiter, extname, join, posix, win32 } from "node:path";
12
12
  import { durableBunRuntime, type DurableBunRuntime } from "../lib/bun-runtime";
13
13
  import { assertSelectedRuntimeWritable, RuntimePreflightError, type RuntimePreflightDeps } from "../lib/bun-runtime-preflight";
14
14
  import { getConfigDir } from "../config";
15
- import type { BunRuntimeSource } from "../lib/bun-runtime";
16
- import { serviceApiTokenFilePath } from "../lib/service-secrets";
17
15
  import { isWslRuntime, wslAutomountRoot } from "./home";
18
16
  import { truncateRetainedUtf8 } from "../lib/admission";
19
- import {
20
- buildUnixCodexShim,
21
- buildWindowsCodexShim,
22
- buildWindowsPowerShellCodexShim,
23
- gitBashPath,
24
- SHIM_MARKER,
25
- UNIX_SHIM_REVISION_MARKER,
26
- } from "./shim-templates";
17
+ import { SHIM_MARKER, UNIX_SHIM_REVISION_MARKER } from "./shim-templates";
27
18
  import {
28
19
  hasUsableBackingPath,
29
20
  isCurrentShimProbe,
@@ -65,6 +56,7 @@ import {
65
56
  resolveStableFnmCodexPath,
66
57
  type CodexPathScanDeps,
67
58
  } from "./shim-path-resolution";
59
+ import { ownedWrapperFingerprint, windowsShimContent, wrapperInodeIsOurs, writeShim } from "./shim-wrapper-write";
68
60
 
69
61
  export { buildUnixCodexShim, buildWindowsCodexShim, buildWindowsPowerShellCodexShim } from "./shim-templates";
70
62
  export { isVersionManagerOwnedCodexPath } from "./shim-fingerprint";
@@ -111,14 +103,6 @@ export type CodexShimAutoRestoreResult =
111
103
  | { status: "ineligible" | "deferred"; message?: string }
112
104
  | { status: "restored"; message: string };
113
105
 
114
- function cliEntry(runtime: DurableBunRuntime = durableBunRuntime()): { bun: string; bunRuntimeSource: BunRuntimeSource; cli: string } {
115
- // Bundled Bun path (survives `ocx update`); all three shim builders
116
- // (Unix / Windows cmd / Windows PowerShell) receive it via this entry.
117
- // This module lives in src/codex/, the CLI entry in src/cli/index.ts.
118
- // Path and provenance resolve together so the marker always describes this binary.
119
- return { bun: runtime.path, bunRuntimeSource: runtime.source, cli: join(import.meta.dir, "..", "cli", "index.ts") };
120
- }
121
-
122
106
  function commandNames(name: string): string[] {
123
107
  if (process.platform !== "win32") return [name];
124
108
  const exts = (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD;.PS1").split(";").filter(Boolean);
@@ -341,108 +325,6 @@ function rollbackFreshShimInstall(journal: readonly FreshShimInstallJournalEntry
341
325
  if (errors.length > 0) throw new AggregateError(errors, "Codex shim install validation rollback failed");
342
326
  }
343
327
 
344
- /**
345
- * Write the wrapper and return the identity of the inode this call created, or
346
- * `undefined` where the platform still writes the destination in place.
347
- *
348
- * Callers must derive ownership from the returned identity rather than from a
349
- * later `stat` of `wrapperPath`: the shim markers are public, so a concurrent
350
- * updater's wrapper can carry them, and a replacement landing between the write
351
- * and the observation is otherwise indistinguishable from our own file.
352
- */
353
- /** The Windows wrapper for `wrapperPath`'s flavor (.ps1, .cmd/.bat, or extensionless Git-Bash sh). */
354
- function windowsShimContent(wrapperPath: string, realCodexPath: string, runtime?: DurableBunRuntime): string {
355
- const { bun, bunRuntimeSource, cli } = cliEntry(runtime);
356
- const lower = wrapperPath.toLowerCase();
357
- // UTF-8 BOM: Windows PowerShell 5.1 decodes BOM-less .ps1 files in the ANSI
358
- // codepage, which mangles non-ASCII paths embedded in the shim.
359
- if (lower.endsWith(".ps1")) return `\uFEFF${buildWindowsPowerShellCodexShim(realCodexPath, bun, cli, bunRuntimeSource)}`;
360
- if (lower.endsWith(".cmd") || lower.endsWith(".bat")) return buildWindowsCodexShim(realCodexPath, bun, cli, bunRuntimeSource);
361
- // Extensionless Git-Bash sh launcher: sh shim with forward-slash paths.
362
- return buildUnixCodexShim(gitBashPath(realCodexPath), gitBashPath(bun), gitBashPath(cli), bunRuntimeSource, gitBashPath(serviceApiTokenFilePath()));
363
- }
364
-
365
- function writeShim(wrapperPath: string, realCodexPath: string, runtime?: DurableBunRuntime): { dev: number; ino: number } | undefined {
366
- const { bun, bunRuntimeSource, cli } = cliEntry(runtime);
367
- if (process.platform === "win32") {
368
- writeFileSync(wrapperPath, windowsShimContent(wrapperPath, realCodexPath, runtime), "utf8");
369
- return undefined;
370
- } else {
371
- // Stage the wrapper as its own inode and rename it into place, so ownership
372
- // comes from the write itself rather than from observing the path afterwards.
373
- // Writing the destination directly leaves a window in which a concurrent
374
- // updater can replace the file between our write and our fingerprint; we would
375
- // then adopt that replacement as ours and unlink it during rollback, deleting
376
- // an executable we never wrote.
377
- // Hidden and non-executable while staged, so a crash between the write and the
378
- // rename cannot leave an executable `codex*` artifact that a glob or a shell
379
- // completion would surface.
380
- const staged = join(dirname(wrapperPath), `.${basename(wrapperPath)}.opencodex-staging.${process.pid}.${randomUUID()}`);
381
- let renamed = false;
382
- try {
383
- // "wx" fails if the staging path somehow exists, so we never inherit a file.
384
- writeFileSync(staged, buildUnixCodexShim(realCodexPath, bun, cli, bunRuntimeSource), { encoding: "utf8", flag: "wx", mode: 0o600 });
385
- const stagedStat = lstatSync(staged);
386
- chmodSync(staged, 0o755);
387
- renameSync(staged, wrapperPath);
388
- renamed = true;
389
- // rename() preserves dev/ino and updates ctime, so identity is the inode
390
- // pair, captured from the file we created rather than from the destination.
391
- return { dev: stagedStat.dev, ino: stagedStat.ino };
392
- } finally {
393
- if (!renamed) {
394
- try { unlinkSync(staged); } catch { /* best-effort: nothing to clean up */ }
395
- }
396
- }
397
- }
398
- }
399
-
400
- /**
401
- * The fingerprint to record as "we wrote this", or `undefined` when the file at
402
- * `wrapperPath` is not the inode `writeShim()` created. Returning `undefined`
403
- * makes every rollback path treat the file as someone else's and leave it alone.
404
- */
405
- function ownedWrapperFingerprint(
406
- wrapperPath: string,
407
- written: { dev: number; ino: number } | undefined,
408
- ): ShimPathFingerprint | undefined {
409
- const probe = stableShimPathProbe(wrapperPath);
410
- if (!probe) return undefined;
411
- // Platforms that still write in place (Windows) have no staged identity; fall
412
- // back to the marker check they have always used.
413
- if (!written) return probe.prefix.includes(SHIM_MARKER) ? probe.fingerprint : undefined;
414
- if (probe.fingerprint.dev !== written.dev || probe.fingerprint.ino !== written.ino) return undefined;
415
- return probe.fingerprint;
416
- }
417
-
418
- /**
419
- * Whether the file now at the wrapper path is one this transaction may unlink.
420
- *
421
- * The inode our write created is the authority. It stays ours through an in-place
422
- * truncation — a partial write we must clean up — and stops being ours the moment
423
- * someone renames a different file over the path, which is exactly the concurrent
424
- * updater we must not delete. Where no inode was recorded (Windows writes the
425
- * destination directly), fall back to the exact fingerprint recorded at the time.
426
- */
427
- function wrapperInodeIsOurs(
428
- wrapper: StableShimPathProbe,
429
- written: { dev: number; ino: number } | undefined,
430
- recorded: ShimPathFingerprint | undefined,
431
- ): boolean {
432
- // A different inode is conclusive: someone renamed their own file over ours.
433
- if (written && (wrapper.fingerprint.dev !== written.dev || wrapper.fingerprint.ino !== written.ino)) {
434
- return false;
435
- }
436
- // Same inode is not sufficient on its own — an in-place truncation (shell `>`,
437
- // writeFileSync) keeps it while replacing the contents. When we recorded a full
438
- // fingerprint, require it to still match; that covers our own partial write,
439
- // whose fingerprint we record before anything can fail.
440
- if (recorded !== undefined) return sameFingerprint(wrapper.fingerprint, recorded);
441
- // No recorded fingerprint: only the inode identity we captured at write time can
442
- // speak for us, and there is nothing else to distinguish this file.
443
- return written !== undefined;
444
- }
445
-
446
328
  function primaryState(files: ShimFileState[]): ShimState {
447
329
  const first = files[0]!;
448
330
  return { platform: process.platform, ...first, wrappers: files };
@@ -1096,10 +978,21 @@ function installCodexShimInternal(options: InstallCodexShimInternalOptions): { i
1096
978
 
1097
979
  export function installCodexShim(deps: RuntimePreflightDeps = {}): { installed: boolean; message: string; refused?: boolean; runnable?: boolean } {
1098
980
  if (process.platform !== "win32") return installUnixOverlay(findCodexOnPath, lastCodexDiscoveryError);
1099
- return installCodexShimInternal({ ...deps, allowFreshInstall: true });
981
+ const gate = beginCodexCliSelectionParentWrite();
982
+ if (!gate.entered) return { installed: false, refused: true, message: "codex_cli_selection_busy" };
983
+ try { return installCodexShimInternal({ ...deps, allowFreshInstall: true }); }
984
+ finally { gate.exit(); }
985
+ }
986
+
987
+ export function autoRestoreCodexShim(options: Parameters<typeof autoRestoreWindowsCodexShim>[0]): CodexShimAutoRestoreResult {
988
+ if (process.platform !== "win32") return autoRestoreUnixOverlay(options);
989
+ const gate = beginCodexCliSelectionParentWrite();
990
+ if (!gate.entered) return { status: "deferred", message: "codex_cli_selection_busy" };
991
+ try { return autoRestoreWindowsCodexShim(options); }
992
+ finally { gate.exit(); }
1100
993
  }
1101
994
 
1102
- export function autoRestoreCodexShim(options: RuntimePreflightDeps & {
995
+ function autoRestoreWindowsCodexShim(options: RuntimePreflightDeps & {
1103
996
  enabled: () => boolean;
1104
997
  stabilitySleep?: (ms: number) => void;
1105
998
  /** Narrow deterministic seam used to hold the interprocess lock in tests. */
@@ -1109,7 +1002,6 @@ export function autoRestoreCodexShim(options: RuntimePreflightDeps & {
1109
1002
  /** Narrow deterministic race seam for the guarded transaction tests. */
1110
1003
  beforeGuardedRefresh?: (wrapperPath: string, index: number) => void;
1111
1004
  }): CodexShimAutoRestoreResult {
1112
- if (process.platform !== "win32") return autoRestoreUnixOverlay(options);
1113
1005
  const stateRead = readStateResult();
1114
1006
  const state = stateRead.state;
1115
1007
  if (!state) {
@@ -1223,6 +1115,13 @@ export function autoRestoreCodexShim(options: RuntimePreflightDeps & {
1223
1115
 
1224
1116
  export function uninstallCodexShim(): { removed: boolean; message: string } {
1225
1117
  if (process.platform !== "win32") return uninstallUnixCodexShim();
1118
+ const gate = beginCodexCliSelectionParentWrite();
1119
+ if (!gate.entered) return { removed: false, message: "codex_cli_selection_busy" };
1120
+ try { return uninstallWindowsCodexShim(); }
1121
+ finally { gate.exit(); }
1122
+ }
1123
+
1124
+ function uninstallWindowsCodexShim(): { removed: boolean; message: string } {
1226
1125
  const state = readState();
1227
1126
  if (!state) return { removed: false, message: "Codex autostart shim is not installed." };
1228
1127
  const files = stateFiles(state);
@@ -0,0 +1,119 @@
1
+ import { dlopen, ptr, read, type Library, type Symbols } from "bun:ffi";
2
+
3
+ // Windows x64 ABI only. No native binary, compiler, worker URL, or shell dependency.
4
+ export const WIN64_CHILD_ABI = Object.freeze({ securityAttributes: 24, securityDescriptor: 8, inheritHandle: 16,
5
+ startupInfo: 104, startupInfoEx: 112, startupFlags: 60, stdin: 80, stdout: 88, stderr: 96, attributes: 104,
6
+ processInformation: 24, process: 0, thread: 8, pid: 16, tid: 20,
7
+ overlapped: 32, event: 24, jobAccounting: 48, activeProcesses: 40 });
8
+ const KERNEL = {
9
+ GetLastError: { args: [], returns: "u32" },
10
+ SetLastError: { args: ["u32"], returns: "void" },
11
+ SetHandleInformation: { args: ["u64", "u32", "u32"], returns: "i32" },
12
+ DuplicateHandle: { args: ["u64", "u64", "u64", "ptr", "u32", "i32", "u32"], returns: "i32" },
13
+ GetCurrentProcess: { args: [], returns: "u64" },
14
+ CompareStringOrdinal: { args: ["ptr", "i32", "ptr", "i32", "i32"], returns: "i32" },
15
+ CreateJobObjectW: { args: ["ptr", "ptr"], returns: "u64" },
16
+ AssignProcessToJobObject: { args: ["u64", "u64"], returns: "i32" },
17
+ QueryInformationJobObject: { args: ["u64", "i32", "ptr", "u32", "ptr"], returns: "i32" },
18
+ TerminateJobObject: { args: ["u64", "u32"], returns: "i32" },
19
+ TerminateProcess: { args: ["u64", "u32"], returns: "i32" },
20
+ CreateProcessW: { args: ["ptr", "ptr", "ptr", "ptr", "i32", "u32", "ptr", "ptr", "ptr", "ptr"], returns: "i32" },
21
+ ResumeThread: { args: ["u64"], returns: "u32" },
22
+ WaitForSingleObject: { args: ["u64", "u32"], returns: "u32" },
23
+ GetExitCodeProcess: { args: ["u64", "ptr"], returns: "i32" },
24
+ GetProcessTimes: { args: ["u64", "ptr", "ptr", "ptr", "ptr"], returns: "i32" },
25
+ InitializeProcThreadAttributeList: { args: ["ptr", "u32", "u32", "ptr"], returns: "i32" },
26
+ UpdateProcThreadAttribute: { args: ["ptr", "u32", "u64", "ptr", "u64", "ptr", "ptr"], returns: "i32" },
27
+ DeleteProcThreadAttributeList: { args: ["ptr"], returns: "void" },
28
+ CreateNamedPipeW: { args: ["ptr", "u32", "u32", "u32", "u32", "u32", "u32", "ptr"], returns: "u64" },
29
+ ConnectNamedPipe: { args: ["u64", "ptr"], returns: "i32" },
30
+ CreateFileW: { args: ["ptr", "u32", "u32", "ptr", "u32", "u32", "u64"], returns: "u64" },
31
+ CreateEventW: { args: ["ptr", "i32", "i32", "ptr"], returns: "u64" },
32
+ ResetEvent: { args: ["u64"], returns: "i32" },
33
+ ReadFile: { args: ["u64", "ptr", "u32", "ptr", "ptr"], returns: "i32" },
34
+ GetOverlappedResult: { args: ["u64", "ptr", "ptr", "i32"], returns: "i32" },
35
+ CancelIoEx: { args: ["u64", "ptr"], returns: "i32" },
36
+ CloseHandle: { args: ["u64"], returns: "i32" },
37
+ LocalFree: { args: ["ptr"], returns: "ptr" },
38
+ } as const satisfies Symbols;
39
+ const ADVAPI = {
40
+ OpenProcessToken: { args: ["u64", "u32", "ptr"], returns: "i32" },
41
+ GetTokenInformation: { args: ["u64", "i32", "ptr", "u32", "ptr"], returns: "i32" },
42
+ ConvertSidToStringSidW: { args: ["ptr", "ptr"], returns: "i32" },
43
+ ConvertStringSecurityDescriptorToSecurityDescriptorW: { args: ["ptr", "u32", "ptr", "ptr"], returns: "i32" },
44
+ } as const satisfies Symbols;
45
+
46
+ export const wide = (value: string): Buffer => Buffer.from(`${value}\0`, "utf16le");
47
+ export function securityAttributes(inherit: boolean, descriptor = 0n): Buffer {
48
+ const bytes = Buffer.alloc(WIN64_CHILD_ABI.securityAttributes);
49
+ bytes.writeUInt32LE(bytes.length, 0); bytes.writeBigUInt64LE(descriptor, 8); bytes.writeUInt32LE(+inherit, 16);
50
+ return bytes;
51
+ }
52
+
53
+ type OwnedDispatch<SymbolsTable> = { -readonly [Key in keyof SymbolsTable]:
54
+ SymbolsTable[Key] extends (...args: infer Args) => infer Result ? (...args: Args) => Result : SymbolsTable[Key] };
55
+
56
+ /** Owns only handles returned by this invocation, never PID-reopened handles. */
57
+ export class WindowsChildNative {
58
+ readonly k: OwnedDispatch<Library<typeof KERNEL>["symbols"]>;
59
+ readonly a: OwnedDispatch<Library<typeof ADVAPI>["symbols"]>;
60
+ readonly handles = new Set<bigint>();
61
+ /** Explicit GC roots for pointers stored inside native attribute lists. */
62
+ readonly borrowedMemory = new Set<Buffer>();
63
+ readonly closeErrors: bigint[] = [];
64
+ private readonly kernel: Library<typeof KERNEL>;
65
+ private readonly advapi: Library<typeof ADVAPI>;
66
+ private closed = false;
67
+ constructor() {
68
+ if (process.platform !== "win32" || process.arch !== "x64") throw new Error("windows_child_unsupported_platform");
69
+ this.kernel = dlopen("kernel32.dll", KERNEL);
70
+ try { this.advapi = dlopen("advapi32.dll", ADVAPI); }
71
+ catch (error) { this.kernel.close(); throw error; }
72
+ // Own mutable dispatch tables permit per-instance fault injection in native fixtures.
73
+ this.k = { ...this.kernel.symbols }; this.a = { ...this.advapi.symbols };
74
+ }
75
+ keep(value: number | bigint): bigint {
76
+ const handle = BigInt(value);
77
+ if (!handle || handle === 0xffffffffffffffffn) throw new Error(`windows_child_handle_${this.k.GetLastError!()}`);
78
+ this.handles.add(handle); return handle;
79
+ }
80
+ close(handle: bigint): void {
81
+ if (!this.handles.has(handle)) return;
82
+ if (!this.k.CloseHandle!(handle)) { this.closeErrors.push(handle); return; }
83
+ this.handles.delete(handle);
84
+ }
85
+ dispose(): boolean {
86
+ if (this.handles.size || this.borrowedMemory.size) return false;
87
+ if (!this.closed) { this.closed = true; this.advapi.close(); this.kernel.close(); }
88
+ return true;
89
+ }
90
+ /** Protected DACL grants only the current token user. No default/world pipe ACL. */
91
+ privateDescriptor(): bigint {
92
+ const output = Buffer.alloc(8), size = Buffer.alloc(4);
93
+ if (!this.a.OpenProcessToken!(this.k.GetCurrentProcess!(), 8, ptr(output))) throw new Error("windows_child_token");
94
+ const token = this.keep(output.readBigUInt64LE());
95
+ let sidText = 0n;
96
+ try {
97
+ this.a.GetTokenInformation!(token, 1, null, 0, ptr(size));
98
+ const length = size.readUInt32LE();
99
+ if (length < 8 || length > 65536) throw new Error("windows_child_token_size");
100
+ const user = Buffer.alloc(length);
101
+ if (!this.a.GetTokenInformation!(token, 1, ptr(user), length, ptr(size))) throw new Error("windows_child_token_user");
102
+ const sid = user.readBigUInt64LE();
103
+ if (!this.a.ConvertSidToStringSidW!(sid, ptr(output))) throw new Error("windows_child_token_sid");
104
+ sidText = output.readBigUInt64LE();
105
+ let sidString = "";
106
+ for (let index = 0; index < 184; index++) {
107
+ const code = read.u16(sidText, index * 2);
108
+ if (!code) break;
109
+ sidString += String.fromCharCode(code);
110
+ }
111
+ if (!/^S-1-(?:\d+-)+\d+$/.test(sidString)) throw new Error("windows_child_sid_shape");
112
+ const sddl = wide(`D:P(A;;GA;;;${sidString})`);
113
+ if (!this.a.ConvertStringSecurityDescriptorToSecurityDescriptorW!(ptr(sddl), 1, ptr(output), null)) {
114
+ throw new Error("windows_child_pipe_acl");
115
+ }
116
+ return output.readBigUInt64LE();
117
+ } finally { if (sidText) this.k.LocalFree!(sidText); this.close(token); }
118
+ }
119
+ }
@@ -0,0 +1,87 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { ptr } from "bun:ffi";
3
+ import { securityAttributes, wide, WIN64_CHILD_ABI, WindowsChildNative } from "./windows-cli-child-native";
4
+
5
+ /** One overlapped operation and one retained buffer per pipe. Never PeekNamedPipe. */
6
+ export class WindowsChildPipe {
7
+ readonly overlapped = Buffer.alloc(WIN64_CHILD_ABI.overlapped);
8
+ readonly buffer = Buffer.alloc(64 * 1024);
9
+ readonly count = Buffer.alloc(4);
10
+ handle = 0n;
11
+ child = 0n;
12
+ event = 0n;
13
+ pending = false;
14
+ eof = false;
15
+ error = false;
16
+ private connecting = false;
17
+ private disposed = false;
18
+ constructor(readonly native: WindowsChildNative) {}
19
+ open(): void {
20
+ const n = this.native, k = n.k;
21
+ const descriptor = n.privateDescriptor();
22
+ try {
23
+ const sa = securityAttributes(false, descriptor), childSa = securityAttributes(true, descriptor);
24
+ const name = wide(`\\\\.\\pipe\\ocx-child-${randomUUID()}`);
25
+ // Inbound, OVERLAPPED, FIRST_PIPE_INSTANCE; byte stream, REJECT_REMOTE_CLIENTS.
26
+ this.handle = n.keep(k.CreateNamedPipeW!(ptr(name), 0x40080001, 8, 1, 0, this.buffer.length, 0, ptr(sa)));
27
+ this.event = n.keep(k.CreateEventW!(null, 1, 0, null));
28
+ this.overlapped.writeBigUInt64LE(this.event, 24);
29
+ // A known local client connects before ConnectNamedPipe: ERROR_PIPE_CONNECTED is success.
30
+ this.child = n.keep(k.CreateFileW!(ptr(name), 0x40000000, 0, ptr(childSa), 3, 0, 0n));
31
+ if (!k.ConnectNamedPipe!(this.handle, ptr(this.overlapped))) {
32
+ const error = Number(k.GetLastError!());
33
+ if (error === 997) { this.pending = true; this.connecting = true; }
34
+ else if (error !== 535) throw new Error(`windows_child_pipe_connect_${error}`);
35
+ }
36
+ } finally { k.LocalFree!(descriptor); }
37
+ }
38
+ closeChild(): void { if (this.child) { this.native.close(this.child); this.child = 0n; } }
39
+ /** Bounded synchronous work; pending overlapped operations always return immediately. */
40
+ pump(consume: (bytes: Buffer) => void): void {
41
+ if (this.disposed) return;
42
+ if (this.eof) return;
43
+ const k = this.native.k;
44
+ for (let i = 0; i < 4 && !this.eof; i++) {
45
+ let done: number;
46
+ if (this.pending) {
47
+ if (!k.GetOverlappedResult!(this.handle, ptr(this.overlapped), ptr(this.count), 0)) {
48
+ const error = Number(k.GetLastError!());
49
+ if (error === 996) return; // ERROR_IO_INCOMPLETE: retain buffers and operation.
50
+ if (this.overlapped.readBigUInt64LE(0) === 0x103n) { this.error = true; return; }
51
+ this.pending = false; this.finish(error); return;
52
+ }
53
+ this.pending = false;
54
+ if (this.connecting) { this.connecting = false; continue; }
55
+ done = this.count.readUInt32LE();
56
+ } else {
57
+ this.overlapped.fill(0); this.overlapped.writeBigUInt64LE(this.event, 24);
58
+ if (!k.ResetEvent!(this.event)) { this.finish(-1); return; }
59
+ if (!k.ReadFile!(this.handle, ptr(this.buffer), this.buffer.length, ptr(this.count), ptr(this.overlapped))) {
60
+ const error = Number(k.GetLastError!());
61
+ if (error === 997) { this.pending = true; return; }
62
+ this.finish(error); return;
63
+ }
64
+ done = this.count.readUInt32LE();
65
+ }
66
+ if (!done) { this.eof = true; return; }
67
+ consume(this.buffer.subarray(0, done));
68
+ }
69
+ }
70
+ private finish(error: number): void { this.eof = true; this.error = error !== 109; }
71
+ /** Cancel is only a request. Keep the OVERLAPPED, event and bytes until settlement. */
72
+ async dispose(): Promise<void> {
73
+ if (this.disposed) return;
74
+ this.closeChild();
75
+ if (this.pending) {
76
+ this.native.k.CancelIoEx!(this.handle, ptr(this.overlapped));
77
+ while (this.pending) {
78
+ if (this.native.k.GetOverlappedResult!(this.handle, ptr(this.overlapped), ptr(this.count), 0)
79
+ || (Number(this.native.k.GetLastError!()) !== 996 && this.overlapped.readBigUInt64LE(0) !== 0x103n)) this.pending = false;
80
+ else await Bun.sleep(5);
81
+ }
82
+ }
83
+ if (this.handle) this.native.close(this.handle);
84
+ if (this.event) this.native.close(this.event);
85
+ this.disposed = true;
86
+ }
87
+ }