@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,253 @@
1
+ /**
2
+ * Every role model write the omo tab and `ocx agent roles set` make, so a role can be put back.
3
+ * The integration journal cannot hold these: it snapshots one client config per operation, and a
4
+ * role write spans `$CODEX_HOME/agents/<role>.toml` and LazyCodex's omo.jsonc mirror. So the
5
+ * values are recorded rather than bytes, and a restore is an ordinary write of the earlier values.
6
+ * Writes made in one action (auto-assign's Apply all) share a batch and are restored together.
7
+ * The server hands out batch ids and a write joins a batch only while the history still holds it whole,
8
+ * so an id compaction dropped can never start over and pass for the beginning of a batch. Every row
9
+ * carries its number in its batch, which keeps the cap durable and lets a read tell a whole batch
10
+ * from a cut one, which is never listed or restored.
11
+ * The file sits under the opencodex config directory, which outlives a switch of Codex home, so every
12
+ * row names the canonical Codex home it was written in and only that home's rows are listed or restored.
13
+ * The file is bounded three ways: a batch holds at most ROLE_HISTORY_LIMIT rows, an append that takes
14
+ * the file past ROLE_HISTORY_MAX_BYTES rewrites it to its newest whole batches, and a read looks at
15
+ * no more than that many bytes and ROLE_HISTORY_MAX_ROWS rows from the end.
16
+ */
17
+ import { appendFileSync, closeSync, fstatSync, openSync, readSync, statSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { atomicWriteFile } from "../config/atomic-write";
20
+ import { ensureDir, integrationsDir } from "../integrations/ownership";
21
+
22
+ export interface RoleSetting {
23
+ readonly model: string | null;
24
+ readonly effort: string | null;
25
+ }
26
+
27
+ export interface RoleModelChange {
28
+ readonly at: string;
29
+ readonly batch: string;
30
+ readonly role: string;
31
+ readonly before: RoleSetting;
32
+ readonly after: RoleSetting;
33
+ }
34
+
35
+ interface StoredRoleModelChange extends RoleModelChange {
36
+ readonly codexHome: string;
37
+ /** This row's number in its batch, from 1: a batch is whole when it holds rows 1 to its highest. */
38
+ readonly n: number;
39
+ /** The batch this row's write restored, so compaction keeps that batch while the Restore is kept. */
40
+ readonly restores?: string;
41
+ }
42
+
43
+ /** The batch a write is recorded in and its row number there. */
44
+ export interface BatchSlot {
45
+ readonly batch: string;
46
+ readonly n: number;
47
+ }
48
+
49
+ /** Rows one listing returns, and rows one batch may hold, so a whole batch always fits a listing. */
50
+ export const ROLE_HISTORY_LIMIT = 50;
51
+ export const ROLE_HISTORY_MAX_BYTES = 256 * 1024;
52
+ export const ROLE_HISTORY_MAX_ROWS = 1000;
53
+ const BATCH_PATTERN = /^[A-Za-z0-9-]{1,64}$/;
54
+
55
+ function historyPath(dir: string): string {
56
+ return join(dir, "codex-agent-roles.jsonl");
57
+ }
58
+
59
+ export function isRoleHistoryBatch(value: unknown): value is string {
60
+ return typeof value === "string" && BATCH_PATTERN.test(value);
61
+ }
62
+
63
+ /** `codexHome` is the canonical path `getCodexHome()` returns, so two spellings of one home match. */
64
+ export function recordRoleModelChange(codexHome: string, change: RoleModelChange & { readonly n: number; readonly restores?: string }, dir: string = integrationsDir()): void {
65
+ ensureDir(historyPath(dir));
66
+ const stored: StoredRoleModelChange = { ...change, codexHome };
67
+ // Capture the complete source before this append can move its first row outside either tail limit.
68
+ const tail = tailRows(historyPath(dir));
69
+ // An interrupted JSONL suffix must not swallow the first record returned after restart.
70
+ appendFileSync(historyPath(dir), `${tail.unterminated ? "\n" : ""}${JSON.stringify(stored)}\n`, { encoding: "utf8", mode: 0o600 });
71
+ if (statSync(historyPath(dir)).size <= ROLE_HISTORY_MAX_BYTES && tail.lines < ROLE_HISTORY_MAX_ROWS) return;
72
+ try {
73
+ compact(dir, wholeBatches([stored, ...tail.rows]));
74
+ } catch (cause) {
75
+ // Reads stay bounded without the trim; the next append retries it.
76
+ throw new Error("recorded the change but could not trim the history file", { cause });
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Rewrite the file to its newest rows within half the byte budget and the row budget, so the next
82
+ * compaction is many saves away. A batch the cut falls inside is dropped whole, for every Codex home,
83
+ * so no home is left with part of an Apply all to restore. A kept Restore keeps the batch it restores
84
+ * whole when the Restore and its sources fit both read limits; protected rows displace older batches.
85
+ */
86
+ function compact(dir: string, rows: StoredRoleModelChange[]): void {
87
+ const batches = new Map<string, StoredRoleModelChange[]>();
88
+ for (const row of rows) {
89
+ const key = batchKey(row);
90
+ batches.set(key, [...(batches.get(key) ?? []), row]);
91
+ }
92
+ const keep = new Set<string>();
93
+ let bytes = 0;
94
+ let count = 0;
95
+ for (const key of batches.keys()) {
96
+ if (keep.has(key)) continue;
97
+ const needed = new Set([key]);
98
+ // Include source dependencies before admitting a batch, so they share its byte and row budgets.
99
+ for (const dependency of needed) {
100
+ for (const row of batches.get(dependency) ?? []) {
101
+ if (row.restores) {
102
+ const source = batchKey({ ...row, batch: row.restores });
103
+ if (batches.has(source) && !keep.has(source)) needed.add(source);
104
+ }
105
+ }
106
+ }
107
+ const added = rows.filter(row => needed.has(batchKey(row)));
108
+ const addedBytes = added.reduce((sum, row) => sum + Buffer.byteLength(JSON.stringify(row)) + 1, 0);
109
+ if (bytes + addedBytes > ROLE_HISTORY_MAX_BYTES || count + added.length > ROLE_HISTORY_MAX_ROWS) break;
110
+ // Ordinary batches stay within the half-budget target; Restore sources may use the headroom.
111
+ if (bytes + addedBytes > ROLE_HISTORY_MAX_BYTES / 2 && !added.some(row => row.restores)) break;
112
+ for (const dependency of needed) keep.add(dependency);
113
+ bytes += addedBytes;
114
+ count += added.length;
115
+ if (bytes >= ROLE_HISTORY_MAX_BYTES / 2) break;
116
+ }
117
+ const whole = rows.filter(row => keep.has(batchKey(row))).reverse();
118
+ atomicWriteFile(historyPath(dir), whole.map(row => `${JSON.stringify(row)}\n`).join(""));
119
+ }
120
+
121
+ function batchKey(row: Pick<StoredRoleModelChange, "codexHome" | "batch">): string {
122
+ return `${row.codexHome}\n${row.batch}`;
123
+ }
124
+
125
+ function isSetting(value: unknown): value is RoleSetting {
126
+ const setting = value as RoleSetting | null;
127
+ return typeof setting === "object" && setting !== null
128
+ && (setting.model === null || typeof setting.model === "string")
129
+ && (setting.effort === null || typeof setting.effort === "string");
130
+ }
131
+
132
+ function parseRow(line: string): StoredRoleModelChange | null {
133
+ let value: unknown;
134
+ try {
135
+ value = JSON.parse(line);
136
+ } catch {
137
+ return null;
138
+ }
139
+ const change = value as StoredRoleModelChange | null;
140
+ return typeof change === "object" && change !== null && typeof change.codexHome === "string"
141
+ && typeof change.at === "string" && typeof change.role === "string"
142
+ && isRoleHistoryBatch(change.batch) && isSetting(change.before) && isSetting(change.after)
143
+ && Number.isSafeInteger(change.n) && change.n >= 1
144
+ && (change.restores === undefined || isRoleHistoryBatch(change.restores))
145
+ ? change
146
+ : null;
147
+ }
148
+
149
+ /**
150
+ * Every Codex home's rows, newest first, from at most the last ROLE_HISTORY_MAX_BYTES of the file and
151
+ * at most ROLE_HISTORY_MAX_ROWS of them. When the read starts mid-file, its first partial line is
152
+ * skipped; a batch that continues above the read is left for `wholeBatches` to drop.
153
+ */
154
+ function tailRows(path: string): { rows: StoredRoleModelChange[]; lines: number; unterminated: boolean } {
155
+ let fd: number;
156
+ try {
157
+ fd = openSync(path, "r");
158
+ } catch (error) {
159
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { rows: [], lines: 0, unterminated: false };
160
+ throw error;
161
+ }
162
+ let text: string;
163
+ try {
164
+ const stat = fstatSync(fd);
165
+ // Windows opens a directory for reading, so the type is checked rather than left to the read.
166
+ if (!stat.isFile()) throw new Error(`${path} is not a regular file`);
167
+ const size = stat.size;
168
+ const start = Math.max(0, size - ROLE_HISTORY_MAX_BYTES - 1);
169
+ const bytes = Buffer.alloc(size - start);
170
+ let length = 0;
171
+ while (length < bytes.length) {
172
+ const count = readSync(fd, bytes, length, bytes.length - length, start + length);
173
+ if (count === 0) break;
174
+ length += count;
175
+ }
176
+ const read = bytes.subarray(0, length);
177
+ text = (start > 0 ? read.subarray(read.indexOf(10) + 1) : read).toString("utf8");
178
+ } finally {
179
+ closeSync(fd);
180
+ }
181
+ const lines = text.split("\n").filter(line => line.trim()).slice(-ROLE_HISTORY_MAX_ROWS);
182
+ const rows = lines.flatMap(line => {
183
+ const row = parseRow(line);
184
+ return row ? [row] : [];
185
+ }).reverse();
186
+ return { rows, lines: lines.length, unterminated: text.length > 0 && !text.endsWith("\n") };
187
+ }
188
+
189
+ /**
190
+ * The rows of every batch that holds each of its rows 1 to its highest, so a batch the read or a
191
+ * compaction cut into is never offered as if it were whole.
192
+ */
193
+ function wholeBatches(rows: StoredRoleModelChange[]): StoredRoleModelChange[] {
194
+ const numbers = new Map<string, Set<number>>();
195
+ const highest = new Map<string, number>();
196
+ for (const row of rows) {
197
+ const key = batchKey(row);
198
+ numbers.set(key, (numbers.get(key) ?? new Set()).add(row.n));
199
+ highest.set(key, Math.max(highest.get(key) ?? 0, row.n));
200
+ }
201
+ return rows.filter(row => numbers.get(batchKey(row))!.size === highest.get(batchKey(row)));
202
+ }
203
+
204
+ function forHome(rows: StoredRoleModelChange[], codexHome: string): RoleModelChange[] {
205
+ return rows.flatMap(({ codexHome: home, n: _n, restores: _restores, ...change }) => home === codexHome ? [change] : []);
206
+ }
207
+
208
+ /**
209
+ * This Codex home's changes, newest first, in whole batches and never more than `limit` rows: batches
210
+ * are taken newest first until the next would not fit, so Restore never puts back part of an Apply all.
211
+ * A batch larger than `limit` (written before batches were capped) can never be listed whole and is
212
+ * skipped. A torn or foreign line, and a row another Codex home wrote, is skipped, the way the
213
+ * integration journal reads its own.
214
+ */
215
+ export function listRoleModelChanges(codexHome: string, limit: number = ROLE_HISTORY_LIMIT, dir: string = integrationsDir()): RoleModelChange[] {
216
+ const newestFirst = forHome(wholeBatches(tailRows(historyPath(dir)).rows), codexHome);
217
+ const sizes = new Map<string, number>();
218
+ for (const change of newestFirst) sizes.set(change.batch, (sizes.get(change.batch) ?? 0) + 1);
219
+ const listed = new Set<string>();
220
+ let count = 0;
221
+ for (const [batch, size] of sizes) {
222
+ if (size > limit) continue;
223
+ if (count + size > limit) break;
224
+ listed.add(batch);
225
+ count += size;
226
+ }
227
+ return newestFirst.filter(change => listed.has(change.batch));
228
+ }
229
+
230
+ /**
231
+ * Where a write in this Codex home is recorded. Without `batch` it starts a new batch under a fresh id.
232
+ * With one, it joins that batch only while this home's retained history holds the batch whole, and is
233
+ * refused once the batch holds ROLE_HISTORY_LIMIT rows. An id compaction dropped, or one the server
234
+ * never handed out, is closed: it cannot take a row and pass for the start of a batch.
235
+ */
236
+ export function claimBatchRow(codexHome: string, batch: string | undefined, dir: string = integrationsDir()): BatchSlot | "batch_closed" | "batch_full" {
237
+ if (batch === undefined) return { batch: crypto.randomUUID(), n: 1 };
238
+ const held = wholeBatches(tailRows(historyPath(dir)).rows).filter(row => row.codexHome === codexHome && row.batch === batch);
239
+ if (held.length === 0) return "batch_closed";
240
+ return held.length >= ROLE_HISTORY_LIMIT ? "batch_full" : { batch, n: held.length + 1 };
241
+ }
242
+
243
+ /**
244
+ * The setting a Restore of `batch` may put back on `role` in this Codex home: the role's earliest
245
+ * `before` in that batch, or null when this home's retained history has no such change. The server
246
+ * checks a restore against it, so a dashboard still showing another home's history cannot write
247
+ * that home's earlier models here. It reads every retained batch rather than the 50-row listing,
248
+ * because a Restore's own rows push the batch it restores out of that listing before it finishes.
249
+ */
250
+ export function restorableSetting(codexHome: string, batch: string, role: string, dir: string = integrationsDir()): RoleSetting | null {
251
+ const changes = forHome(wholeBatches(tailRows(historyPath(dir)).rows), codexHome).filter(change => change.batch === batch && change.role === role);
252
+ return changes.at(-1)?.before ?? null;
253
+ }
@@ -1,9 +1,20 @@
1
1
  import { execFile, execFileSync } from "node:child_process";
2
- import { closeSync, constants, existsSync, fstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, unlinkSync } from "node:fs";
2
+ import { closeSync, constants, existsSync, fstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, unlinkSync } from "node:fs";
3
3
  import { homedir, tmpdir } from "node:os";
4
- import { delimiter, join, posix } from "node:path";
4
+ import { delimiter, join } from "node:path";
5
5
  import { atomicWriteFile, getConfigDir } from "../config";
6
- import { codexExecInvocation, isSpawnableCodexCandidate } from "./exec-invocation";
6
+ import { isSpawnableCodexCandidate } from "./exec-invocation";
7
+ import type { SpawnInvocation } from "../lib/win-exec";
8
+ import {
9
+ CodexExecTrustError,
10
+ validatedCodexExecTarget,
11
+ validatedCodexExecTargetAsync,
12
+ } from "./exec-boundary";
13
+ import { macCodexAppBundleFor, macCodexAppCommands } from "./mac-app-bundle";
14
+ import {
15
+ beginCodexCliSelectionParentWrite,
16
+ CodexCliSelectionMutationBusyError,
17
+ } from "./cli-update-selection-gate";
7
18
  import { resolveCodexHomeDir } from "./home";
8
19
  import { decodeOverlayState } from "./shim-state-file";
9
20
  import { redactSecretString, redactUserPath } from "../lib/redact";
@@ -92,6 +103,14 @@ export interface ResolveCodexRuntimeDeps {
92
103
  readFileSync?: (path: string, encoding: "utf8") => string;
93
104
  /** Bounded in-process macOS bundle identity reader; injected readers bypass the memo. */
94
105
  readBundleIdentifier?: (infoPlistPath: string) => string | null;
106
+ /** macOS bundle publisher/filesystem trust check; injected checks bypass the memo. */
107
+ macBundleTrustReason?: (bundleRoot: string, binary: string) => string | null;
108
+ /** Async twin used by resolveCodexRuntimeAsync; injected checks bypass the memo. */
109
+ macBundleTrustReasonAsync?: (bundleRoot: string, binary: string, signal?: AbortSignal) => Promise<string | null>;
110
+ /** POSIX spawnability predicate at the exec boundary (regular file + X_OK). */
111
+ executable?: (path: string) => boolean;
112
+ /** Canonicalizer at the exec boundary; returns null when the path cannot be resolved. */
113
+ realpath?: (path: string) => string | null;
95
114
  now?: () => number;
96
115
  /**
97
116
  * When false, stop after the first valid priority candidate (skip PATH-wide
@@ -382,19 +401,30 @@ export function persistCodexRuntime(
382
401
  deps: ResolveCodexRuntimeDeps = {},
383
402
  origin: CodexRuntimePinOrigin = "pinned",
384
403
  ): void {
385
- const configDir = deps.configDir ?? getConfigDir();
386
- mkdirSync(configDir, { recursive: true, mode: 0o700 });
387
- const payload: PersistedCodexRuntimeState = {
388
- version: 1,
389
- command: runtime.command,
390
- source: runtime.source,
391
- selectedVersion: runtime.version,
392
- updatedAt: new Date((deps.now ?? Date.now)()).toISOString(),
393
- origin,
394
- };
395
- // Invalidate process authority before the persisted replacement is visible.
396
- clearCodexRuntimeResolveCache();
397
- atomicWriteFile(codexRuntimeStatePath(configDir), `${JSON.stringify(payload, null, 2)}\n`);
404
+ // A cli-update worker holds the shared selection gate from its final process
405
+ // scan through its installer spawn; this write must not slip into that
406
+ // window, so a held gate is an immediate busy rather than a wait. Checked
407
+ // BEFORE the mkdir and the resolve-cache invalidation so a busy refusal
408
+ // changes nothing at all.
409
+ const selectionWrite = beginCodexCliSelectionParentWrite();
410
+ if (!selectionWrite.entered) throw new CodexCliSelectionMutationBusyError();
411
+ try {
412
+ const configDir = deps.configDir ?? getConfigDir();
413
+ mkdirSync(configDir, { recursive: true, mode: 0o700 });
414
+ const payload: PersistedCodexRuntimeState = {
415
+ version: 1,
416
+ command: runtime.command,
417
+ source: runtime.source,
418
+ selectedVersion: runtime.version,
419
+ updatedAt: new Date((deps.now ?? Date.now)()).toISOString(),
420
+ origin,
421
+ };
422
+ // Invalidate process authority before the persisted replacement is visible.
423
+ clearCodexRuntimeResolveCache();
424
+ atomicWriteFile(codexRuntimeStatePath(configDir), `${JSON.stringify(payload, null, 2)}\n`);
425
+ } finally {
426
+ selectionWrite.exit();
427
+ }
398
428
  }
399
429
 
400
430
  /**
@@ -405,24 +435,33 @@ export function persistCodexRuntime(
405
435
  * folds the persisted `updatedAt` into its key, and a removed file has no stamp to fold.
406
436
  */
407
437
  export function clearPersistedCodexRuntime(deps: ResolveCodexRuntimeDeps = {}): void {
408
- const configDir = deps.configDir ?? getConfigDir();
409
- clearCodexRuntimeResolveCache();
438
+ // Same gate as persistCodexRuntime, checked before the cache invalidation
439
+ // and outside the swallowing catch: a busy refusal must stay an error, not
440
+ // become a silent "already removed".
441
+ const selectionWrite = beginCodexCliSelectionParentWrite();
442
+ if (!selectionWrite.entered) throw new CodexCliSelectionMutationBusyError();
410
443
  try {
411
- unlinkSync(codexRuntimeStatePath(configDir));
412
- } catch (error) {
413
- // An already-missing file is the success case: the pin is gone, which is the point.
414
- // Anything else means the pin SURVIVES and stays authoritative, so every later
415
- // resolve re-probes the same dead path — #4035 unfixed, silently. Say so once.
416
- const code = (error as NodeJS.ErrnoException | null)?.code;
417
- if (code === "ENOENT") return;
418
- console.warn(
419
- `[opencodex] Could not remove the stale Codex runtime pin at ${displayCodexRuntimePath(codexRuntimeStatePath(configDir))}`
420
- + ` (${code ?? "unknown error"}). It will be re-probed until the file is removed.`,
421
- );
444
+ const configDir = deps.configDir ?? getConfigDir();
445
+ clearCodexRuntimeResolveCache();
446
+ try {
447
+ unlinkSync(codexRuntimeStatePath(configDir));
448
+ } catch (error) {
449
+ // An already-missing file is the success case: the pin is gone, which is the point.
450
+ // Anything else means the pin SURVIVES and stays authoritative, so every later
451
+ // resolve re-probes the same dead path — #4035 unfixed, silently. Say so once.
452
+ const code = (error as NodeJS.ErrnoException | null)?.code;
453
+ if (code === "ENOENT") return;
454
+ console.warn(
455
+ `[opencodex] Could not remove the stale Codex runtime pin at ${displayCodexRuntimePath(codexRuntimeStatePath(configDir))}`
456
+ + ` (${code ?? "unknown error"}). It will be re-probed until the file is removed.`,
457
+ );
458
+ }
459
+ } finally {
460
+ selectionWrite.exit();
422
461
  }
423
462
  }
424
463
 
425
- type VersionProbeResult = { ok: true; version: string | null } | { ok: false; reason: string };
464
+ type VersionProbeResult = { ok: true; version: string | null; macAppBundle?: boolean } | { ok: false; reason: string };
426
465
 
427
466
  /** Checks that need no exec; a non-null answer settles the candidate without running `--version`. */
428
467
  function versionProbePrecheck(command: string, deps: ResolveCodexRuntimeDeps): VersionProbeResult | null {
@@ -445,11 +484,19 @@ function versionProbePrecheck(command: string, deps: ResolveCodexRuntimeDeps): V
445
484
  return null;
446
485
  }
447
486
 
448
- function versionProbeInvocation(command: string, deps: ResolveCodexRuntimeDeps, probeHome: string) {
449
- const invocation = codexExecInvocation(command, ["--version"], deps.platform ?? process.platform, {
487
+ /** The sync and async probes differ only in which exec-boundary check builds this invocation. */
488
+ function codexExecBoundaryDeps(deps: ResolveCodexRuntimeDeps) {
489
+ return {
450
490
  env: deps.env,
491
+ platform: deps.platform,
451
492
  exists: deps.existsSync,
452
- });
493
+ executable: deps.executable,
494
+ realpath: deps.realpath,
495
+ macBundleTrustReason: deps.macBundleTrustReason,
496
+ };
497
+ }
498
+
499
+ function versionProbeInvocation(deps: ResolveCodexRuntimeDeps, probeHome: string, invocation: SpawnInvocation) {
453
500
  return {
454
501
  file: invocation.file,
455
502
  args: invocation.args,
@@ -464,10 +511,10 @@ function versionProbeInvocation(command: string, deps: ResolveCodexRuntimeDeps,
464
511
  };
465
512
  }
466
513
 
467
- function versionProbeOutput(output: string): VersionProbeResult {
514
+ function versionProbeOutput(output: string, macAppBundle: boolean): VersionProbeResult {
468
515
  const version = parseCodexVersionOutput(output);
469
516
  if (!version) return { ok: false, reason: "unrecognized --version output" };
470
- return { ok: true, version };
517
+ return { ok: true, version, macAppBundle };
471
518
  }
472
519
 
473
520
  function versionProbeError(error: unknown, probeHome: string | undefined): VersionProbeResult {
@@ -498,9 +545,13 @@ function probeVersion(command: string, deps: ResolveCodexRuntimeDeps): VersionPr
498
545
  let probeHome: string | undefined;
499
546
  try {
500
547
  probeHome = mkdtempSync(join(tmpdir(), "ocx-codex-probe-"));
501
- const { file, args, options } = versionProbeInvocation(command, deps, probeHome);
502
- return versionProbeOutput(exec(file, args, options));
548
+ const target = validatedCodexExecTarget(command, ["--version"], codexExecBoundaryDeps(deps));
549
+ const { file, args, options } = versionProbeInvocation(deps, probeHome, target.invocation);
550
+ return versionProbeOutput(exec(file, args, options), target.macAppBundle);
503
551
  } catch (error) {
552
+ if (error instanceof CodexExecTrustError) {
553
+ return { ok: false, reason: redactUserPath(redactSecretString(error.message)).slice(0, 160) };
554
+ }
504
555
  return versionProbeError(error, probeHome);
505
556
  } finally {
506
557
  removeProbeHome(probeHome);
@@ -561,9 +612,17 @@ async function probeVersionAsync(command: string, deps: ResolveCodexRuntimeDeps)
561
612
  let probeHome: string | undefined;
562
613
  try {
563
614
  probeHome = mkdtempSync(join(tmpdir(), "ocx-codex-probe-"));
564
- const { file, args, options } = versionProbeInvocation(command, deps, probeHome);
565
- return versionProbeOutput(await exec(file, args, { ...options, signal: deps.signal }));
615
+ const target = await validatedCodexExecTargetAsync(command, ["--version"], {
616
+ ...codexExecBoundaryDeps(deps),
617
+ macBundleTrustReasonAsync: deps.macBundleTrustReasonAsync,
618
+ signal: deps.signal,
619
+ });
620
+ const { file, args, options } = versionProbeInvocation(deps, probeHome, target.invocation);
621
+ return versionProbeOutput(await exec(file, args, { ...options, signal: deps.signal }), target.macAppBundle);
566
622
  } catch (error) {
623
+ if (error instanceof CodexExecTrustError) {
624
+ return { ok: false, reason: redactUserPath(redactSecretString(error.message)).slice(0, 160) };
625
+ }
567
626
  return versionProbeError(error, probeHome);
568
627
  } finally {
569
628
  removeProbeHome(probeHome);
@@ -615,37 +674,12 @@ function pathCandidates(deps: ResolveCodexRuntimeDeps): string[] {
615
674
  return [...new Set(out)];
616
675
  }
617
676
 
618
- /** Conventional Codex desktop bundles, ordered system before user. */
619
- function macCodexAppBundles(deps: ResolveCodexRuntimeDeps): string[] {
620
- const env = deps.env ?? process.env;
621
- const home = env.HOME?.trim() || env.USERPROFILE?.trim() || homedir();
622
- return ["/Applications/ChatGPT.app", posix.join(home, "Applications/ChatGPT.app")];
623
- }
624
-
625
- function macCodexAppCommands(deps: ResolveCodexRuntimeDeps): string[] {
626
- return macCodexAppBundles(deps).flatMap(bundle => [
627
- `${bundle}/Contents/Resources/codex-cli/bin/codex`, `${bundle}/Contents/Resources/codex`,
628
- ]);
629
- }
630
-
631
- function realpathOrNull(path: string): string | null {
632
- try { return realpathSync(path); } catch { return null; }
633
- }
634
-
635
677
  /**
636
- * Classify any path inside either bundle, including backing executables, by normalized and
637
- * canonical forms with a segment boundary: a symlinked HOME (or /tmp -> /private/tmp) must not
638
- * let a canonical bundle path skip the identity check or the handover exclusion.
678
+ * Bundle-identity eligibility only. This runs inside the exec-free precheck and
679
+ * inside deferred/passive enumeration, so it must never spawn: signature and
680
+ * ownership trust is enforced at the execution boundary (exec-boundary.ts)
681
+ * every time the selected command is actually run, not once at selection.
639
682
  */
640
- function macCodexAppBundleFor(command: string, deps: ResolveCodexRuntimeDeps): string | undefined {
641
- if ((deps.platform ?? process.platform) !== "darwin" || !posix.isAbsolute(command)) return undefined;
642
- const forms = [posix.normalize(command), realpathOrNull(command)].filter((form): form is string => Boolean(form));
643
- return macCodexAppBundles(deps).find(bundle => {
644
- const roots = [posix.normalize(bundle), realpathOrNull(bundle)].filter((root): root is string => Boolean(root));
645
- return forms.some(form => roots.some(root => form.startsWith(`${root}/`)));
646
- });
647
- }
648
-
649
683
  function macCodexAppIdentityMatches(command: string, deps: ResolveCodexRuntimeDeps): boolean {
650
684
  const bundle = macCodexAppBundleFor(command, deps);
651
685
  if (!bundle) return true;
@@ -1015,6 +1049,10 @@ function resolveCacheKey(deps: ResolveCodexRuntimeDeps): string | null {
1015
1049
  || deps.existsSync
1016
1050
  || deps.readFileSync
1017
1051
  || deps.readBundleIdentifier
1052
+ || deps.macBundleTrustReason
1053
+ || deps.macBundleTrustReasonAsync
1054
+ || deps.executable
1055
+ || deps.realpath
1018
1056
  || deps.readdirSync
1019
1057
  || deps.statSync
1020
1058
  || deps.configDir
@@ -1212,6 +1250,7 @@ function* resolveCodexRuntimeSteps(
1212
1250
 
1213
1251
  const seen = new Set<string>();
1214
1252
  const valid: ResolvedCodexRuntime[] = [];
1253
+ const probedAppCommands = new Set<string>();
1215
1254
  // A caller that declined PATH-wide discovery normally gets the first valid
1216
1255
  // candidate and nothing else, which is right for a hot path and wrong for
1217
1256
  // exactly one arrangement: an unpinned persisted selection sitting in front of
@@ -1249,6 +1288,9 @@ function* resolveCodexRuntimeSteps(
1249
1288
  continue;
1250
1289
  }
1251
1290
  valid.push({ command: candidate.command, version: probed.version, source: candidate.source });
1291
+ // Keep the actual executed target's classification, including a bare PATH alias.
1292
+ // Deferred candidates have no version and cannot trigger a version-based takeover.
1293
+ if (probed.macAppBundle) probedAppCommands.add(candidate.command);
1252
1294
  }
1253
1295
 
1254
1296
  if (valid.length === 0) {
@@ -1299,7 +1341,7 @@ function* resolveCodexRuntimeSteps(
1299
1341
  const newerDiscovered = valid
1300
1342
  .filter(item =>
1301
1343
  !sameRuntimeCommand(item.command, selected.command)
1302
- && !macCodexAppBundleFor(item.command, deps)
1344
+ && !probedAppCommands.has(item.command)
1303
1345
  && typeof item.version === "string"
1304
1346
  && typeof selected.version === "string"
1305
1347
  && compareCodexVersions(item.version, selected.version) > 0)
@@ -1363,9 +1405,16 @@ export async function resolveAndPersistCodexRuntimeAsync(
1363
1405
  deps: ResolveCodexRuntimeDeps = {},
1364
1406
  isCurrent: () => boolean = () => true,
1365
1407
  ): Promise<ResolveCodexRuntimeResult | null> {
1366
- const observation = await resolveCodexRuntimeObservationAsync(deps);
1367
- if (!isCurrent() || observation.epoch === null || observation.epoch !== resolveCacheEpoch
1408
+ if (deps.signal?.aborted) return null;
1409
+ let observation: AsyncRuntimeObservation;
1410
+ try { observation = await resolveCodexRuntimeObservationAsync(deps); }
1411
+ catch (error) {
1412
+ if (deps.signal?.aborted) return null;
1413
+ throw error;
1414
+ }
1415
+ if (deps.signal?.aborted || !isCurrent() || observation.epoch === null || observation.epoch !== resolveCacheEpoch
1368
1416
  || observation.inputs !== codexRuntimeSelectionIdentity(deps)) return null;
1417
+ if (deps.signal?.aborted) return null;
1369
1418
  return cloneAndDeepFreeze(persistResolvedCodexRuntime(observation.result, deps));
1370
1419
  }
1371
1420
 
@@ -5,6 +5,10 @@ import {
5
5
  } from "node:fs";
6
6
  import { dirname, isAbsolute, join, resolve } from "node:path";
7
7
  import { getConfigDir } from "../config";
8
+ import {
9
+ beginCodexCliSelectionParentWrite,
10
+ CodexCliSelectionMutationBusyError,
11
+ } from "./cli-update-selection-gate";
8
12
  import { durableBunRuntime } from "../lib/bun-runtime";
9
13
  import { recordOwnedConfigPath } from "../lib/config-ownership";
10
14
  import { truncateRetainedUtf8 } from "../lib/admission";
@@ -442,6 +446,12 @@ function installLocked(
442
446
  return publishOverlay(launcher, overlay, check, pinnedState);
443
447
  }
444
448
  export function installUnixOverlay(discover: () => string | null, describeMiss?: () => string | null): InstallResult {
449
+ // The update worker's commit window re-observes selection evidence right up
450
+ // to its installer spawn; a shim install must not cross that window. Busy is
451
+ // surfaced before namespace creation, the restore lock and any journal
452
+ // mutation, so a held gate refuses without touching state.
453
+ const selectionWrite = beginCodexCliSelectionParentWrite();
454
+ if (!selectionWrite.entered) return failure(new CodexCliSelectionMutationBusyError());
445
455
  let lock: ReturnType<typeof tryAcquireShimRestoreLock> = null;
446
456
  try {
447
457
  const check = namespace(true);
@@ -450,7 +460,7 @@ export function installUnixOverlay(discover: () => string | null, describeMiss?:
450
460
  check();
451
461
  return installLocked(discover, false, check, describeMiss);
452
462
  } catch (error) { return failure(error); }
453
- finally { lock?.release(); }
463
+ finally { selectionWrite.exit(); lock?.release(); }
454
464
  }
455
465
  export function autoRestoreUnixOverlay(options: RestoreOptions): CodexShimAutoRestoreResult {
456
466
  const result = readStateResult();
@@ -468,6 +478,11 @@ export function autoRestoreUnixOverlay(options: RestoreOptions): CodexShimAutoRe
468
478
  } catch (error) { return { status: "ineligible", message: failure(error).message }; }
469
479
  if (!nativeProbe(state.launcherPath)) return { status: "ineligible", message: "Recorded native Codex launcher is unusable; repair it with its package manager" };
470
480
  if (!options.enabled()) return { status: "disabled" };
481
+ // Same selection gate as install: acquired before namespace creation, the
482
+ // restore lock and journal mutation; a held update commit window defers the
483
+ // restore rather than racing it.
484
+ const selectionWrite = beginCodexCliSelectionParentWrite();
485
+ if (!selectionWrite.entered) return { status: "deferred", message: "a Codex CLI update is committing an install; shim restore deferred" };
471
486
  let lock: ReturnType<typeof tryAcquireShimRestoreLock> = null;
472
487
  try {
473
488
  const check = namespace(true);
@@ -484,9 +499,13 @@ export function autoRestoreUnixOverlay(options: RestoreOptions): CodexShimAutoRe
484
499
  const installed = installLocked(() => null, true, check);
485
500
  return installed.installed ? { status: "restored", message: installed.message } : { status: "healthy" };
486
501
  } catch (error) { return { status: "deferred", message: failure(error).message }; }
487
- finally { lock?.release(); }
502
+ finally { selectionWrite.exit(); lock?.release(); }
488
503
  }
489
504
  export function uninstallUnixCodexShim(): { removed: boolean; message: string } {
505
+ // Same selection gate: removal mutates the same state the update worker
506
+ // re-observes in its commit window, so a held gate reports busy unchanged.
507
+ const selectionWrite = beginCodexCliSelectionParentWrite();
508
+ if (!selectionWrite.entered) return { removed: false, message: new CodexCliSelectionMutationBusyError().message };
490
509
  let lock: ReturnType<typeof tryAcquireShimRestoreLock> = null;
491
510
  try {
492
511
  const check = namespace(false);
@@ -522,5 +541,5 @@ export function uninstallUnixCodexShim(): { removed: boolean; message: string }
522
541
  if (!removePinned(statePath(), stateFile)) throw new Error("Concurrent Codex state replacement preserved");
523
542
  return { removed: true, message: "Codex PATH shim removed. Native Codex launcher was preserved. Remove the codex-shell-env source line from your shell startup file." };
524
543
  } catch (error) { return { removed: false, message: failure(error).message }; }
525
- finally { lock?.release(); }
544
+ finally { selectionWrite.exit(); lock?.release(); }
526
545
  }
@@ -35,7 +35,10 @@ const CODEX_SHIM_REENTRY_DIAGNOSTIC = "opencodex: saved Codex launcher resolved
35
35
  */
36
36
  export const CODEX_SHIM_ENSURE_FAILED_DIAGNOSTIC = "opencodex: proxy autostart failed; launching Codex anyway. Run 'ocx doctor' for details, or 'ocx restore' to hand Codex back to its own account.";
37
37
 
38
- const CODEX_INTERNAL_COMMANDS = [
38
+ // Shared with launchers that speak the same argv vocabulary (`ocx codex`): the
39
+ // generated shell templates inline this grammar, so the sets are the single
40
+ // source and the shell text is the consumer, not the definition.
41
+ export const CODEX_INTERNAL_COMMANDS = [
39
42
  "app-server",
40
43
  "archive",
41
44
  "apply",
@@ -60,7 +63,7 @@ const CODEX_INTERNAL_COMMANDS = [
60
63
  // Codex accepts global options before a subcommand. The shim must skip the value belonging to
61
64
  // these options before it decides which first positional token is the real subcommand. Keep this
62
65
  // list aligned with `codex --help`; `--option=value` and attached short forms stay one token.
63
- const CODEX_GLOBAL_OPTIONS_WITH_VALUE = [
66
+ export const CODEX_GLOBAL_OPTIONS_WITH_VALUE = [
64
67
  "-c", "--config",
65
68
  "--enable", "--disable",
66
69
  "--remote", "--remote-auth-token-env",