@bitkyc08/opencodex 2.91.0 → 2.93.0-preview.20261027

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 (360) hide show
  1. package/bin/ocx.mjs +47 -8
  2. package/gui/dist/assets/App-CJZoq-uF.js +58 -0
  3. package/gui/dist/assets/{Tray-BuLy7hL1.js → Tray-BWQPcgZn.js} +1 -1
  4. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  5. package/gui/dist/assets/index-Xfct8owH.js +94 -0
  6. package/gui/dist/assets/quota-summary-DxToX1rV.js +1 -0
  7. package/gui/dist/index.html +2 -2
  8. package/gui/dist/provider-icons/workbuddy-color.svg +29 -0
  9. package/package.json +8 -7
  10. package/src/adapters/anthropic.ts +28 -5
  11. package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
  12. package/src/adapters/coding-agent/profile.ts +54 -16
  13. package/src/adapters/coding-agent/turn.ts +30 -2
  14. package/src/adapters/command-code.ts +114 -7
  15. package/src/adapters/cursor/native-exec-fs.ts +11 -9
  16. package/src/adapters/devin/live-models.ts +4 -0
  17. package/src/adapters/google-vertex-endpoint.ts +9 -1
  18. package/src/adapters/google-vertex-key-project.ts +223 -0
  19. package/src/adapters/google-wire-compiler.ts +1 -2
  20. package/src/adapters/google.ts +13 -3
  21. package/src/adapters/kiro/reasoning.ts +2 -0
  22. package/src/adapters/kiro-refusal.ts +6 -1
  23. package/src/adapters/kiro-wire.ts +1 -1
  24. package/src/adapters/openai-chat/messages.ts +8 -2
  25. package/src/adapters/openai-chat/passthrough.ts +35 -14
  26. package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
  27. package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
  28. package/src/adapters/openai-chat/required-tool-result.ts +64 -0
  29. package/src/adapters/openai-chat/tool-name-registry.ts +3 -1
  30. package/src/adapters/openai-chat.ts +9 -10
  31. package/src/adapters/openai-responses/passthrough.ts +7 -4
  32. package/src/adapters/openai-responses/reasoning.ts +13 -0
  33. package/src/adapters/openai-responses/request-strips.ts +60 -0
  34. package/src/adapters/qoder/adapter.ts +129 -8
  35. package/src/adapters/qoder/scaffold-guard.ts +5 -0
  36. package/src/adapters/reasoning-controls.ts +16 -0
  37. package/src/adapters/registry.ts +5 -0
  38. package/src/adapters/tool-call-id.ts +1 -3
  39. package/src/adapters/workbuddy-schema.ts +61 -0
  40. package/src/adapters/workbuddy.ts +68 -0
  41. package/src/bridge/errors.ts +27 -0
  42. package/src/bridge/response-json.ts +1 -1
  43. package/src/bridge/sse.ts +1 -1
  44. package/src/bridge.ts +1 -1
  45. package/src/chat/inbound.ts +4 -1
  46. package/src/chat/outbound.ts +20 -6
  47. package/src/chat/reasoning-details.ts +28 -5
  48. package/src/claude/desktop-first-party.ts +54 -4
  49. package/src/claude/desktop-picker.ts +11 -8
  50. package/src/claude/first-party-settings.ts +3 -1
  51. package/src/claude/inbound.ts +2 -1
  52. package/src/claude/intercept/local-ca.ts +2 -1
  53. package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
  54. package/src/claude/intercept/picker-ca-startup.ts +3 -1
  55. package/src/claude/intercept/picker-models.ts +6 -3
  56. package/src/claude/intercept/picker-runtime.ts +3 -2
  57. package/src/claude/intercept/runtime.ts +6 -3
  58. package/src/claude/model-info.ts +31 -8
  59. package/src/cli/account-api.ts +11 -0
  60. package/src/cli/capabilities-agents-routing.ts +3 -3
  61. package/src/cli/capabilities-base.ts +7 -1
  62. package/src/cli/capabilities-observe-system.ts +10 -0
  63. package/src/cli/claude-desktop.ts +9 -8
  64. package/src/cli/claude.ts +3 -2
  65. package/src/cli/codex-cli-update.ts +8 -0
  66. package/src/cli/codex-shim-autorestore.ts +9 -0
  67. package/src/cli/combo-result.ts +13 -0
  68. package/src/cli/combo-stats.ts +3 -0
  69. package/src/cli/combo.ts +83 -41
  70. package/src/cli/cross-home-owner.ts +13 -1
  71. package/src/cli/dispatch.ts +25 -6
  72. package/src/cli/ensure-desired-integrations.ts +8 -6
  73. package/src/cli/export-command.ts +4 -1
  74. package/src/cli/help.ts +2 -1
  75. package/src/cli/index.ts +45 -45
  76. package/src/cli/integration-plan-dto.ts +4 -0
  77. package/src/cli/launcher-context.ts +49 -2
  78. package/src/cli/link.ts +45 -32
  79. package/src/cli/opencode.ts +20 -9
  80. package/src/cli/provider.ts +2 -1
  81. package/src/cli/registry.ts +6 -4
  82. package/src/cli/root.ts +9 -0
  83. package/src/cli/status.ts +59 -1
  84. package/src/cli/stop-restore.ts +113 -0
  85. package/src/cli/sync-expectation.ts +60 -0
  86. package/src/cli/uninstall-integrations.ts +41 -7
  87. package/src/cli/usage-compare.ts +68 -12
  88. package/src/client/connect.ts +40 -3
  89. package/src/client/link-home.ts +10 -1
  90. package/src/client/link-ingress.ts +1 -1
  91. package/src/client/link-readiness.ts +97 -0
  92. package/src/client/link-relay-transport.ts +79 -11
  93. package/src/client/link-relay.ts +74 -15
  94. package/src/client/link-tunnel.ts +45 -18
  95. package/src/client/machine-api.ts +3 -1
  96. package/src/client/machine-listener.ts +20 -2
  97. package/src/client/runtime.ts +20 -2
  98. package/src/client/sync-expectation.ts +118 -0
  99. package/src/clients/config-export/agent-clients.ts +96 -0
  100. package/src/clients/config-export/contracts.ts +25 -7
  101. package/src/clients/config-export/qoder.ts +38 -23
  102. package/src/clients/config-export/reasoning-metadata.ts +55 -8
  103. package/src/clients/config-export.ts +12 -0
  104. package/src/clients/lazycodex.ts +7 -2
  105. package/src/clients/reasoning-controls.ts +49 -0
  106. package/src/codex/account-store.ts +17 -3
  107. package/src/codex/app-server-restart-service.ts +6 -5
  108. package/src/codex/auth-api/account-identity.ts +14 -0
  109. package/src/codex/auth-api/account-list.ts +29 -2
  110. package/src/codex/auth-api/http.ts +13 -0
  111. package/src/codex/auth-api/main-account-probe.ts +2 -2
  112. package/src/codex/auth-api/pool-mode-gate.ts +16 -3
  113. package/src/codex/auth-api/pool-quota-probe.ts +15 -0
  114. package/src/codex/auth-context.ts +15 -12
  115. package/src/codex/catalog/build-entries.ts +22 -0
  116. package/src/codex/catalog/configured-tiers.ts +70 -0
  117. package/src/codex/catalog/effort.ts +52 -11
  118. package/src/codex/catalog/gather-capture.ts +5 -2
  119. package/src/codex/catalog/heal-observation.ts +155 -13
  120. package/src/codex/catalog/metadata.ts +6 -0
  121. package/src/codex/catalog/model-hints.ts +60 -11
  122. package/src/codex/catalog/model-visibility.ts +3 -2
  123. package/src/codex/catalog/native-models.ts +18 -3
  124. package/src/codex/catalog/parsing.ts +10 -8
  125. package/src/codex/catalog/pinned-models.ts +2 -1
  126. package/src/codex/catalog/provider-models.ts +18 -13
  127. package/src/codex/catalog/retained-sync.ts +2 -1
  128. package/src/codex/catalog/routed-gather.ts +19 -20
  129. package/src/codex/catalog/write-audit.ts +3 -2
  130. package/src/codex/catalog-self-heal.ts +43 -23
  131. package/src/codex/chatgpt-refresh-failure.ts +6 -2
  132. package/src/codex/cli-install-provenance.ts +418 -0
  133. package/src/codex/cli-installation-targets.ts +5 -1
  134. package/src/codex/cli-update-plan.ts +43 -16
  135. package/src/codex/collision-identity.ts +30 -5
  136. package/src/codex/convergence.ts +4 -3
  137. package/src/codex/data/roster-pinned-models.json +177 -1
  138. package/src/codex/desired-state.ts +6 -1
  139. package/src/codex/desktop-app/picker-freshness.ts +10 -8
  140. package/src/codex/desktop-compatibility/installed-build.ts +88 -12
  141. package/src/codex/desktop-compatibility/runtime.ts +29 -5
  142. package/src/codex/desktop-compatibility/usage-activation.ts +2 -1
  143. package/src/codex/desktop-compatibility/usage-controller.ts +9 -1
  144. package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
  145. package/src/codex/inject/config-toml.ts +0 -18
  146. package/src/codex/inject/plan.ts +18 -3
  147. package/src/codex/inject/remove.ts +6 -2
  148. package/src/codex/inject.ts +1 -1
  149. package/src/codex/journal.ts +61 -1
  150. package/src/codex/model-entitlements.ts +1 -1
  151. package/src/codex/native-main-owner.ts +27 -1
  152. package/src/codex/native-profile-store.ts +2 -1
  153. package/src/codex/pool-credit-policy.ts +35 -1
  154. package/src/codex/pool-refresh-backoff.ts +3 -1
  155. package/src/codex/quota-types.ts +3 -0
  156. package/src/codex/quota.ts +24 -4
  157. package/src/codex/role-auto-assign.ts +6 -2
  158. package/src/codex/subagent-defaults.ts +49 -4
  159. package/src/codex/user-identity.ts +35 -6
  160. package/src/codex/windows-current-sid.ts +162 -0
  161. package/src/combos/failover.ts +17 -2
  162. package/src/combos/jev-decision-contract.ts +22 -1
  163. package/src/combos/jev-quota-activation.ts +5 -1
  164. package/src/combos/jev-quota-route.ts +1 -1
  165. package/src/combos/jev-quota.ts +9 -1
  166. package/src/combos/jev-service-exchange.ts +3 -1
  167. package/src/combos/jev-session-pin-config.ts +51 -0
  168. package/src/combos/jev.ts +101 -9
  169. package/src/combos/resolve.ts +45 -1
  170. package/src/combos/types.ts +43 -0
  171. package/src/config/load-degrade.ts +5 -0
  172. package/src/config/paths.ts +19 -3
  173. package/src/config/pending-teardown.ts +22 -1
  174. package/src/config/provider-validation.ts +22 -4
  175. package/src/config/removed-opencode-free.ts +11 -0
  176. package/src/config/schema/leaf-validators.ts +6 -0
  177. package/src/generated/compatibility-version.json +467 -311
  178. package/src/generated/model-metadata.ts +5 -5
  179. package/src/images/loop.ts +16 -2
  180. package/src/integrations/catalog-refresh.ts +1 -1
  181. package/src/integrations/hermes-profiles.ts +251 -0
  182. package/src/integrations/merge.ts +8 -0
  183. package/src/integrations/mutation-plan.ts +19 -4
  184. package/src/integrations/registry.ts +5 -0
  185. package/src/integrations/state.ts +36 -1
  186. package/src/integrations/writer.ts +18 -4
  187. package/src/lib/bun-path-runtime.mjs +2 -1
  188. package/src/lib/decision-quota-sink.ts +10 -0
  189. package/src/lib/errors.ts +62 -0
  190. package/src/lib/eventstream-decoder.ts +81 -37
  191. package/src/lib/opaque-proxy-tunnel.ts +32 -8
  192. package/src/lib/pinned-http.ts +35 -2
  193. package/src/lib/process-control.ts +13 -1
  194. package/src/lib/socks5-fetch.ts +59 -64
  195. package/src/lib/socks5-upload-waiter.ts +50 -0
  196. package/src/lib/sse-decoder.ts +7 -2
  197. package/src/lib/state-store-sweeper.ts +40 -14
  198. package/src/lib/translator-budget.ts +4 -4
  199. package/src/lib/upstream-retry.ts +4 -1
  200. package/src/lib/windows-native-principal-worker.ts +14 -0
  201. package/src/lib/windows-native-principal.ts +188 -0
  202. package/src/lib/windows-secret-acl.ts +39 -3
  203. package/src/lib/windows-user-principal.ts +62 -18
  204. package/src/link/diagnostics.ts +193 -0
  205. package/src/link/relay-auth.ts +6 -0
  206. package/src/link/ssh-config.ts +35 -3
  207. package/src/link/status-projection.ts +39 -0
  208. package/src/link/supervisor.ts +45 -12
  209. package/src/link/tunnel-history.ts +109 -0
  210. package/src/link/tunnel-state.ts +80 -17
  211. package/src/messaging/remote-files.ts +24 -1
  212. package/src/oauth/generic-account-failover.ts +91 -7
  213. package/src/oauth/index.ts +15 -0
  214. package/src/oauth/model-discovery-auth.ts +5 -0
  215. package/src/oauth/store.ts +4 -1
  216. package/src/oauth/token-guardian.ts +7 -0
  217. package/src/oauth/types.ts +9 -0
  218. package/src/oauth/workbuddy.ts +139 -0
  219. package/src/providers/account-quota-disk.ts +12 -4
  220. package/src/providers/antigravity-quota-identity.ts +37 -0
  221. package/src/providers/base-url-choices.ts +8 -5
  222. package/src/providers/codebuddy-models.ts +6 -0
  223. package/src/providers/codex-capacity.ts +3 -1
  224. package/src/providers/derive.ts +51 -3
  225. package/src/providers/kiro-models.ts +3 -0
  226. package/src/providers/mimo-thinking.ts +12 -0
  227. package/src/providers/model-discovery.ts +2 -0
  228. package/src/providers/model-rename-fields.ts +2 -0
  229. package/src/providers/model-rename-migration.ts +10 -0
  230. package/src/providers/openai-sidecar-credit.ts +2 -2
  231. package/src/providers/quota/account-cache.ts +3 -2
  232. package/src/providers/quota/antigravity.ts +25 -14
  233. package/src/providers/quota/report-cache.ts +13 -4
  234. package/src/providers/quota/vendor-probes-key.ts +60 -0
  235. package/src/providers/quota/workbuddy.ts +83 -0
  236. package/src/providers/quota-decision-antigravity.ts +64 -0
  237. package/src/providers/quota-decision-publication.ts +11 -0
  238. package/src/providers/quota-decision-snapshot.ts +21 -4
  239. package/src/providers/quota-types.ts +2 -0
  240. package/src/providers/quota.ts +3 -1
  241. package/src/providers/reasoning-capabilities.ts +76 -0
  242. package/src/providers/registry/entries-core.ts +23 -12
  243. package/src/providers/registry/entries-extended.ts +83 -27
  244. package/src/providers/registry/model-ids.ts +5 -0
  245. package/src/providers/registry/model-seeds.ts +120 -56
  246. package/src/providers/registry/types.ts +29 -2
  247. package/src/providers/resolved-model-policy.ts +30 -10
  248. package/src/providers/routed-config.ts +24 -1
  249. package/src/providers/stale-model-roster-migration.ts +123 -18
  250. package/src/providers/workbuddy-credit-balance.ts +81 -0
  251. package/src/providers/workbuddy-models.ts +37 -0
  252. package/src/providers/workbuddy.ts +60 -0
  253. package/src/remote-control/workspace-pi-runtime.ts +11 -6
  254. package/src/responses/compaction-summary.ts +45 -0
  255. package/src/responses/muse-tool-name-alias.ts +1 -2
  256. package/src/responses/parser.ts +3 -2
  257. package/src/responses/reasoning-replay-cache.ts +18 -14
  258. package/src/responses/schema.ts +1 -0
  259. package/src/responses/thought-signature-replay.ts +10 -2
  260. package/src/router.ts +2 -0
  261. package/src/routing/analytics.ts +2 -3
  262. package/src/routing/capability.ts +8 -2
  263. package/src/routing/fallback-policy.ts +3 -3
  264. package/src/routing/history/ingest.ts +28 -3
  265. package/src/server/auth-cors.ts +4 -2
  266. package/src/server/chat-completions.ts +21 -1
  267. package/src/server/chat-native-eligibility.ts +7 -0
  268. package/src/server/chat-native-reasoning.ts +24 -7
  269. package/src/server/chat-native.ts +13 -2
  270. package/src/server/claude-messages.ts +3 -0
  271. package/src/server/direct-local-http.ts +5 -2
  272. package/src/server/effort-policy.ts +5 -1
  273. package/src/server/index/link-relay-sessions.ts +9 -5
  274. package/src/server/index/live-sideband.ts +18 -15
  275. package/src/server/index/optional-listeners.ts +4 -0
  276. package/src/server/index/serve-options.ts +5 -4
  277. package/src/server/local-management-read-client.ts +3 -1
  278. package/src/server/management/agent-settings-routes.ts +27 -15
  279. package/src/server/management/combo-routes.ts +14 -4
  280. package/src/server/management/config-routes.ts +2 -2
  281. package/src/server/management/decision-discovery.ts +12 -2
  282. package/src/server/management/hermes-profile-routes.ts +156 -0
  283. package/src/server/management/integration-routes.ts +85 -24
  284. package/src/server/management/link-routes.ts +5 -2
  285. package/src/server/management/model-routes.ts +2 -2
  286. package/src/server/management/model-row-export-metadata.ts +25 -6
  287. package/src/server/management/model-rows.ts +15 -20
  288. package/src/server/management/native-integration-routes.ts +11 -8
  289. package/src/server/management/provider-routes.ts +1 -1
  290. package/src/server/management/route-registry.ts +4 -0
  291. package/src/server/management-api.ts +5 -0
  292. package/src/server/models-capabilities.ts +21 -3
  293. package/src/server/port-reclaim.ts +51 -9
  294. package/src/server/request-log-conversation.ts +49 -0
  295. package/src/server/request-log.ts +2 -0
  296. package/src/server/responses/adapter-delivery.ts +11 -1
  297. package/src/server/responses/adapter-dispatch.ts +2 -2
  298. package/src/server/responses/anthropic-thinking-recovery.ts +1 -0
  299. package/src/server/responses/codex-ws-exchange.ts +39 -9
  300. package/src/server/responses/codex-ws-session.ts +38 -4
  301. package/src/server/responses/codex-ws-wire.ts +6 -1
  302. package/src/server/responses/combo-required-tool-contract.ts +103 -0
  303. package/src/server/responses/combo-stream-preflight.ts +8 -1
  304. package/src/server/responses/compact.ts +14 -5
  305. package/src/server/responses/context-overflow.ts +8 -1
  306. package/src/server/responses/core-combo-failure.ts +10 -0
  307. package/src/server/responses/core-combo.ts +74 -44
  308. package/src/server/responses/core-lifetime.ts +5 -2
  309. package/src/server/responses/core-normalize.ts +17 -4
  310. package/src/server/responses/core-opaque-recovery.ts +1 -0
  311. package/src/server/responses/core-options.ts +7 -0
  312. package/src/server/responses/core-replay.ts +2 -1
  313. package/src/server/responses/jev-combo-choice.ts +39 -0
  314. package/src/server/responses/jev-session-pin.ts +203 -0
  315. package/src/server/responses/main-hard-lock-routing.ts +60 -44
  316. package/src/server/responses/passthrough-delivery.ts +44 -2
  317. package/src/server/responses/policy-fallback.ts +6 -1
  318. package/src/server/responses/request-compression.ts +12 -7
  319. package/src/server/responses/request-prepare.ts +32 -7
  320. package/src/server/responses/request-sidecar-auth.ts +2 -0
  321. package/src/server/responses/request-transport.ts +25 -6
  322. package/src/server/responses/response-effects.ts +22 -10
  323. package/src/server/responses/run-turn-execution.ts +2 -4
  324. package/src/server/responses/sidecar-execution.ts +13 -7
  325. package/src/server/responses-phase-inference.ts +267 -0
  326. package/src/server/sse-payload-rewrite.ts +14 -1
  327. package/src/server/stop-teardown.ts +36 -1
  328. package/src/server/ws-bridge.ts +1 -1
  329. package/src/service/definition.ts +20 -8
  330. package/src/service/desktop-supervision.d.mts +7 -4
  331. package/src/service/desktop-supervision.mjs +90 -13
  332. package/src/service/ownership-mutation-lease.mjs +21 -7
  333. package/src/types/config.ts +14 -2
  334. package/src/types/provider.ts +29 -7
  335. package/src/types/request.ts +11 -0
  336. package/src/types/wire.ts +1 -0
  337. package/src/types.ts +1 -0
  338. package/src/update/bind-probe.ts +29 -0
  339. package/src/update/codex-cli-update-launch-policy.d.mts +9 -0
  340. package/src/update/codex-cli-update-launch-policy.mjs +30 -0
  341. package/src/update/job.ts +10 -29
  342. package/src/update/npm-install-job.ps1 +173 -0
  343. package/src/update/npm-install.mjs +70 -0
  344. package/src/update/stop-contract.d.mts +1 -0
  345. package/src/update/stop-contract.mjs +14 -0
  346. package/src/update/stop-decision.d.mts +1 -1
  347. package/src/update/stop-decision.mjs +13 -3
  348. package/src/update/teardown-handover.ts +166 -0
  349. package/src/update/transactional-install.d.mts +14 -3
  350. package/src/update/transactional-install.mjs +33 -7
  351. package/src/usage/expected-prices.ts +64 -31
  352. package/src/usage/jev-stats.ts +54 -14
  353. package/src/usage/timeline.ts +19 -9
  354. package/src/vision/eligibility.ts +15 -5
  355. package/src/vision/plan.ts +2 -2
  356. package/src/web-search/loop.ts +16 -2
  357. package/gui/dist/assets/App-nZ34cR5G.js +0 -58
  358. package/gui/dist/assets/index-DGXS51sp.js +0 -94
  359. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
  360. package/gui/dist/assets/quota-summary-DO1Sx5TM.js +0 -1
@@ -0,0 +1,173 @@
1
+ # ASCII-only Windows PowerShell 5.1 supervisor. Arguments arrive as JSON on stdin.
2
+ # The child is born in our private job; no installer can outlive its supervisor.
3
+ $ErrorActionPreference = 'Stop'
4
+ $utf8 = New-Object System.Text.UTF8Encoding($false, $true)
5
+ $reader = New-Object System.IO.StreamReader([Console]::OpenStandardInput(), $utf8, $false)
6
+ $request = $reader.ReadToEnd() | ConvertFrom-Json
7
+ Add-Type -TypeDefinition @'
8
+ using System;
9
+ using System.ComponentModel;
10
+ using System.Diagnostics;
11
+ using System.Runtime.InteropServices;
12
+ using System.Text;
13
+ using System.Threading;
14
+
15
+ public static class NpmInstallJob {
16
+ [StructLayout(LayoutKind.Sequential)] struct Startup {
17
+ public int cb; public IntPtr reserved, desktop, title;
18
+ public int x, y, width, height, charsX, charsY, fill, flags;
19
+ public short show, reservedSize; public IntPtr reservedData, stdin, stdout, stderr;
20
+ }
21
+ [StructLayout(LayoutKind.Sequential)] struct ProcessInfo {
22
+ public IntPtr process, thread; public uint pid, tid;
23
+ }
24
+ [StructLayout(LayoutKind.Sequential)] struct StartupEx {
25
+ public Startup startup; public IntPtr attributes;
26
+ }
27
+ [StructLayout(LayoutKind.Sequential)] struct Limits {
28
+ public long processTime, jobTime; public uint flags;
29
+ public UIntPtr minWorkingSet, maxWorkingSet; public uint activeLimit;
30
+ public UIntPtr affinity; public uint priority, scheduling;
31
+ }
32
+ [StructLayout(LayoutKind.Sequential)] struct ExtendedLimits {
33
+ public Limits basic;
34
+ public ulong readOps, writeOps, otherOps, readBytes, writeBytes, otherBytes;
35
+ public UIntPtr processMemory, jobMemory, peakProcessMemory, peakJobMemory;
36
+ }
37
+ [StructLayout(LayoutKind.Sequential)] struct Accounting {
38
+ public long userTime, kernelTime, periodUserTime, periodKernelTime;
39
+ public uint faults, total, active, terminated;
40
+ }
41
+ public sealed class Result {
42
+ public object status; public bool processTreeExited; public object error;
43
+ }
44
+ public sealed class InstallError {
45
+ public string code, message;
46
+ public InstallError(string c, string m) { code = c; message = m; }
47
+ }
48
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
49
+ static extern IntPtr CreateJobObject(IntPtr attributes, string name);
50
+ [DllImport("kernel32.dll", SetLastError=true)]
51
+ static extern bool SetInformationJobObject(IntPtr job, int info, ref ExtendedLimits limits, uint size);
52
+ [DllImport("kernel32.dll", SetLastError=true)]
53
+ static extern bool QueryInformationJobObject(IntPtr job, int info, out Accounting data, uint size, IntPtr returned);
54
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
55
+ static extern bool CreateProcess(string file, StringBuilder args, IntPtr pa, IntPtr ta, bool inherit, uint flags,
56
+ IntPtr environment, string cwd, ref StartupEx startup, out ProcessInfo process);
57
+ [DllImport("kernel32.dll", SetLastError=true)]
58
+ static extern bool InitializeProcThreadAttributeList(IntPtr list, int count, uint flags, ref IntPtr size);
59
+ [DllImport("kernel32.dll", SetLastError=true)]
60
+ static extern bool UpdateProcThreadAttribute(IntPtr list, uint flags, IntPtr attribute, IntPtr value,
61
+ IntPtr size, IntPtr previous, IntPtr returned);
62
+ [DllImport("kernel32.dll")] static extern void DeleteProcThreadAttributeList(IntPtr list);
63
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateJobObject(IntPtr job, uint code);
64
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint ResumeThread(IntPtr thread);
65
+ [DllImport("kernel32.dll")] static extern uint WaitForSingleObject(IntPtr handle, uint ms);
66
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
67
+ [DllImport("kernel32.dll")] static extern IntPtr GetStdHandle(int number);
68
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetHandleInformation(IntPtr handle, uint mask, uint flags);
69
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
70
+ static void Require(bool ok) { if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error()); }
71
+ static void RequireAttribute(bool ok) {
72
+ if (!ok) {
73
+ int code = Marshal.GetLastWin32Error();
74
+ throw new Win32Exception(code,
75
+ "Atomic npm supervision requires Windows 10 or later with Job List and handle-list process attributes; installer was not started: "
76
+ + new Win32Exception(code).Message);
77
+ }
78
+ }
79
+ static uint Active(IntPtr job) {
80
+ Accounting data;
81
+ Require(QueryInformationJobObject(job, 1, out data, (uint)Marshal.SizeOf(typeof(Accounting)), IntPtr.Zero));
82
+ return data.active;
83
+ }
84
+ public static Result Run(string file, string args, string cwd, int timeoutMs, int joinMs) {
85
+ IntPtr job = IntPtr.Zero, attributes = IntPtr.Zero, jobList = IntPtr.Zero, handles = IntPtr.Zero;
86
+ ProcessInfo process = new ProcessInfo();
87
+ bool started = false, attributesInitialized = false, timedOut = false;
88
+ Result result = new Result { status = null, processTreeExited = true };
89
+ try {
90
+ job = CreateJobObject(IntPtr.Zero, null); Require(job != IntPtr.Zero);
91
+ ExtendedLimits limits = new ExtendedLimits();
92
+ limits.basic.flags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; no breakaway.
93
+ Require(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(ExtendedLimits))));
94
+ StartupEx startup = new StartupEx(); startup.startup.cb = Marshal.SizeOf(typeof(StartupEx)); startup.startup.flags = 0x100;
95
+ startup.startup.stdin = GetStdHandle(-10);
96
+ // Keep stdout exclusively for the one supervisor result. npm logs inherit stderr.
97
+ startup.startup.stdout = startup.startup.stderr = GetStdHandle(-12);
98
+ Require(SetHandleInformation(startup.startup.stdin, 1, 1));
99
+ Require(SetHandleInformation(startup.startup.stderr, 1, 1));
100
+ Require(SetHandleInformation(GetStdHandle(-11), 1, 0)); // Result pipe is supervisor-only.
101
+ IntPtr size = IntPtr.Zero;
102
+ InitializeProcThreadAttributeList(IntPtr.Zero, 2, 0, ref size);
103
+ RequireAttribute(size != IntPtr.Zero);
104
+ attributes = Marshal.AllocHGlobal(size);
105
+ RequireAttribute(InitializeProcThreadAttributeList(attributes, 2, 0, ref size));
106
+ attributesInitialized = true; startup.attributes = attributes;
107
+ jobList = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(jobList, job);
108
+ // PROC_THREAD_ATTRIBUTE_JOB_LIST: membership is atomic with creation (Windows 10+).
109
+ RequireAttribute(UpdateProcThreadAttribute(attributes, 0, new IntPtr(0x0002000D), jobList,
110
+ new IntPtr(IntPtr.Size), IntPtr.Zero, IntPtr.Zero));
111
+ handles = Marshal.AllocHGlobal(2 * IntPtr.Size);
112
+ Marshal.WriteIntPtr(handles, 0, startup.startup.stdin);
113
+ Marshal.WriteIntPtr(handles, IntPtr.Size, startup.startup.stderr);
114
+ // PROC_THREAD_ATTRIBUTE_HANDLE_LIST: never inherit the Job or result pipe.
115
+ RequireAttribute(UpdateProcThreadAttribute(attributes, 0, new IntPtr(0x00020002), handles,
116
+ new IntPtr(2 * IntPtr.Size), IntPtr.Zero, IntPtr.Zero));
117
+ // Fail closed on unsupported attributes/creation: never retry without the Job list.
118
+ RequireAttribute(CreateProcess(file, new StringBuilder(args), IntPtr.Zero, IntPtr.Zero, true,
119
+ 0x08080004, IntPtr.Zero, cwd, ref startup, out process)); // NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT | SUSPENDED
120
+ started = true; result.processTreeExited = false;
121
+ // Keep suspension until local exit-proof/error handling is armed.
122
+ Require(ResumeThread(process.thread) != UInt32.MaxValue);
123
+ Stopwatch clock = Stopwatch.StartNew();
124
+ while (Active(job) != 0 && clock.ElapsedMilliseconds < timeoutMs) Thread.Sleep(20);
125
+ if (Active(job) != 0) {
126
+ timedOut = true;
127
+ result.error = new InstallError("ETIMEDOUT", "npm install exceeded " + timeoutMs + " ms");
128
+ Require(TerminateJobObject(job, 1));
129
+ clock.Restart();
130
+ while (Active(job) != 0 && clock.ElapsedMilliseconds < joinMs) Thread.Sleep(10);
131
+ } else clock.Restart();
132
+ uint remainingJoinMs = (uint)Math.Max(0L, joinMs - clock.ElapsedMilliseconds);
133
+ result.processTreeExited = Active(job) == 0 && WaitForSingleObject(process.process, remainingJoinMs) == 0;
134
+ if (result.processTreeExited && result.error == null) {
135
+ uint code; Require(GetExitCodeProcess(process.process, out code)); result.status = (long)code;
136
+ } else if (!result.processTreeExited) {
137
+ result.error = new InstallError(timedOut ? "ETIMEDOUT" : "EINSTALLJOIN",
138
+ (timedOut ? "npm install exceeded " + timeoutMs + " ms; " : "") + "process-tree exit could not be confirmed; stage retained");
139
+ }
140
+ } catch (Exception error) {
141
+ if (started) {
142
+ TerminateJobObject(job, 1);
143
+ Stopwatch clock = Stopwatch.StartNew();
144
+ while (clock.ElapsedMilliseconds < joinMs) {
145
+ try {
146
+ if (WaitForSingleObject(process.process, 0) == 0 && Active(job) == 0) {
147
+ result.processTreeExited = true; break;
148
+ }
149
+ } catch { break; }
150
+ Thread.Sleep(10);
151
+ }
152
+ }
153
+ InstallError timeout = result.error as InstallError;
154
+ result.error = new InstallError(timeout == null ? "EINSTALLJOIN" : timeout.code,
155
+ (timeout == null ? "" : timeout.message + "; ") + "npm supervision failed: " + error.Message);
156
+ } finally {
157
+ if (attributesInitialized) DeleteProcThreadAttributeList(attributes);
158
+ if (attributes != IntPtr.Zero) Marshal.FreeHGlobal(attributes);
159
+ if (handles != IntPtr.Zero) Marshal.FreeHGlobal(handles);
160
+ if (jobList != IntPtr.Zero) Marshal.FreeHGlobal(jobList);
161
+ if (process.thread != IntPtr.Zero) CloseHandle(process.thread);
162
+ if (process.process != IntPtr.Zero) CloseHandle(process.process);
163
+ if (job != IntPtr.Zero) CloseHandle(job);
164
+ }
165
+ return result;
166
+ }
167
+ }
168
+ '@
169
+ $result = [NpmInstallJob]::Run([string]$request.file, [string]$request.commandLine, [string]$request.cwd,
170
+ [int]$request.timeoutMs, [int]$request.joinMs) | ConvertTo-Json -Compress -Depth 4
171
+ $writer = New-Object System.IO.StreamWriter([Console]::OpenStandardOutput(), $utf8)
172
+ $writer.Write($result)
173
+ $writer.Flush()
@@ -0,0 +1,70 @@
1
+ // Windows Node-launcher compatibility code. The install owns its entire process tree until
2
+ // exit is proved; a timeout signal alone never authorizes stage removal.
3
+ import { spawn } from "node:child_process";
4
+ import { dirname, join, win32 } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const JOIN_MS = 10000;
8
+ const failure = message => ({ status: null, processTreeExited: false, error: { code: "EINSTALLJOIN", message } });
9
+
10
+ function quoteWindowsArg(value) {
11
+ return '"' + value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1") + '"';
12
+ }
13
+
14
+ export async function runNpmInstall(invocation, { env = process.env, timeoutMs = 180000 } = {}) {
15
+ if (!invocation) return { status: 1, processTreeExited: true, error: { code: "ENOENT", message: "npm invocation unavailable" } };
16
+ if (process.platform === "win32") {
17
+ // Resolve from the same absolute system directory as the hardened cmd hop.
18
+ // Never search PATH for PowerShell, and never interpolate the JSON as code.
19
+ const roots = new Set(Object.entries(env).filter(([key, value]) => key.toLowerCase() === "systemroot" && value !== undefined).map(([, value]) => value));
20
+ const root = env.SystemRoot ?? (roots.size === 1 ? [...roots][0] : undefined);
21
+ if (!root || !win32.isAbsolute(root)) return failure("absolute SystemRoot is required for npm process supervision");
22
+ const supervisor = win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
23
+ const helper = join(dirname(fileURLToPath(import.meta.url)), "npm-install-job.ps1");
24
+ return new Promise(resolve => {
25
+ const child = spawn(supervisor, ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", helper], {
26
+ env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"],
27
+ });
28
+ let output = "";
29
+ let invalid = false;
30
+ let spawned = false;
31
+ let completed = false;
32
+ const complete = result => {
33
+ if (completed) return;
34
+ completed = true;
35
+ clearTimeout(watchdog);
36
+ child.stdin.destroy(); child.stdout.destroy(); child.stderr.destroy();
37
+ resolve(result);
38
+ };
39
+ const watchdog = setTimeout(() => {
40
+ child.kill();
41
+ complete(failure(`npm supervisor exceeded ${timeoutMs} ms install budget and exit-confirmation budget; stage retained`));
42
+ }, timeoutMs + JOIN_MS + 30000);
43
+ child.on("spawn", () => { spawned = true; });
44
+ child.stderr.on("data", chunk => { if (!completed) process.stderr.write(chunk); });
45
+ child.stdout.setEncoding("utf8");
46
+ child.stdout.on("data", chunk => {
47
+ if (output.length + chunk.length > 16384) { invalid = true; child.kill(); complete(failure("invalid npm supervisor output; stage retained")); }
48
+ else output += chunk.toString("utf8");
49
+ });
50
+ child.on("error", error => {
51
+ complete({ status: null, processTreeExited: !spawned, error: { code: error.code, message: error.message } });
52
+ });
53
+ child.on("close", status => {
54
+ clearTimeout(watchdog);
55
+ try {
56
+ const result = JSON.parse(output);
57
+ if (invalid || status !== 0 || typeof result.processTreeExited !== "boolean"
58
+ || !(result.status === null || Number.isInteger(result.status))) throw new Error("invalid supervisor result");
59
+ complete(result);
60
+ } catch { complete(failure("npm supervisor did not confirm process-tree exit; stage retained")); }
61
+ });
62
+ child.stdin.on("error", () => { /* close/result decides whether the helper ran */ });
63
+ const args = invocation.options?.windowsVerbatimArguments ? invocation.args.join(" ") : invocation.args.map(quoteWindowsArg).join(" ");
64
+ child.stdin.end(JSON.stringify({ file: invocation.file, commandLine: quoteWindowsArg(invocation.file) + " " + args,
65
+ cwd: process.cwd(), timeoutMs, joinMs: JOIN_MS }));
66
+ });
67
+ }
68
+
69
+ return failure("the npm Job Object supervisor is Windows-only");
70
+ }
@@ -1,3 +1,4 @@
1
1
  /** Declaration for the plain-ESM stop contract shared with `bin/ocx.mjs`. */
2
2
  export declare const STOP_HISTORY_INCOMPLETE_EXIT_CODE: 79;
3
3
  export declare const STOP_HISTORY_DEFERRED_EXIT_CODE: 80;
4
+ export declare const STOP_TEARDOWN_HANDED_OVER_EXIT_CODE: 81;
@@ -32,3 +32,17 @@ export const STOP_HISTORY_INCOMPLETE_EXIT_CODE = 79;
32
32
  * dispatcher already emit.
33
33
  */
34
34
  export const STOP_HISTORY_DEFERRED_EXIT_CODE = 80;
35
+
36
+ /**
37
+ * The exit code `ocx stop` uses to say "the proxy is down and its shared teardown was
38
+ * handed to the proxy this update is about to start" (#7423).
39
+ *
40
+ * Only an update that will restart the proxy asks for this. Restoring native Codex here
41
+ * replaced the routed catalog with the pristine one, and a Codex process that loaded it
42
+ * before the new proxy's first publication kept treating routed models as unknown until
43
+ * it was restarted. Like 80, the receipt stays outstanding, and the stop proved before
44
+ * choosing this code that it is the only obligation left; unlike 80, nothing refused the
45
+ * restore. The replacement discharges the receipt after it publishes, and a stop finishes
46
+ * it if no replacement ever starts.
47
+ */
48
+ export const STOP_TEARDOWN_HANDED_OVER_EXIT_CODE = 81;
@@ -6,5 +6,5 @@ export declare function decidePostStopUpdate(input: {
6
6
  teardownOutstanding?: boolean;
7
7
  }): {
8
8
  proceed: boolean;
9
- reason: "stop-failed" | "runtime-state" | "teardown-outstanding" | "proxy-live" | "proxy-unknown" | "history-only" | "history-deferred" | "ok";
9
+ reason: "stop-failed" | "runtime-state" | "teardown-outstanding" | "proxy-live" | "proxy-unknown" | "history-only" | "history-deferred" | "handed-over" | "ok";
10
10
  };
@@ -1,4 +1,8 @@
1
- import { STOP_HISTORY_DEFERRED_EXIT_CODE, STOP_HISTORY_INCOMPLETE_EXIT_CODE } from "./stop-contract.mjs";
1
+ import {
2
+ STOP_HISTORY_DEFERRED_EXIT_CODE,
3
+ STOP_HISTORY_INCOMPLETE_EXIT_CODE,
4
+ STOP_TEARDOWN_HANDED_OVER_EXIT_CODE,
5
+ } from "./stop-contract.mjs";
2
6
 
3
7
  /**
4
8
  * May an update replace package files after `ocx stop` returned?
@@ -29,15 +33,21 @@ import { STOP_HISTORY_DEFERRED_EXIT_CODE, STOP_HISTORY_INCOMPLETE_EXIT_CODE } fr
29
33
  * gate still applies: runtime records and a live or unreadable endpoint abort exactly
30
34
  * as they do for a clean stop, because package replacement under a live server is the
31
35
  * danger this function exists to prevent, and a history refusal says nothing about it.
36
+ * - `handed-over` — proceed; the stop is down and kept its receipt on purpose so the
37
+ * proxy this update restarts can take the routing over without a native gap (#7423).
38
+ * It is gated exactly like `history-deferred`: the child proved its receipt is the only
39
+ * obligation, and runtime records or a live or unreadable endpoint still abort.
32
40
  */
33
41
  export function decidePostStopUpdate({ status, hasRuntimeState, liveness, teardownOutstanding = false }) {
34
42
  const historyOnly = status === STOP_HISTORY_INCOMPLETE_EXIT_CODE;
35
43
  const historyDeferred = status === STOP_HISTORY_DEFERRED_EXIT_CODE;
36
- if (status !== 0 && !historyOnly && !historyDeferred) return { proceed: false, reason: "stop-failed" };
44
+ const handedOver = status === STOP_TEARDOWN_HANDED_OVER_EXIT_CODE;
45
+ if (status !== 0 && !historyOnly && !historyDeferred && !handedOver) return { proceed: false, reason: "stop-failed" };
37
46
  if (hasRuntimeState) return { proceed: false, reason: "runtime-state" };
38
- if (teardownOutstanding && !historyDeferred) return { proceed: false, reason: "teardown-outstanding" };
47
+ if (teardownOutstanding && !historyDeferred && !handedOver) return { proceed: false, reason: "teardown-outstanding" };
39
48
  if (liveness === "live") return { proceed: false, reason: "proxy-live" };
40
49
  if (liveness !== "dead") return { proceed: false, reason: "proxy-unknown" };
41
50
  if (historyDeferred) return { proceed: true, reason: "history-deferred" };
51
+ if (handedOver) return { proceed: true, reason: "handed-over" };
42
52
  return { proceed: true, reason: historyOnly ? "history-only" : "ok" };
43
53
  }
@@ -0,0 +1,166 @@
1
+ import {
2
+ clearPendingTeardown,
3
+ isPendingTeardownAbandoned,
4
+ listPendingTeardowns,
5
+ pendingTeardownPathFor,
6
+ pendingTeardownsAreExactly,
7
+ readPendingTeardown,
8
+ } from "../config/pending-teardown";
9
+ import { isLikelyOcxProcess } from "../config/process-state";
10
+ import { isProcessAlive } from "../lib/process-control";
11
+
12
+ /**
13
+ * Update teardown handover (#7423).
14
+ *
15
+ * An update stops the proxy before replacing the package. That stop used to restore native
16
+ * Codex, which puts the pristine catalog back and removes every routed row. The new proxy
17
+ * appends them again when it starts, but a Codex process that loads the catalog in between
18
+ * keeps treating routed models as unknown until it is restarted. On a long-context model
19
+ * that silent fallback metadata turned into a compaction loop.
20
+ *
21
+ * When the caller is going to restart the proxy, it sets this variable on the update
22
+ * child. The `ocx stop` that the update runs then keeps its teardown receipt instead of
23
+ * restoring, and the proxy that honours the deferral keeps its client config on exit.
24
+ * Ownership stays explicit: the receipt is the same durable obligation any deferred stop
25
+ * writes, so a replacement that never starts leaves it for the next `ocx stop` to finish.
26
+ *
27
+ * An ordinary `ocx stop` never sees the variable and still restores native routing.
28
+ */
29
+ export const UPDATE_TEARDOWN_HANDOVER_ENV = "OCX_UPDATE_TEARDOWN_HANDOVER";
30
+
31
+ /**
32
+ * `publishesOnStart` answers whether the restarted proxy will run its startup Codex sync.
33
+ * Without one it can never discharge the receipt, so the stop restores as usual; an
34
+ * unreadable answer is treated the same way.
35
+ */
36
+ export function updateTeardownHandoverRequested(
37
+ env: NodeJS.ProcessEnv = process.env,
38
+ publishesOnStart: () => boolean = () => true,
39
+ ): boolean {
40
+ if (env[UPDATE_TEARDOWN_HANDOVER_ENV] !== "1") return false;
41
+ try { return publishesOnStart(); } catch { return false; }
42
+ }
43
+
44
+ /** An identity-aware "is that stop still running", the rule handleStop uses for receipts. */
45
+ export function teardownOwnerStillRunning(pid: number): boolean {
46
+ return isProcessAlive(pid) && isLikelyOcxProcess(pid);
47
+ }
48
+
49
+ /**
50
+ * Is an update handover waiting for this starting proxy? True when a valid, exact handover
51
+ * receipt exists whose stop has exited: that stop kept Codex routing for the replacement.
52
+ */
53
+ export function updateTeardownHandoverPending(ownerStillRunning: (pid: number) => boolean = teardownOwnerStillRunning): boolean {
54
+ return listPendingTeardowns().some(read => read.state === "valid"
55
+ && read.receipt.handover === "update-restart" && read.receipt.endpointSource === "exact"
56
+ && isPendingTeardownAbandoned(read, ownerStillRunning));
57
+ }
58
+
59
+ /** The environment for an update child whose caller will restart the proxy afterwards. */
60
+ export function withUpdateTeardownHandover(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
61
+ return { ...env, [UPDATE_TEARDOWN_HANDOVER_ENV]: "1" };
62
+ }
63
+
64
+ /** The environment for an update child that must restore as usual, whatever this process inherited. */
65
+ export function withoutUpdateTeardownHandover(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
66
+ const child = { ...env };
67
+ delete child[UPDATE_TEARDOWN_HANDOVER_ENV];
68
+ return child;
69
+ }
70
+
71
+ /**
72
+ * Drop the marker from a starting proxy. The updater lanes pass their environment to the
73
+ * recovery and replacement starts they spawn; a proxy that kept it would hand it to every
74
+ * dashboard update worker it launches later, including ones that never restart.
75
+ */
76
+ export function forgetUpdateTeardownHandover(env: NodeJS.ProcessEnv = process.env): void {
77
+ delete env[UPDATE_TEARDOWN_HANDOVER_ENV];
78
+ }
79
+
80
+ /** The facts `ocx stop` has already settled when it reaches the shared restore. */
81
+ export type StopHandoverFacts = {
82
+ requested: boolean;
83
+ restoreBlocked: boolean;
84
+ nonce: string | undefined;
85
+ stopFailed: boolean;
86
+ recoveredCount: number;
87
+ proxy: string;
88
+ /** What the service-manager stop returned; a manager can take the proxy down itself. */
89
+ service?: string;
90
+ /**
91
+ * The proxy this run stopped answered `deferred` before exiting. Any fallback (a failed
92
+ * or unconfirmed /api/stop, then a signal) lets a standalone proxy's exit cleanup restore
93
+ * native Codex and the pristine catalog, so nothing is left to hand over.
94
+ */
95
+ deferralHonored?: boolean;
96
+ };
97
+
98
+ /**
99
+ * May this stop skip the restore and hand its teardown to the restarted proxy?
100
+ *
101
+ * Only when the update asked for it, this run's own receipt is the single obligation in
102
+ * the home, and the proxy it named is down: stopped by this run, or gone after a clean
103
+ * service-manager stop (a launchd/systemd/scheduler child exits with its manager, and its
104
+ * own exit cleanup keeps routing because it runs with OCX_SERVICE). A recovered or foreign
105
+ * receipt, a blocked restore or a stop that failed on the way all take the ordinary
106
+ * restore instead. The exclusivity check is what lets the updater treat the outstanding
107
+ * receipt as expected; the updater still probes the endpoint itself before replacing files.
108
+ */
109
+ export function stopHandsTeardownOver(facts: StopHandoverFacts): boolean {
110
+ const managerStopped = facts.service === "stopped" || facts.service === "stopped-respawnable";
111
+ const proxyDown = ((facts.proxy === "stopped" || facts.proxy === "stopped-orphan") && facts.deferralHonored === true)
112
+ || (facts.proxy === "not-running" && managerStopped);
113
+ return facts.requested && !facts.restoreBlocked && facts.nonce !== undefined && !facts.stopFailed
114
+ && facts.recoveredCount === 0 && proxyDown && pendingTeardownsAreExactly([facts.nonce])
115
+ && handoverReceiptIsRecoverable(facts.nonce);
116
+ }
117
+
118
+ /**
119
+ * A handed-over receipt must be one a later `ocx stop` can finish on its own if no
120
+ * replacement ever starts. A `guessed` endpoint fails closed into manual recovery there,
121
+ * so a stop that could only record the configured address restores instead.
122
+ */
123
+ function handoverReceiptIsRecoverable(nonce: string): boolean {
124
+ const read = readPendingTeardown(nonce);
125
+ return read.state === "valid" && read.receipt.endpointSource === "exact" && read.receipt.handover === "update-restart";
126
+ }
127
+
128
+ export function announceStopHandover(log: Pick<Console, "log"> = console): void {
129
+ log.log("↪️ Codex routing, its catalog and the Grok config stay in place for the updated proxy, which releases them after its first sync.");
130
+ log.log(" If it does not start, run 'ocx start' to take them over or 'ocx stop' to restore native Codex.");
131
+ }
132
+
133
+ /**
134
+ * Release handover receipts once this proxy has published its own routing.
135
+ *
136
+ * Called after a successful startup sync, when Codex config and catalog point at the
137
+ * running proxy again, so the restore the stop handed over is no longer owed. Only a
138
+ * handover receipt whose owning stop has exited is released: an ordinary deferred stop
139
+ * still has to run its own restore, and a stop that is still running owns its receipt.
140
+ */
141
+ export function dischargeUpdateTeardownHandovers(ownerStillRunning: (pid: number) => boolean): {
142
+ discharged: string[];
143
+ failed: string[];
144
+ } {
145
+ const discharged: string[] = [];
146
+ const failed: string[] = [];
147
+ for (const read of listPendingTeardowns()) {
148
+ if (read.state !== "valid" || read.receipt.handover !== "update-restart") continue;
149
+ if (!isPendingTeardownAbandoned(read, ownerStillRunning)) continue;
150
+ if (clearPendingTeardown(read.receipt.nonce)) discharged.push(read.receipt.nonce);
151
+ else failed.push(read.receipt.nonce);
152
+ }
153
+ return { discharged, failed };
154
+ }
155
+
156
+ /** Startup half: after this proxy published its own routing, release what the update kept. */
157
+ export function completeUpdateTeardownHandover(
158
+ ownerStillRunning: (pid: number) => boolean,
159
+ log: Pick<Console, "log" | "error"> = console,
160
+ ): void {
161
+ const handover = dischargeUpdateTeardownHandovers(ownerStillRunning);
162
+ if (handover.discharged.length > 0) log.log(" Took over the Codex routing an update kept in place.");
163
+ for (const nonce of handover.failed) {
164
+ log.error(`⚠️ Could not remove the update handover receipt ${pendingTeardownPathFor(nonce)}; the next 'ocx stop' finishes it.`);
165
+ }
166
+ }
@@ -25,20 +25,31 @@ export function sweepUpdateLeftovers(args: {
25
25
  notOwned: string[];
26
26
  };
27
27
  export function launcherUsableAfterNpmUpdate(tx: { ok: boolean; phase: string; rolledBack?: boolean } | null | undefined): boolean;
28
- export function transactionalNpmUpdate(args: {
28
+ export type NpmInstallResult = {
29
+ status: number | null;
30
+ error?: { code?: string; message?: string };
31
+ signal?: string | null;
32
+ processTreeExited?: boolean;
33
+ };
34
+ type NpmUpdateOptions = {
29
35
  packageDir: string;
30
36
  pkgName: string;
31
37
  targetVersion?: string;
32
38
  tag: string;
33
- runNpm: (args: string[]) => { status: number | null };
39
+ runNpm: (args: string[]) => NpmInstallResult;
34
40
  /** npm cache root the pre-flight resolved and checked; pinned with `--cache` for staging. */
35
41
  cachePath?: string;
36
42
  log?: (line: string) => void;
37
43
  deps?: UpdateFsDeps;
38
- }): {
44
+ };
45
+ type NpmUpdateResult = {
39
46
  ok: boolean;
40
47
  phase: "stage" | "verify" | "swap-backup" | "swap-live" | "post-verify" | "double-fault" | "done";
41
48
  error?: string;
42
49
  rolledBack?: boolean;
43
50
  backup?: string;
44
51
  };
52
+ export function transactionalNpmUpdate(args: NpmUpdateOptions): NpmUpdateResult;
53
+ export function transactionalNpmUpdateAsync(args: Omit<NpmUpdateOptions, "runNpm"> & {
54
+ runNpm: (args: string[]) => NpmInstallResult | Promise<NpmInstallResult>;
55
+ }): Promise<NpmUpdateResult>;
@@ -384,12 +384,11 @@ export function bootRestoreProbe(packageDir, deps = {}) {
384
384
  * Run the transactional update. `runNpm(args, opts)` is injected so the caller keeps
385
385
  * its hardened npm resolution (npm-invocation.mjs) and logging.
386
386
  */
387
- export function transactionalNpmUpdate({
387
+ function* npmUpdateTransaction({
388
388
  packageDir,
389
389
  pkgName,
390
390
  targetVersion,
391
391
  tag,
392
- runNpm,
393
392
  cachePath,
394
393
  log = () => {},
395
394
  deps = {},
@@ -437,13 +436,18 @@ export function transactionalNpmUpdate({
437
436
  // operator's global npmrc would be dropped and npm would fall back to its default root. Pin
438
437
  // the cache the pre-flight resolved and checked, so staging uses that exact root (#6288).
439
438
  const cacheArgs = typeof cachePath === "string" && cachePath.length > 0 ? ["--cache", cachePath] : [];
440
- const install = runNpm([
439
+ const install = yield [
441
440
  "install", "-g", "--prefix", stageRoot, ...cacheArgs,
442
441
  "--allow-scripts=bun", "--no-audit", "--no-fund", spec,
443
- ]);
444
- if (install.status !== 0) {
445
- discardStage();
446
- return { ok: false, phase: "stage", error: "npm staging install failed (" + (install.status ?? "?") + ")" };
442
+ ];
443
+ if (install.status !== 0 || install.error || install.processTreeExited === false) {
444
+ if (install.processTreeExited === false) {
445
+ log("Left this update's staging directory in place: process-tree exit was not confirmed; stop the installer before removing " + basename(stageRoot));
446
+ } else discardStage();
447
+ const detail = install.error
448
+ ? [install.error.code, install.error.message].filter(Boolean).join(": ")
449
+ : install.signal ?? install.status ?? "?";
450
+ return { ok: false, phase: "stage", error: "npm staging install failed (" + detail + ")" };
447
451
  }
448
452
  const stagedPackage = stagedCandidatesIn(stageRoot).find(dir => existsSync(join(dir, "package.json")));
449
453
  if (!stagedPackage) {
@@ -524,3 +528,25 @@ export function transactionalNpmUpdate({
524
528
  discardStage();
525
529
  return { ok: true, phase: "done", backup: backupPackage };
526
530
  }
531
+
532
+ /** Keep synchronous callers while the Node launcher awaits the install/exit barrier. */
533
+ export function transactionalNpmUpdate(options) {
534
+ const transaction = npmUpdateTransaction(options);
535
+ const step = transaction.next();
536
+ if (step.done) return step.value;
537
+ // Preserve the legacy status-only transaction on POSIX and for existing callers.
538
+ const install = options.runNpm(step.value);
539
+ return transaction.next({ status: install.status }).value;
540
+ }
541
+
542
+ export async function transactionalNpmUpdateAsync(options) {
543
+ const transaction = npmUpdateTransaction(options);
544
+ const step = transaction.next();
545
+ if (step.done) return step.value;
546
+ let install;
547
+ try { install = await options.runNpm(step.value); }
548
+ catch (error) { install = { status: null, error, processTreeExited: false }; }
549
+ if (install.processTreeExited !== true) install = { ...install, status: null, processTreeExited: false,
550
+ error: install.error ?? { code: "EINSTALLJOIN", message: "npm process-tree exit was not confirmed" } };
551
+ return transaction.next(install).value;
552
+ }