@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
@@ -41,12 +41,14 @@ import {
41
41
  import {
42
42
  GENERIC_OAUTH_MAX_ACCOUNTS_PER_REQUEST,
43
43
  GENERIC_OAUTH_MAX_FAILOVERS_PER_REQUEST,
44
+ antigravityModelRefusal,
44
45
  eligibleFailoverAccounts,
45
46
  forgetGenericFailoverRoster,
46
47
  isGenericFailoverProvider,
47
48
  isProactivePreferenceEnabled,
48
49
  preferredInitialAccount,
49
50
  refusalAwareInitialKiroAccount,
51
+ routeAntigravityModel,
50
52
  noteGenericPoolSelection,
51
53
  } from "../../oauth/generic-account-failover";
52
54
  import { admitGenericSessionAccount, bindGenericSessionAccount, genericSessionAccount, genericSessionAccountEligible, genericSessionAffinityEnabled, preferredGenericSessionAccount } from "../../oauth/generic-session-affinity";
@@ -79,7 +81,7 @@ import { recordAnthropicAccountQuotaFromHeadersForInstance, hasPassiveAccountQuo
79
81
  import { checkOutboundBodySize, describeOutboundBodyRefusal } from "./outbound-body-guard";
80
82
  import { formatErrorResponse } from "../../bridge";
81
83
  import { bindRouteReasoningReplayScope } from "./core-replay";
82
- import { sessionIdHeaderFromRequest, normalizeLogConversationId } from "../request-log-conversation";
84
+ import { assignNativeLogConversationId, sessionIdHeaderFromRequest, normalizeLogConversationId } from "../request-log-conversation";
83
85
  import { redactSecretString } from "../../lib/redact";
84
86
  import { captureAccountAutoPauseAttempt } from "../../oauth/account-auto-pause";
85
87
  import { selectProactiveApiKeyTransport } from "../../providers/key-failover";
@@ -183,6 +185,7 @@ export async function prepareResponsesTransport(
183
185
  || route.providerName === "orcarouter-oauth"
184
186
  // runTurn transport: the replay runs on the first-event preflight in run-turn-execution.
185
187
  || route.providerName === "devin"
188
+ || route.providerName === "workbuddy-ai"
186
189
  || route.providerName === "dsh-account"
187
190
  ) && route.provider.authMode === "oauth";
188
191
  let sentOAuthSnapshot: OAuthAccessSnapshot | undefined;
@@ -244,6 +247,9 @@ export async function prepareResponsesTransport(
244
247
  if (candidate.provider !== route.providerName) return null;
245
248
  if (anthropicInstance) anthropicRouteDecision = currentAnthropicRouteDecision();
246
249
  if (anthropicRouteDecision && !routeCandidates(anthropicRouting!.getEligibleAnthropicAccounts(Date.now(), route.modelId), anthropicRouteDecision).includes(candidate.accountId)) return null;
250
+ // #7500: no admission, initial or a recovery/failover rebind, may land on an Antigravity
251
+ // account whose own roster omits the model. Callers abandon the send on null.
252
+ if (antigravityModelRefusal(config, route.providerName, candidate.accountId, route.modelId)) return null;
247
253
  const committed = genericAffinityMode
248
254
  ? admitGenericSessionAccount(config, route.providerName, oauthSelection, candidate, route.modelId, genericAffinityMode)
249
255
  : await commitOAuthAccountSelection(route.providerName, candidate.accountId, {
@@ -485,6 +491,10 @@ export async function prepareResponsesTransport(
485
491
  parsed._kiroAuthContext = kiroContext;
486
492
  if (retryParsed !== parsed) retryParsed._kiroAuthContext = { ...kiroContext };
487
493
  }
494
+ if (route.providerName === "workbuddy-ai") {
495
+ parsed._workbuddyAuthContext = snapshot.workbuddy;
496
+ if (retryParsed !== parsed) retryParsed._workbuddyAuthContext = snapshot.workbuddy;
497
+ }
488
498
  if (route.providerName === "zed") {
489
499
  // Zed signs with its own user id; `snapshot.accountId` is the local slot hash.
490
500
  const zedContext = { userId: snapshot.providerUserId ?? "" };
@@ -978,10 +988,16 @@ export async function prepareResponsesTransport(
978
988
  ?? refusalAwareId ?? (isGenericFailoverProvider(route.providerName, route.provider)
979
989
  ? preferredInitialAccount(config, route.providerName, Date.now(), route.modelId)
980
990
  : null);
991
+ // #7500: an Antigravity account whose own discovery omits the model is never sent to.
992
+ // A usable listing (or not-yet-discovered) sibling replaces it, or the request is refused.
993
+ const modelRoute = routeAntigravityModel(config, route.providerName,
994
+ proposedAccountId ?? oauthSelection?.accountId, route.modelId);
995
+ if (modelRoute.kind === "refuse") return formatErrorResponse(403, "permission_error", modelRoute.message);
996
+ const routedAccountId = modelRoute.kind === "reroute" ? modelRoute.accountId : proposedAccountId;
981
997
  // An unchanged active choice must retain the ordinary resolver's terminal-refresh
982
998
  // recovery (not the speculative-preference fallback that resolves the same dead grant).
983
- const preferredAccountId = genericAffinityMode && proposedAccountId === oauthSelection?.accountId
984
- ? null : proposedAccountId;
999
+ const preferredAccountId = genericAffinityMode && routedAccountId === oauthSelection?.accountId
1000
+ ? null : routedAccountId;
985
1001
  let safetyAlternateId: string | null = !affinityAccountId && preferredAccountId === refusalAwareId ? refusalAwareId : null;
986
1002
  // Resolved account-scoped, NOT through failoverAccountSnapshot: that helper marks a
987
1003
  // rotation site, and rotation sites must apply their credential through
@@ -1041,6 +1057,10 @@ export async function prepareResponsesTransport(
1041
1057
  resolved = await getValidAccessTokenSnapshot(route.providerName);
1042
1058
  usedPreferredAccount = false;
1043
1059
  }
1060
+ // Resolution fallbacks can still land on an omitting account; answer with the refusal
1061
+ // here, since the commit below would only report it as a changed selection.
1062
+ const unlisted = antigravityModelRefusal(config, route.providerName, resolved.accountId, route.modelId);
1063
+ if (unlisted) return formatErrorResponse(403, "permission_error", unlisted);
1044
1064
  const admitted = await commitResolvedOAuthSelection(resolved, safetyAlternateId === null);
1045
1065
  if (!admitted) return formatErrorResponse(409, "conflict_error", "OAuth account selection changed; retry the request");
1046
1066
  if (safetyAlternateId && admitted.accountId !== safetyAlternateId)
@@ -1104,6 +1124,7 @@ export async function prepareResponsesTransport(
1104
1124
  // Only genuinely accountless adapter calls leave the context undefined and use local/env fallback.
1105
1125
  parsed._kiroAuthContext = { ...(resolved.kiro ?? {}) };
1106
1126
  }
1127
+ if (route.providerName === "workbuddy-ai") parsed._workbuddyAuthContext = resolved.workbuddy;
1107
1128
  if (route.providerName === "zed") {
1108
1129
  parsed._zedAuthContext = { userId: resolved.providerUserId ?? "" };
1109
1130
  }
@@ -1198,9 +1219,7 @@ export async function prepareResponsesTransport(
1198
1219
  codexAuthContext: admissionState.authCtx,
1199
1220
  forwardHeaders: requestState.selectedForwardHeaders,
1200
1221
  });
1201
- if (!logCtx.conversationId && parsed._cursorConversationId) {
1202
- logCtx.conversationId = normalizeLogConversationId(parsed._cursorConversationId);
1203
- }
1222
+ assignNativeLogConversationId(logCtx, normalizeLogConversationId(parsed._cursorConversationId));
1204
1223
  logCtx.providerAdapter = adapter.name;
1205
1224
  // Ordinary requests receive one durable attempt only after their final initial
1206
1225
  // adapter is resolved. Combo children own their attempt and retries keep it.
@@ -1,3 +1,4 @@
1
+ import { requiresToolCall } from "../../types";
1
2
  import type { ResponsesRequestContext, ResponsesAdmissionState } from "./core-options";
2
3
  import type { PreparedResponsesRequest } from "./request-prepare";
3
4
  import type { ResponsesSidecarAuth } from "./request-sidecar-auth";
@@ -26,11 +27,11 @@ export function createResponsesEffects(
26
27
  | "route"
27
28
  | "substituteMainCredential"
28
29
  >,
29
- sidecarState: Pick<ResponsesSidecarAuth, "routedCompaction">,
30
+ sidecarState: Pick<ResponsesSidecarAuth, "routedCompaction"> & Partial<Pick<ResponsesSidecarAuth, "preserveCompactionPrefix">>,
30
31
  ) {
31
32
  const { options, req, config } = requestContext;
32
33
  const { parsed, poolAffinityKey, route, substituteMainCredential } = requestState;
33
- const { routedCompaction } = sidecarState;
34
+ const { routedCompaction, preserveCompactionPrefix } = sidecarState;
34
35
 
35
36
 
36
37
  const recordTerminalOutcomes = options.recordTerminalOutcomes !== false;
@@ -67,8 +68,8 @@ export function createResponsesEffects(
67
68
 
68
69
  // Remote compaction v2 on a ROUTED model: Codex sent `compaction_trigger` and requires exactly
69
70
  // one `{type:"compaction"}` output item (codex-rs compact_remote_v2.rs). Passthrough handles it
70
- // natively upstream; here we run the routed model as a plain summarizer — no tools, no web-search
71
- // sidecar — and the bridge appends the synthetic compaction item (src/responses/compaction.ts).
71
+ // natively upstream; here the routed model summarizes without sidecar execution, and the
72
+ // bridge appends the synthetic compaction item (src/responses/compaction.ts).
72
73
  // A Responses-shaped wire does not imply support for Codex's private
73
74
  // `compaction_trigger` item — only the canonical ChatGPT backend speaks that
74
75
  // contract. An API-key gateway would receive the trigger, answer with an ordinary
@@ -87,12 +88,21 @@ export function createResponsesEffects(
87
88
  }
88
89
  };
89
90
  if (routedCompaction) {
90
- delete parsed.context.tools;
91
91
  delete parsed._webSearch;
92
- delete parsed._anthropicServerTools;
93
- delete parsed._anthropicServerReplay;
94
- delete parsed.options.toolChoice;
95
- delete parsed.options.parallelToolCalls;
92
+ if (!preserveCompactionPrefix) {
93
+ delete parsed.context.tools;
94
+ delete parsed._anthropicServerTools;
95
+ delete parsed._anthropicServerReplay;
96
+ delete parsed.options.toolChoice;
97
+ delete parsed.options.parallelToolCalls;
98
+ } else if (parsed._anthropicServerTools?.length || requiresToolCall(parsed.options.toolChoice)) {
99
+ // Hosted tools execute upstream, and a mandatory choice would force a call the summary
100
+ // guard must reject. Keep the choice itself so the adapter derives the same tools and
101
+ // system bytes; the adapter replaces only the final wire tool_choice with "none".
102
+ // tool_choice changes invalidate message cache, not tools/system (Anthropic caching docs).
103
+ parsed._summaryProhibitsToolCalls = true;
104
+ }
105
+ // Client tool events are rejected by guardCompactionSummary before reaching Codex.
96
106
  // The compaction turn is a plain prose summary; a surviving structured-output format
97
107
  // would force schema-constrained JSON into the synthetic compaction item. The flag and
98
108
  // the raw `text` control go too: the key-mode openai-responses adapter builds from
@@ -105,7 +115,9 @@ export function createResponsesEffects(
105
115
  }
106
116
  parsed.context.messages = [
107
117
  ...parsed.context.messages,
108
- { role: "user", content: COMPACT_PROMPT, timestamp: Date.now() },
118
+ { role: "user", content: preserveCompactionPrefix
119
+ ? `${COMPACT_PROMPT}\n\nReturn only the handoff summary. Do not call tools or continue the task.`
120
+ : COMPACT_PROMPT, timestamp: Date.now() },
109
121
  ];
110
122
  }
111
123
 
@@ -19,7 +19,7 @@ import { releaseProviderRequestSlot, waitForProviderRequestSlot, RequestPacingQu
19
19
  import type { AdapterEventQueue } from "../../adapters/run-turn-queue";
20
20
  import type { AttemptRecoveryKind } from "../../usage/log";
21
21
  import { providerFetch } from "./fetch-helpers";
22
- import { normalizeLogConversationId } from "../request-log-conversation";
22
+ import { assignNativeLogConversationId, normalizeLogConversationId } from "../request-log-conversation";
23
23
  import { normalizeDeclaredToolName, type AdapterEvent, type OcxProviderContinuationState } from "../../types";
24
24
  import { adapterFailureFromMessage, SEND_BUDGET_EXHAUSTED_CODE, SPEND_LEDGER_STORAGE_UNAVAILABLE_CODE, type OcxErrorPayload } from "../../lib/errors";
25
25
  import { SendBudgetExhaustedError, markResponseNonReplayable } from "../../lib/upstream-retry";
@@ -406,9 +406,7 @@ export async function executeResponsesRunTurn(
406
406
  releaseProviderRequestSlot(pacingSlot);
407
407
  // Cursor assigns a stable conversation id inside runTurn on the first headerless
408
408
  // turn; backfill so Logs can filter/total that opening request (#330 / #522).
409
- if (!logCtx.conversationId && parsed._cursorConversationId) {
410
- logCtx.conversationId = normalizeLogConversationId(parsed._cursorConversationId);
411
- }
409
+ assignNativeLogConversationId(logCtx, normalizeLogConversationId(parsed._cursorConversationId));
412
410
  targetQueue.close();
413
411
  }
414
412
  };
@@ -34,6 +34,7 @@ import {
34
34
  } from "../../oauth/generic-account-failover";
35
35
  import { classifyKiroRefusal } from "../../adapters/kiro-refusal";
36
36
  import { isNonReplayableResponse, SendBudgetExhaustedError } from "../../lib/upstream-retry";
37
+ import { isVerifiedModelNotInPlanResponse, markVerifiedModelNotInPlanResponse } from "../../lib/errors";
37
38
  import { unwrapUpstreamRetryEvidenceError } from "../../codex/auth-context";
38
39
  import { AdmissionModelDeniedError, admissionModelDeniedResponse } from "../admission-model-scope";
39
40
  import { noteKiroMonthlyRefusal, noteKiroServedSuccess } from "../../providers/kiro-usage";
@@ -51,7 +52,7 @@ import { namespacedToolName } from "../../types";
51
52
  import { providerFetch } from "./fetch-helpers";
52
53
  import type { AttemptRecoveryKind } from "../../usage/log";
53
54
  import { recordAdapterReasoning, recordAdapterTier } from "../request-log";
54
- import { normalizeLogConversationId } from "../request-log-conversation";
55
+ import { assignNativeLogConversationId, normalizeLogConversationId } from "../request-log-conversation";
55
56
  import { attemptAccountChanged } from "../request-log-account-rotation";
56
57
  import { rememberResponseState } from "../../responses/state";
57
58
  import { trackStreamLifetime } from "../lifecycle";
@@ -200,7 +201,7 @@ export async function executeResponsesSidecars(
200
201
  }
201
202
 
202
203
  // Image / web-search sidecars: plan once, then dispatch with runTurn-aware priority.
203
- // Routed-compaction turns must NOT hit the image bridge: compaction clears tools/_webSearch but
204
+ // Routed-compaction turns must NOT hit the image bridge: compaction disables tool execution but
204
205
  // leaves _imageGeneration, so planImageBridge would activate and return a normal Responses
205
206
  // completion instead of the synthetic compaction item Codex expects (#424).
206
207
  //
@@ -584,6 +585,7 @@ export async function executeResponsesSidecars(
584
585
  return fetch.unpacedFetch ?? fetch;
585
586
  },
586
587
  onRequestBuilt: request => {
588
+ if (typeof request.usageLog?.inputTokens === "number") logCtx.usageLogInputTokens = request.usageLog.inputTokens;
587
589
  recordAdapterReasoning(logCtx, request);
588
590
  recordAdapterTier(logCtx, request);
589
591
  },
@@ -592,9 +594,7 @@ export async function executeResponsesSidecars(
592
594
  // Cursor may assign _cursorConversationId inside the image loop's first runTurn;
593
595
  // backfill so Logs can filter/total that opening request (parity with the normal
594
596
  // runTurn branch).
595
- if (!logCtx.conversationId && parsed._cursorConversationId) {
596
- logCtx.conversationId = normalizeLogConversationId(parsed._cursorConversationId);
597
- }
597
+ assignNativeLogConversationId(logCtx, normalizeLogConversationId(parsed._cursorConversationId));
598
598
  transportState.bindKeyUsageFromBridge(usage);
599
599
  },
600
600
  on429: rotateSidecarProviderOn429,
@@ -632,10 +632,13 @@ export async function executeResponsesSidecars(
632
632
  if (imgResponse.body) {
633
633
  const imgTurnAc = new AbortController();
634
634
  imgTurnAc.signal.addEventListener("abort", cancelResponseCompletion, { once: true });
635
- return new Response(trackStreamLifetime(imgResponse.body, imgTurnAc, releaseSearchProbeLease, options.turnAdmissionLease), {
635
+ const tracked = new Response(trackStreamLifetime(imgResponse.body, imgTurnAc, releaseSearchProbeLease, options.turnAdmissionLease), {
636
636
  status: imgResponse.status,
637
637
  headers: imgResponse.headers,
638
638
  });
639
+ // The wrapper is a new object; a verified plan refusal keeps its provenance across it.
640
+ if (isVerifiedModelNotInPlanResponse(imgResponse)) markVerifiedModelNotInPlanResponse(tracked);
641
+ return tracked;
639
642
  }
640
643
  releaseSearchProbeLease();
641
644
  return imgResponse;
@@ -696,6 +699,7 @@ export async function executeResponsesSidecars(
696
699
  abortSignal: options.abortSignal,
697
700
  onFirstOutput: noteSidecarOutput,
698
701
  onRequestBuilt: request => {
702
+ if (typeof request.usageLog?.inputTokens === "number") logCtx.usageLogInputTokens = request.usageLog.inputTokens;
699
703
  recordAdapterReasoning(logCtx, request);
700
704
  recordAdapterTier(logCtx, request);
701
705
  },
@@ -751,10 +755,12 @@ export async function executeResponsesSidecars(
751
755
  if (wsResponse.body) {
752
756
  const wsTurnAc = new AbortController();
753
757
  wsTurnAc.signal.addEventListener("abort", cancelResponseCompletion, { once: true });
754
- return new Response(trackStreamLifetime(wsResponse.body, wsTurnAc, releaseSearchProbeLease, options.turnAdmissionLease), {
758
+ const tracked = new Response(trackStreamLifetime(wsResponse.body, wsTurnAc, releaseSearchProbeLease, options.turnAdmissionLease), {
755
759
  status: wsResponse.status,
756
760
  headers: wsResponse.headers,
757
761
  });
762
+ if (isVerifiedModelNotInPlanResponse(wsResponse)) markVerifiedModelNotInPlanResponse(tracked);
763
+ return tracked;
758
764
  }
759
765
  releaseSearchProbeLease();
760
766
  return wsResponse;
@@ -0,0 +1,267 @@
1
+ import type { OcxMessagePhase } from "../types";
2
+ import { Buffer } from "node:buffer";
3
+ import type { TranslatorBudget } from "../lib/translator-budget";
4
+ import type { SseBlockRewrite } from "./sse-payload-rewrite";
5
+ import { replaceSseDataPayload, sseDataPayload } from "./sse-payload-rewrite";
6
+
7
+ /**
8
+ * Opt-in per-provider phase inference for Responses passthrough streams.
9
+ *
10
+ * OpenAI models annotate assistant messages with a commentary/final_answer
11
+ * phase; the Codex desktop UI collapses commentary into progress rows and
12
+ * only fully renders the final answer. Third-party gateways forward plain
13
+ * Responses items without that field, so every narration chunk renders
14
+ * expanded. The wire has no phase field, so phase is inferred from what
15
+ * follows each completed message, mirroring the openai-chat bridge strategy:
16
+ * a message followed by tool-call work is commentary; a message at turn end
17
+ * is the final answer. Messages already carrying commentary or final_answer
18
+ * are left untouched and forwarded without buffering; a null or unknown phase
19
+ * is inferred like a missing one. Each rewritten message stays
20
+ * buffered until the next protocol event (SSE keepalives keep it pending).
21
+ * Live text deltas are not buffered, but message completion waits for that
22
+ * event. Snapshots reuse each item decision when their phase is absent,
23
+ * matched by item id or, when either side lacks an id, by output index;
24
+ * explicit snapshot phases take precedence, and failed snapshots are untouched.
25
+ */
26
+
27
+ const TERMINAL_EVENT_TYPES = new Set([
28
+ "response.completed",
29
+ "response.incomplete",
30
+ "response.failed",
31
+ ]);
32
+ const TOOL_CALL_ITEM_TYPES = new Set([
33
+ "function_call",
34
+ "custom_tool_call",
35
+ "local_shell_call",
36
+ "shell_call",
37
+ "apply_patch_call",
38
+ "mcp_call",
39
+ "tool_search_call",
40
+ "web_search_call",
41
+ ]);
42
+
43
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
44
+ return !!value && typeof value === "object" && !Array.isArray(value);
45
+ }
46
+
47
+ /** Only these two values are decisions; null or unknown phases count as missing. */
48
+ function isMessagePhase(value: unknown): value is OcxMessagePhase {
49
+ return value === "commentary" || value === "final_answer";
50
+ }
51
+
52
+ function isToolCallItem(item: unknown): boolean {
53
+ if (!isPlainObject(item)) return false;
54
+ const type = item.type;
55
+ return typeof type === "string"
56
+ && (TOOL_CALL_ITEM_TYPES.has(type)
57
+ // Unknown hosted/extension call shapes still prove the turn continued.
58
+ || (type.endsWith("_call") && !type.endsWith("_call_output")));
59
+ }
60
+
61
+ function parseDataPayload(block: string): Record<string, unknown> | null {
62
+ const payload = sseDataPayload(block);
63
+ if (payload === null) return null;
64
+ try {
65
+ const parsed = JSON.parse(payload) as unknown;
66
+ return isPlainObject(parsed) ? parsed : null;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+
72
+ function isDoneSentinel(block: string): boolean {
73
+ return sseDataPayload(block)?.trim() === "[DONE]";
74
+ }
75
+
76
+ function isMessageDoneBlock(block: string): boolean {
77
+ const parsed = parseDataPayload(block);
78
+ return parsed?.type === "response.output_item.done"
79
+ && isPlainObject(parsed.item) && parsed.item.type === "message";
80
+ }
81
+
82
+ function withMessagePhase(block: string, phase: OcxMessagePhase): string {
83
+ const parsed = parseDataPayload(block);
84
+ if (!parsed || parsed.type !== "response.output_item.done") return block;
85
+ if (!isPlainObject(parsed.item) || isMessagePhase(parsed.item.phase)) return block;
86
+ const patched = { ...parsed, item: { ...parsed.item, phase } };
87
+ return replaceSseDataPayload(block, JSON.stringify(patched));
88
+ }
89
+
90
+ /** One per-item decision, findable by item id and by output index. */
91
+ interface PhaseDecision {
92
+ readonly id: string | null;
93
+ readonly index: number | null;
94
+ readonly phase: OcxMessagePhase;
95
+ }
96
+
97
+ interface PhaseDecisions {
98
+ readonly byId: ReadonlyMap<string, PhaseDecision>;
99
+ readonly byIndex: ReadonlyMap<number, PhaseDecision>;
100
+ }
101
+
102
+ function outputIndexOf(value: unknown): number | null {
103
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
104
+ }
105
+
106
+ /**
107
+ * The phase already emitted on the wire for the snapshot item at `position`.
108
+ * An id match wins. A position match is used only when the event or the
109
+ * snapshot item lacks an id, so two different ids never share a decision.
110
+ */
111
+ function decidedPhase(decisions: PhaseDecisions, id: string | null, position: number): OcxMessagePhase | undefined {
112
+ const byId = id !== null ? decisions.byId.get(id) : undefined;
113
+ if (byId) return byId.phase;
114
+ const byIndex = decisions.byIndex.get(position);
115
+ return byIndex && (byIndex.id === null || id === null) ? byIndex.phase : undefined;
116
+ }
117
+
118
+ function withSnapshotPhases(block: string, decisions: PhaseDecisions): string {
119
+ const parsed = parseDataPayload(block);
120
+ if (!parsed) return block;
121
+ const response = parsed.response;
122
+ if (!isPlainObject(response) || !Array.isArray(response.output)) return block;
123
+ let changed = false;
124
+ const output = response.output.map((item: unknown, position: number) => {
125
+ if (isPlainObject(item) && item.type === "message" && !isMessagePhase(item.phase)) {
126
+ // Mirror the decision already emitted for this item on the wire, so
127
+ // clients reconciling the final snapshot never re-expand a message
128
+ // whose output_item.done said commentary. Items the rewrite never saw
129
+ // (joined mid-stream, no buffered decision) fall back to final_answer.
130
+ const id = typeof item.id === "string" ? item.id : null;
131
+ const phase = decidedPhase(decisions, id, position) ?? "final_answer";
132
+ changed = true;
133
+ return { ...item, phase };
134
+ }
135
+ return item;
136
+ });
137
+ if (!changed) return block;
138
+ const patched = { ...parsed, response: { ...response, output } };
139
+ return replaceSseDataPayload(block, JSON.stringify(patched));
140
+ }
141
+
142
+ export function createResponsesPhaseInferenceBlockRewrite(budget: TranslatorBudget): SseBlockRewrite {
143
+ // At most one message-done block is held at a time; the next block decides
144
+ // its phase and is then processed itself. Malformed blocks pass through
145
+ // without consuming the pending decision. Per-item decisions fill missing
146
+ // snapshot phases. Both pending blocks and decisions share the request
147
+ // retention budget and are released at a terminal event or teardown.
148
+ let pending: string | null = null;
149
+ let pendingBytes = 0;
150
+ let decisionBytes = 0;
151
+ const byId = new Map<string, PhaseDecision>();
152
+ const byIndex = new Map<number, PhaseDecision>();
153
+ const decisions: PhaseDecisions = { byId, byIndex };
154
+ const scope = { kind: "retained_collectors" as const };
155
+
156
+ const clearState = (): void => {
157
+ budget.releaseRetained(pendingBytes + decisionBytes, scope);
158
+ pending = null;
159
+ pendingBytes = 0;
160
+ decisionBytes = 0;
161
+ byId.clear();
162
+ byIndex.clear();
163
+ };
164
+
165
+ const decisionSize = (decision: PhaseDecision): number =>
166
+ Buffer.byteLength(JSON.stringify([decision.id, decision.index, decision.phase]));
167
+
168
+ const rememberPhase = (item: unknown, outputIndex: unknown, phase: OcxMessagePhase): void => {
169
+ const id = isPlainObject(item) && typeof item.id === "string" ? item.id : null;
170
+ const index = outputIndexOf(outputIndex);
171
+ if (id === null && index === null) return;
172
+ const next: PhaseDecision = { id, index, phase };
173
+ const replaced = new Set<PhaseDecision>();
174
+ const previousById = id !== null ? byId.get(id) : undefined;
175
+ const previousByIndex = index !== null ? byIndex.get(index) : undefined;
176
+ if (previousById) replaced.add(previousById);
177
+ if (previousByIndex) replaced.add(previousByIndex);
178
+ let delta = decisionSize(next);
179
+ for (const previous of replaced) delta -= decisionSize(previous);
180
+ // Charge before mutating, so a budget rejection leaves state consistent.
181
+ if (delta > 0) budget.chargeRetained(delta, scope);
182
+ else if (delta < 0) budget.releaseRetained(-delta, scope);
183
+ for (const previous of replaced) {
184
+ if (previous.id !== null && byId.get(previous.id) === previous) byId.delete(previous.id);
185
+ if (previous.index !== null && byIndex.get(previous.index) === previous) byIndex.delete(previous.index);
186
+ }
187
+ if (id !== null) byId.set(id, next);
188
+ if (index !== null) byIndex.set(index, next);
189
+ decisionBytes += delta;
190
+ };
191
+
192
+ const releasePending = (phase: OcxMessagePhase): readonly string[] => {
193
+ if (pending === null) return [];
194
+ const block = pending;
195
+ const parsed = parseDataPayload(block);
196
+ rememberPhase(parsed?.item, parsed?.output_index, phase);
197
+ const patched = withMessagePhase(block, phase);
198
+ budget.releaseRetained(pendingBytes, scope);
199
+ pending = null;
200
+ pendingBytes = 0;
201
+ return [patched];
202
+ };
203
+
204
+ const rewrite = (block: string): readonly string[] => {
205
+ const parsed = parseDataPayload(block);
206
+ const type = typeof parsed?.type === "string" ? parsed.type : null;
207
+ if (TERMINAL_EVENT_TYPES.has(type!)) {
208
+ // Turn end: any still-buffered message is the final answer, and the
209
+ // terminal snapshot mirrors the same per-item decisions for consistency.
210
+ const released = releasePending("final_answer");
211
+ const snapshot = type === "response.failed" ? block : withSnapshotPhases(block, decisions);
212
+ clearState();
213
+ return [...released, snapshot];
214
+ }
215
+ if (type === "response.output_item.done" && isMessageDoneBlock(block)) {
216
+ const item = parsed?.item;
217
+ if (isPlainObject(item) && isMessagePhase(item.phase)) {
218
+ // An explicit upstream phase needs no inference: forward immediately
219
+ // instead of buffering a message that an abnormal teardown would
220
+ // otherwise drop before it was ever emitted.
221
+ const released = releasePending("commentary");
222
+ rememberPhase(item, parsed?.output_index, item.phase);
223
+ return [...released, block];
224
+ }
225
+ // A following message done means the turn continued past the buffered
226
+ // one (a phase change or a guarded continuation): commentary. Buffer
227
+ // the current block for classification by whatever comes next.
228
+ const released = releasePending("commentary");
229
+ const bytes = Buffer.byteLength(block);
230
+ budget.chargeRetained(bytes, scope);
231
+ pending = block;
232
+ pendingBytes = bytes;
233
+ return released;
234
+ }
235
+ if (type === null) {
236
+ // Comment keepalives and other non-JSON data blocks carry no
237
+ // classification evidence in either direction, so a still-buffered
238
+ // message stays pending across them. The [DONE] sentinel closes the
239
+ // stream cleanly, which proves the buffered message was the turn's
240
+ // final answer.
241
+ if (isDoneSentinel(block)) {
242
+ const released = releasePending("final_answer");
243
+ clearState();
244
+ return [...released, block];
245
+ }
246
+ return [block];
247
+ }
248
+ // Any other protocol event after a completed message proves the turn
249
+ // continued past it (tool calls, reasoning, a new item): commentary.
250
+ return [...releasePending("commentary"), block];
251
+ };
252
+
253
+ return Object.assign((block: string): readonly string[] => {
254
+ try { return rewrite(block); }
255
+ catch (error) {
256
+ clearState();
257
+ throw error;
258
+ }
259
+ }, {
260
+ dispose: () => {
261
+ // Relay teardown after a terminal event leaves nothing pending. An
262
+ // abnormal teardown before classification drops the retained block,
263
+ // since the stream is failing anyway and no phase was ever proven.
264
+ clearState();
265
+ },
266
+ });
267
+ }
@@ -96,6 +96,8 @@ export function createSseBlockBuffer(
96
96
  let buffer = "";
97
97
  let offset = 0;
98
98
  let scanOffset = 0;
99
+ let needsScan = false;
100
+ let lastCodeUnit = Number.NaN;
99
101
  let bufferBytes = 0;
100
102
  const delimiterPattern = /(?:\r\n|\r(?!\n)|\n){2}/g;
101
103
 
@@ -111,7 +113,7 @@ export function createSseBlockBuffer(
111
113
  if (!fragment) return;
112
114
  let fragmentBytes = Buffer.byteLength(fragment, "utf8");
113
115
  // Decoder output never splits a surrogate pair, but keep the helper exact for string callers.
114
- const last = buffer.charCodeAt(buffer.length - 1);
116
+ const last = lastCodeUnit;
115
117
  const first = fragment.charCodeAt(0);
116
118
  if (offset < buffer.length && last >= 0xd800 && last <= 0xdbff && first >= 0xdc00 && first <= 0xdfff) {
117
119
  fragmentBytes -= 2;
@@ -122,6 +124,8 @@ export function createSseBlockBuffer(
122
124
  try {
123
125
  compact();
124
126
  buffer += fragment;
127
+ lastCodeUnit = fragment.charCodeAt(fragment.length - 1);
128
+ needsScan ||= fragment.includes("\r") || fragment.includes("\n");
125
129
  reservation.commitRetained();
126
130
  budget.releaseRetained(bufferBytes, scope);
127
131
  bufferBytes = nextBytes;
@@ -131,11 +135,16 @@ export function createSseBlockBuffer(
131
135
  }
132
136
  },
133
137
  next() {
138
+ if (!needsScan) {
139
+ scanOffset = Math.max(offset, buffer.length - 3);
140
+ return null;
141
+ }
134
142
  delimiterPattern.lastIndex = scanOffset;
135
143
  const match = delimiterPattern.exec(buffer);
136
144
  if (!match) {
137
145
  // A delimiter is at most four code units. Revisit only its possible split prefix.
138
146
  scanOffset = Math.max(offset, buffer.length - 3);
147
+ needsScan = false;
139
148
  return null;
140
149
  }
141
150
  const start = match.index;
@@ -153,6 +162,8 @@ export function createSseBlockBuffer(
153
162
  buffer = "";
154
163
  offset = 0;
155
164
  scanOffset = 0;
165
+ needsScan = false;
166
+ lastCodeUnit = Number.NaN;
156
167
  }
157
168
  return { block, delimiter };
158
169
  },
@@ -164,6 +175,8 @@ export function createSseBlockBuffer(
164
175
  buffer = "";
165
176
  offset = 0;
166
177
  scanOffset = 0;
178
+ needsScan = false;
179
+ lastCodeUnit = Number.NaN;
167
180
  bufferBytes = 0;
168
181
  },
169
182
  };
@@ -15,9 +15,18 @@ import type { ManagementPrincipal } from "./management-auth";
15
15
 
16
16
  export type GrokStripResult = { ok: boolean; changed: boolean; message: string };
17
17
 
18
+ /** Read-only promise covering API teardown and the CLI runtime's signal/manager exit cleanup. */
19
+ export function stopCapabilities() {
20
+ return { schema: "ocx-stop-capabilities/1", connectedClientOwnership: true, pid: process.pid };
21
+ }
22
+
18
23
  export type StopTeardownIo = {
19
24
  /** Does the nonce this request carries name a readable obligation on disk? */
20
25
  ownsReceipt?: (nonce: string | null) => boolean;
26
+ /** Does that obligation hand the teardown to the proxy an update restarts (#7423)? */
27
+ isHandoverReceipt?: (nonce: string | null) => boolean;
28
+ /** Keep Codex, Grok and env fences in place when this process exits. */
29
+ keepClientConfigOnExit?: () => void;
21
30
  restoreNativeCodex?: () => Promise<CodexNativeRestoreResult>;
22
31
  stripGrok?: () => GrokStripResult;
23
32
  };
@@ -25,7 +34,7 @@ export type StopTeardownIo = {
25
34
  export type StopTeardownBody = {
26
35
  success: boolean;
27
36
  message: string;
28
- /** `not-owned`: a sibling instance, whose shared client routing belongs to the live owner. */
37
+ /** `not-owned`: shared routing belongs to a live sibling owner or a client connection. */
29
38
  sharedTeardown: "deferred" | "performed" | "not-owned";
30
39
  };
31
40
 
@@ -79,8 +88,34 @@ export async function performStopTeardown(url: URL, io: StopTeardownIo = {}): Pr
79
88
  if (siblingOfLivePort() !== null) {
80
89
  return { success: true, message: `Proxy stopping. ${siblingSkipMessage()}`, sharedTeardown: "not-owned" };
81
90
  }
91
+ // A connection owns its integrations across stop/start, even for a successful API stop.
92
+ // This is persisted authority, not a caller's request to skip an obligation it owns.
93
+ const connection = (await import("../client/state")).readClientConnectionState();
94
+ if (connection.kind === "connected") {
95
+ return {
96
+ success: true,
97
+ message: "Proxy stopping; connection-owned Codex routing, catalog and Grok config preserved. Run `ocx disconnect` to release them.",
98
+ sharedTeardown: "not-owned",
99
+ };
100
+ }
82
101
  const ownsReceipt = io.ownsReceipt ?? deferralMatchesReceipt;
83
102
  if (deferralHonored(url, ownsReceipt)) {
103
+ // A handover outlives this process: the exit cleanup would otherwise restore native
104
+ // Codex and put the pristine catalog back right after the stop kept them (#7423).
105
+ // Exiting as a recycle leaves them for the replacement, as a dashboard restart does.
106
+ const nonce = url.searchParams.get("teardownNonce");
107
+ const handover = io.isHandoverReceipt
108
+ ? io.isHandoverReceipt(nonce)
109
+ : (await import("../config/pending-teardown")).isUpdateHandoverReceipt(nonce);
110
+ if (handover) {
111
+ if (io.keepClientConfigOnExit) io.keepClientConfigOnExit();
112
+ else (await import("./lifecycle")).markRecyclingForExit();
113
+ return {
114
+ success: true,
115
+ message: "Proxy stopping; Codex routing and catalog kept for the updated proxy.",
116
+ sharedTeardown: "deferred",
117
+ };
118
+ }
84
119
  // Not "native Codex restored": nothing was restored here, and claiming otherwise
85
120
  // would be a success message the operator cannot verify.
86
121
  return {