@bitkyc08/opencodex 2.100.1 → 2.100.3

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 (624) hide show
  1. package/README.md +1 -1
  2. package/bin/ocx.mjs +32 -18
  3. package/gui/dist/assets/{App-COo8Yopd.css → App-BGP8I0V4.css} +1 -1
  4. package/gui/dist/assets/App-Dnb6VMsP.js +59 -0
  5. package/gui/dist/assets/Tray-BV4ms9U9.js +1 -0
  6. package/gui/dist/assets/{brand-mark-nr3ziR-T.js → brand-mark-XOLJbomA.js} +1 -1
  7. package/gui/dist/assets/index-DCdXsMyZ.js +105 -0
  8. package/gui/dist/assets/index-DQtCRNAw.css +2 -0
  9. package/gui/dist/assets/{segment-thumb-features-DKCVUUTi.js → segment-thumb-features-DXSidY6D.js} +1 -1
  10. package/gui/dist/classic/assets/App-DA-scMPq.js +58 -0
  11. package/gui/dist/classic/assets/{Tray-BedmOsE7.js → Tray-BrHaVRAq.js} +1 -1
  12. package/gui/dist/classic/assets/index-BqOaGLf5.js +105 -0
  13. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +1 -0
  14. package/gui/dist/classic/index.html +1 -1
  15. package/gui/dist/index.html +2 -2
  16. package/native/ocx-child/Cargo.toml +9 -0
  17. package/native/ocx-child/src/cli.rs +402 -20
  18. package/native/ocx-child/src/codex_home.rs +98 -14
  19. package/native/ocx-child/src/daemon.rs +2 -1
  20. package/native/ocx-child/src/lib.rs +3 -0
  21. package/native/ocx-child/src/link_ws.rs +2598 -0
  22. package/native/ocx-child/src/link_ws_advert.rs +346 -0
  23. package/native/ocx-child/src/link_ws_frame.rs +749 -0
  24. package/native/ocx-child/src/parity.rs +5 -1
  25. package/native/ocx-child/src/platform.rs +152 -6
  26. package/native/ocx-child/src/relay.rs +150 -19
  27. package/package.json +3 -3
  28. package/src/adapters/anthropic/advisor-tool.ts +176 -0
  29. package/src/adapters/anthropic/beta-body-pairs.ts +6 -0
  30. package/src/adapters/anthropic/client-identity.ts +3 -1
  31. package/src/adapters/anthropic/passthrough.ts +9 -3
  32. package/src/adapters/anthropic.ts +31 -14
  33. package/src/adapters/client-fingerprint.ts +6 -4
  34. package/src/adapters/cursor/discovery.ts +17 -0
  35. package/src/adapters/cursor/native-exec-desktop.ts +2 -1
  36. package/src/adapters/cursor/native-exec-shell.ts +2 -1
  37. package/src/adapters/cursor/native-exec.ts +3 -2
  38. package/src/adapters/cursor/protobuf-request.ts +8 -8
  39. package/src/adapters/cursor/tool-guidance.ts +3 -3
  40. package/src/adapters/cursor/tool-wording.ts +10 -1
  41. package/src/adapters/cursor.ts +7 -6
  42. package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
  43. package/src/adapters/google-antigravity-wire.ts +15 -6
  44. package/src/adapters/google-truncation.ts +4 -2
  45. package/src/adapters/google-wire-compiler.ts +2 -2
  46. package/src/adapters/google.ts +17 -4
  47. package/src/adapters/kiro/payload.ts +7 -4
  48. package/src/adapters/kiro/reasoning.ts +44 -1
  49. package/src/adapters/kiro/structured-output.ts +10 -8
  50. package/src/adapters/kiro-tools.ts +61 -15
  51. package/src/adapters/openai-chat/destination-policy.ts +16 -0
  52. package/src/adapters/openai-chat/reasoning-replay.ts +4 -1
  53. package/src/adapters/openai-chat/tool-schema.ts +9 -0
  54. package/src/adapters/openai-responses/tool-schema.ts +18 -4
  55. package/src/adapters/run-turn-queue.ts +139 -5
  56. package/src/adapters/upstream-http-error.ts +4 -2
  57. package/src/adapters/zed.ts +3 -0
  58. package/src/advisor/consult.ts +15 -4
  59. package/src/advisor/context.ts +12 -3
  60. package/src/advisor/runtime.ts +35 -5
  61. package/src/advisor/settings.ts +8 -0
  62. package/src/advisor/synthetic-tool.ts +21 -8
  63. package/src/bridge/response-json.ts +11 -2
  64. package/src/bridge/sse.ts +51 -9
  65. package/src/claude/auth-detect.ts +21 -33
  66. package/src/claude/chat-tool-dispatch.ts +233 -0
  67. package/src/claude/desktop-3p.ts +11 -5
  68. package/src/claude/desktop-gateway-state.ts +2 -0
  69. package/src/claude/desktop-remote-store-artifact.ts +14 -3
  70. package/src/claude/desktop-remote-store.ts +24 -4
  71. package/src/claude/inbound-content-options.ts +31 -16
  72. package/src/claude/inbound-tool-loading.ts +42 -17
  73. package/src/claude/outbound.ts +13 -3
  74. package/src/cli/account-api.ts +23 -1
  75. package/src/cli/account-auth.ts +54 -21
  76. package/src/cli/account-extended.ts +60 -6
  77. package/src/cli/account-key-quota.ts +56 -7
  78. package/src/cli/account.ts +5 -3
  79. package/src/cli/advisor.ts +7 -4
  80. package/src/cli/alias.ts +38 -1
  81. package/src/cli/capabilities-access-remote.ts +137 -2
  82. package/src/cli/capabilities-accounts.ts +3 -3
  83. package/src/cli/capabilities-agents-routing.ts +17 -10
  84. package/src/cli/capabilities-base.ts +43 -18
  85. package/src/cli/capabilities-integrations.ts +2 -2
  86. package/src/cli/capabilities-provider-models.ts +18 -2
  87. package/src/cli/capabilities-route-to.ts +43 -0
  88. package/src/cli/capabilities.ts +2 -0
  89. package/src/cli/capability-contracts.ts +1 -1
  90. package/src/cli/claude-desktop.ts +30 -11
  91. package/src/cli/claude.ts +36 -17
  92. package/src/cli/codex-launcher.ts +3 -1
  93. package/src/cli/codex-shim-autorestore.ts +5 -42
  94. package/src/cli/config-command.ts +38 -2
  95. package/src/cli/config-root-startup.ts +34 -0
  96. package/src/cli/connect.ts +124 -19
  97. package/src/cli/desktop-runtime-guidance.ts +1 -1
  98. package/src/cli/disconnect-runtime.ts +168 -0
  99. package/src/cli/dispatch.ts +54 -12
  100. package/src/cli/export-command.ts +1 -1
  101. package/src/cli/gui-pair-client.ts +29 -5
  102. package/src/cli/gui.ts +10 -5
  103. package/src/cli/help-catalog.ts +11 -0
  104. package/src/cli/help.ts +5 -4
  105. package/src/cli/hub.ts +18 -1
  106. package/src/cli/index.ts +83 -92
  107. package/src/cli/inspect.ts +11 -2
  108. package/src/cli/integrations.ts +26 -1
  109. package/src/cli/link-capture.ts +64 -0
  110. package/src/cli/link-child-ops.ts +314 -0
  111. package/src/cli/link-cleanup.ts +8 -5
  112. package/src/cli/link-diagnostics.ts +67 -0
  113. package/src/cli/link-enrollment.ts +158 -12
  114. package/src/cli/link-operations.ts +52 -0
  115. package/src/cli/link-recover.ts +152 -0
  116. package/src/cli/link-routes.ts +87 -0
  117. package/src/cli/link-status-child.ts +137 -0
  118. package/src/cli/link-status-traffic.ts +34 -0
  119. package/src/cli/link.ts +327 -37
  120. package/src/cli/message-command.ts +1 -1
  121. package/src/cli/message-mcp-command.ts +23 -10
  122. package/src/cli/models-runtime.ts +3 -3
  123. package/src/cli/opencode.ts +3 -1
  124. package/src/cli/pi-sync.ts +35 -0
  125. package/src/cli/preflight-exemptions.ts +46 -0
  126. package/src/cli/registry.ts +29 -12
  127. package/src/cli/restart-failure.ts +5 -2
  128. package/src/cli/root.ts +5 -1
  129. package/src/cli/route-to.ts +172 -0
  130. package/src/cli/runtime-api.ts +5 -8
  131. package/src/cli/status.ts +3 -1
  132. package/src/cli/stop-approval.ts +66 -19
  133. package/src/cli/stop-report.ts +23 -0
  134. package/src/cli/stop-windows-checked.ts +304 -0
  135. package/src/cli/sync-command.ts +70 -13
  136. package/src/cli/sync-fanout.ts +81 -99
  137. package/src/cli/sync-flags.ts +40 -3
  138. package/src/cli/sync-link-status.ts +18 -2
  139. package/src/cli/sync-update-guard.ts +7 -2
  140. package/src/cli/system-restart-client.ts +3 -2
  141. package/src/cli/uninstall-plan.ts +77 -5
  142. package/src/cli/uninstall-stop.ts +152 -0
  143. package/src/cli/v2-input.ts +10 -6
  144. package/src/cli/v2-local-output.ts +3 -2
  145. package/src/cli/v2-runtime.ts +10 -3
  146. package/src/cli/v2.ts +22 -7
  147. package/src/client/connect.ts +321 -34
  148. package/src/client/link-home-features.ts +27 -0
  149. package/src/client/link-home.ts +92 -4
  150. package/src/client/link-ingress.ts +21 -3
  151. package/src/client/link-join.ts +12 -2
  152. package/src/client/link-parity-reporter.ts +60 -6
  153. package/src/client/link-readiness.ts +16 -6
  154. package/src/client/link-relay-transport.ts +161 -36
  155. package/src/client/link-relay.ts +150 -6
  156. package/src/client/link-request-compression.ts +84 -0
  157. package/src/client/link-state.ts +11 -5
  158. package/src/client/link-status.ts +39 -1
  159. package/src/client/link-teardown.ts +1 -0
  160. package/src/client/link-tunnel-status.ts +76 -0
  161. package/src/client/link-tunnel.ts +56 -5
  162. package/src/client/link-websocket-limits.ts +89 -0
  163. package/src/client/link-websocket.ts +586 -0
  164. package/src/client/link-ws-advertisement.ts +100 -0
  165. package/src/client/link-ws-framer.ts +241 -0
  166. package/src/client/link-ws-transport.ts +177 -0
  167. package/src/client/machine-api.ts +13 -2
  168. package/src/client/machine-listener.ts +48 -7
  169. package/src/client/route-intent-apply.ts +293 -0
  170. package/src/client/route-intent-file-originals.ts +97 -0
  171. package/src/client/route-intent-native-originals.ts +201 -0
  172. package/src/client/route-intent-watch.ts +141 -0
  173. package/src/client/runtime-restart.ts +127 -5
  174. package/src/client/runtime.ts +61 -15
  175. package/src/client/state.ts +30 -0
  176. package/src/client/sync-expectation.ts +36 -2
  177. package/src/client/sync-runtime.ts +7 -0
  178. package/src/clients/config-export/alias-selectors.ts +63 -40
  179. package/src/clients/config-export/contracts.ts +2 -0
  180. package/src/clients/config-export/nested-selectors.ts +42 -0
  181. package/src/clients/config-export.ts +36 -4
  182. package/src/codex/account-resume-health.ts +41 -0
  183. package/src/codex/account-store.ts +12 -3
  184. package/src/codex/account-usability.ts +13 -0
  185. package/src/codex/auth-api/account-list.ts +29 -3
  186. package/src/codex/auth-api/login-flow.ts +6 -0
  187. package/src/codex/auth-api/routes.ts +35 -2
  188. package/src/codex/auth-collision.ts +23 -22
  189. package/src/codex/auth-context.ts +21 -6
  190. package/src/codex/catalog/gather-capture.ts +10 -2
  191. package/src/codex/catalog/parsing.ts +7 -3
  192. package/src/codex/catalog/provider-models.ts +67 -23
  193. package/src/codex/catalog/retained-sync.ts +2 -1
  194. package/src/codex/catalog/routed-gather.ts +1 -1
  195. package/src/codex/catalog-auto-refresh.ts +11 -0
  196. package/src/codex/cli-update-job.ts +35 -13
  197. package/src/codex/convergence-types.ts +2 -0
  198. package/src/codex/convergence.ts +2 -2
  199. package/src/codex/desktop-compatibility/native-identity.ts +4 -8
  200. package/src/codex/features.ts +2 -2
  201. package/src/codex/history-provider.ts +31 -0
  202. package/src/codex/inject/multi-agent-v2.ts +9 -3
  203. package/src/codex/inject/paginated-openai-compat.ts +54 -1
  204. package/src/codex/inject/plan.ts +20 -2
  205. package/src/codex/inject.ts +2 -0
  206. package/src/codex/journal-config-restore.ts +217 -0
  207. package/src/codex/journal.ts +75 -6
  208. package/src/codex/main-account.ts +23 -30
  209. package/src/codex/native-main-auth-file.ts +104 -0
  210. package/src/codex/native-profile-manager.ts +4 -3
  211. package/src/codex/native-profile-store.ts +3 -61
  212. package/src/codex/orca-import.ts +10 -1
  213. package/src/codex/quota-history.ts +13 -0
  214. package/src/codex/quota-window-conflict.ts +103 -0
  215. package/src/codex/quota.ts +134 -7
  216. package/src/codex/subagent-model-fallback.ts +3 -1
  217. package/src/codex/websocket-activity.ts +171 -16
  218. package/src/codex/websocket-registry.ts +11 -4
  219. package/src/combos/cooldown-store.ts +228 -0
  220. package/src/combos/failover.ts +760 -35
  221. package/src/config/dashboard-trusted-proxy.ts +83 -0
  222. package/src/config/diagnostics.ts +28 -0
  223. package/src/config/feature-flags.ts +9 -0
  224. package/src/config/live-reconcile.ts +10 -1
  225. package/src/config/load-degrade.ts +12 -1
  226. package/src/config/multi-agent-surface.ts +28 -5
  227. package/src/config/pending-teardown.ts +60 -3
  228. package/src/config/process-state.ts +175 -4
  229. package/src/config/provider-validation.ts +4 -4
  230. package/src/config/salvage.ts +1 -0
  231. package/src/config/schema/config-schema.ts +12 -3
  232. package/src/config/schema/leaf-validators.ts +43 -14
  233. package/src/config/windows-process-command-line.ts +107 -0
  234. package/src/generated/compatibility-version.json +1077 -429
  235. package/src/generated/model-metadata.ts +1 -1
  236. package/src/images/loop.ts +3 -0
  237. package/src/integrations/model-name-guard.ts +25 -0
  238. package/src/integrations/route-intent-catalog.ts +26 -0
  239. package/src/integrations/route-intent-connected.ts +262 -0
  240. package/src/integrations/route-intent-contract.ts +55 -0
  241. package/src/integrations/route-intent-disconnect.ts +109 -0
  242. package/src/integrations/route-intent-initial.ts +64 -0
  243. package/src/integrations/route-intent-state.ts +117 -0
  244. package/src/integrations/route-intent-tick.ts +65 -0
  245. package/src/integrations/route-intent.ts +212 -0
  246. package/src/integrations/writer.ts +44 -11
  247. package/src/lib/catalog-etag.ts +10 -0
  248. package/src/lib/client-error-body.ts +15 -0
  249. package/src/lib/client-retry-after.ts +29 -0
  250. package/src/lib/config-ownership.ts +13 -0
  251. package/src/lib/context-overflow-verdict.ts +266 -9
  252. package/src/lib/desktop-gui-origin.ts +28 -0
  253. package/src/lib/errors.ts +1 -1
  254. package/src/lib/failure-detail.ts +72 -3
  255. package/src/lib/gui-pair-capability.ts +2 -1
  256. package/src/lib/hard-refusal.ts +259 -0
  257. package/src/lib/messages-error-body.ts +4 -1
  258. package/src/lib/outbound-credential-registry.ts +362 -4
  259. package/src/lib/paced-stream.ts +34 -0
  260. package/src/lib/passive-key-fetch-proof.ts +30 -0
  261. package/src/lib/passive-read.ts +5 -0
  262. package/src/lib/process-control.ts +76 -12
  263. package/src/lib/redact.ts +84 -8
  264. package/src/lib/state-store-registrations.ts +11 -0
  265. package/src/lib/state-store-sweeper.ts +4 -0
  266. package/src/lib/supervisor-markers.ts +18 -0
  267. package/src/lib/terminal-safe-text.ts +58 -0
  268. package/src/lib/translator-budget.ts +3 -2
  269. package/src/lib/upstream-retry.ts +14 -4
  270. package/src/link/alias-lock.ts +119 -0
  271. package/src/link/child-activity.ts +83 -0
  272. package/src/link/child-binary-cache-fill.d.mts +50 -0
  273. package/src/link/child-binary-cache-fill.mjs +494 -0
  274. package/src/link/child-binary-cache-start.ts +73 -0
  275. package/src/link/child-binary-source.ts +12 -5
  276. package/src/link/child-catalog-freshness.ts +149 -0
  277. package/src/link/child-gated-ocx.ts +135 -0
  278. package/src/link/child-observations.ts +206 -0
  279. package/src/link/child-observe.ts +121 -0
  280. package/src/link/child-ops-engine.ts +230 -0
  281. package/src/link/child-ops-host.ts +138 -0
  282. package/src/link/child-ops-runners.ts +319 -0
  283. package/src/link/child-ops-scheduler.ts +207 -0
  284. package/src/link/child-ops-types.ts +89 -0
  285. package/src/link/child-parity.ts +23 -4
  286. package/src/link/child-policy.ts +93 -0
  287. package/src/link/child-update-contract.ts +174 -0
  288. package/src/link/codex-settings.ts +1 -1
  289. package/src/link/compatibility.ts +18 -1
  290. package/src/link/diagnostics-read.ts +163 -0
  291. package/src/link/diagnostics.ts +20 -7
  292. package/src/link/explicit-route.ts +209 -0
  293. package/src/link/link-recover.ts +113 -0
  294. package/src/link/management-routes.ts +3 -1
  295. package/src/link/operation-recovery-slot.ts +44 -0
  296. package/src/link/operations-journal.ts +408 -0
  297. package/src/link/paths.ts +5 -0
  298. package/src/link/peer-report.ts +1 -1
  299. package/src/link/relay-auth.ts +14 -0
  300. package/src/link/remote-plant.ts +152 -14
  301. package/src/link/remote-platform.ts +21 -10
  302. package/src/link/remote-probe.ts +11 -3
  303. package/src/link/remote-windows.ts +88 -12
  304. package/src/link/request-compression.ts +30 -0
  305. package/src/link/residual-recovery.ts +54 -0
  306. package/src/link/retirement.ts +128 -0
  307. package/src/link/route-intent-watch.ts +41 -0
  308. package/src/link/route-intent.ts +209 -0
  309. package/src/link/route-proof.ts +82 -0
  310. package/src/link/route-rounds.ts +579 -0
  311. package/src/link/route-select.ts +95 -0
  312. package/src/link/route-trust.ts +96 -0
  313. package/src/link/ssh-argv.ts +285 -43
  314. package/src/link/ssh-capture-redact.ts +253 -0
  315. package/src/link/ssh-capture.ts +497 -0
  316. package/src/link/ssh-runner.ts +141 -14
  317. package/src/link/status-projection.ts +160 -0
  318. package/src/link/store.ts +54 -1
  319. package/src/link/supervisor.ts +543 -55
  320. package/src/link/sync-fanout-classify.ts +114 -0
  321. package/src/link/sync-then-restart.ts +65 -0
  322. package/src/link/tombstones.ts +209 -0
  323. package/src/link/traffic.ts +178 -0
  324. package/src/link/tunnel-state.ts +10 -4
  325. package/src/link/ws-activity-holds.ts +474 -0
  326. package/src/local-credentials/publication-fence.ts +20 -1
  327. package/src/messaging/mcp-queue-rpc.ts +3 -2
  328. package/src/messaging/mcp-queue-server.ts +21 -1
  329. package/src/messaging/mcp-reply-tools.ts +24 -9
  330. package/src/messaging/mcp-reply-wait.ts +70 -0
  331. package/src/messaging/mcp-resume-tools.ts +25 -0
  332. package/src/messaging/remote-enrollment.ts +3 -3
  333. package/src/messaging/remote-tunnels.ts +2 -2
  334. package/src/messaging/resume-permissions.ts +27 -0
  335. package/src/messaging/rpc.ts +46 -2
  336. package/src/oauth/account-resume-health.ts +60 -0
  337. package/src/oauth/anthropic-continuity.ts +23 -7
  338. package/src/oauth/anthropic-routing.ts +5 -2
  339. package/src/oauth/anthropic.ts +22 -2
  340. package/src/oauth/claude-keychain-read.ts +78 -68
  341. package/src/oauth/index.ts +25 -6
  342. package/src/oauth/local-token-detect.ts +8 -29
  343. package/src/oauth/login-cli-errors.ts +5 -1
  344. package/src/oauth/login-cli.ts +33 -18
  345. package/src/oauth/login-flow-state.ts +26 -3
  346. package/src/oauth/meta-muse.ts +1 -1
  347. package/src/oauth/store.ts +51 -1
  348. package/src/oauth/xai.ts +248 -14
  349. package/src/protocols/contract.ts +4 -0
  350. package/src/protocols/encoders/messages.ts +1 -0
  351. package/src/providers/alias-template.ts +48 -0
  352. package/src/providers/anthropic-billing-ownership.ts +2 -0
  353. package/src/providers/anthropic-output-caps.ts +46 -0
  354. package/src/providers/anthropic-reset-grant-ledger.ts +9 -3
  355. package/src/providers/antigravity-effort-families.ts +11 -3
  356. package/src/providers/antigravity-models.ts +32 -9
  357. package/src/providers/antigravity-wire-snapshot.ts +3 -2
  358. package/src/providers/api-key-pause-state.ts +23 -0
  359. package/src/providers/api-key-pause.ts +71 -10
  360. package/src/providers/api-key-resolve.ts +49 -7
  361. package/src/providers/api-key-response-ownership.ts +2 -0
  362. package/src/providers/api-key-selection-capture.ts +3 -1
  363. package/src/providers/api-key-selection.ts +54 -11
  364. package/src/providers/api-keys.ts +24 -7
  365. package/src/providers/cache-affinity-identity.ts +73 -0
  366. package/src/providers/cache-affinity.ts +256 -0
  367. package/src/providers/claude-cli-usage-state.ts +11 -6
  368. package/src/providers/claude-cli-usage.ts +27 -9
  369. package/src/providers/codex-capacity.ts +11 -2
  370. package/src/providers/default-aliases.ts +98 -20
  371. package/src/providers/google-vertex-model-discovery.ts +510 -0
  372. package/src/providers/key-failover.ts +136 -14
  373. package/src/providers/key-store.ts +3 -3
  374. package/src/providers/kiro-models.ts +3 -5
  375. package/src/providers/label.ts +31 -5
  376. package/src/providers/mistral-transport.ts +17 -4
  377. package/src/providers/model-discovery-config.ts +31 -0
  378. package/src/providers/model-discovery-diagnostic.ts +34 -3
  379. package/src/providers/model-discovery.ts +43 -7
  380. package/src/providers/model-rename-fields.ts +5 -0
  381. package/src/providers/muse-key-quota.ts +14 -6
  382. package/src/providers/new-model-policy-runtime.ts +17 -4
  383. package/src/providers/new-model-policy.ts +30 -4
  384. package/src/providers/openai-sidecar.ts +15 -2
  385. package/src/providers/passive-key-observation.ts +252 -0
  386. package/src/providers/provider-id-rewrite.ts +3 -0
  387. package/src/providers/quota/account-cache.ts +53 -34
  388. package/src/providers/quota/anthropic-cooldown-recovery-worker.ts +121 -0
  389. package/src/providers/quota/anthropic-usage-windows.ts +19 -9
  390. package/src/providers/quota/passive-key-limits.ts +272 -0
  391. package/src/providers/quota/passive-wire-model.ts +126 -0
  392. package/src/providers/quota/report-cache.ts +112 -5
  393. package/src/providers/quota/vendor-probes-key.ts +73 -0
  394. package/src/providers/quota/vendor-probes-oauth.ts +57 -3
  395. package/src/providers/quota-key-accounts.ts +22 -10
  396. package/src/providers/quota-mistral-budget.ts +18 -0
  397. package/src/providers/quota-types.ts +43 -0
  398. package/src/providers/quota.ts +31 -32
  399. package/src/providers/reasoning-metadata.ts +1051 -12
  400. package/src/providers/registry/entries-core.ts +34 -16
  401. package/src/providers/registry/entries-extended.ts +32 -0
  402. package/src/providers/registry/model-seeds.ts +35 -0
  403. package/src/providers/resolved-model-policy.ts +7 -0
  404. package/src/providers/routed-config.ts +8 -3
  405. package/src/providers/xai-transport.ts +3 -0
  406. package/src/quota/reset-observer.ts +4 -2
  407. package/src/quota/reset-seen-store.ts +9 -0
  408. package/src/quota/window-mapping.ts +1 -0
  409. package/src/quota-pool/assemble.ts +4 -1
  410. package/src/remote/features.ts +17 -0
  411. package/src/responses/anthropic-progress.ts +10 -4
  412. package/src/responses/citation-markers.ts +231 -0
  413. package/src/responses/hosted-tool-policy.ts +56 -12
  414. package/src/responses/spill-store.ts +5 -1
  415. package/src/responses/state/replay-input.ts +50 -0
  416. package/src/responses/state/replay-owner.ts +24 -0
  417. package/src/responses/state/snapshot-codec.ts +9 -0
  418. package/src/responses/state/spill-queue.ts +1 -0
  419. package/src/responses/state.ts +42 -60
  420. package/src/router.ts +4 -2
  421. package/src/routing/home-route-capture.ts +123 -0
  422. package/src/routing/home-route-intent.ts +200 -0
  423. package/src/routing/route-intent-state.ts +178 -0
  424. package/src/routing/route-to-live-settings.ts +35 -0
  425. package/src/routing/route-to-local.ts +145 -0
  426. package/src/routing/route-to-status.ts +94 -0
  427. package/src/routing/route-to-sync-child.ts +32 -0
  428. package/src/server/adapter-resolve.ts +21 -1
  429. package/src/server/admitted-http-turn.ts +3 -0
  430. package/src/server/auth-cors.ts +109 -8
  431. package/src/server/bare-upstream-error.ts +220 -0
  432. package/src/server/catalog-download.ts +3 -5
  433. package/src/server/chat-native.ts +25 -7
  434. package/src/server/claude-messages.ts +8 -5
  435. package/src/server/codex-model-list.ts +2 -1
  436. package/src/server/configured-credentials.ts +37 -5
  437. package/src/server/gui-desktop-authorization.ts +36 -0
  438. package/src/server/gui-pair-delivery.ts +6 -3
  439. package/src/server/gui-session.ts +10 -1
  440. package/src/server/images.ts +41 -13
  441. package/src/server/inbound-body-admission.ts +17 -4
  442. package/src/server/index/link-listener.ts +203 -11
  443. package/src/server/index/link-management.ts +15 -1
  444. package/src/server/index/link-relay-sessions.ts +128 -8
  445. package/src/server/index/link-websocket-limits.ts +136 -0
  446. package/src/server/index/link-websocket.ts +692 -0
  447. package/src/server/index/optional-listeners.ts +115 -7
  448. package/src/server/index/route-intent-watch.ts +47 -0
  449. package/src/server/index/serve-contract.ts +86 -0
  450. package/src/server/index/serve-options.ts +35 -86
  451. package/src/server/index/startup-warnings.ts +8 -2
  452. package/src/server/index/websocket-handler.ts +26 -4
  453. package/src/server/index.ts +12 -2
  454. package/src/server/inference/client-encoder-delivery.ts +2 -0
  455. package/src/server/inspection-tee.ts +39 -2
  456. package/src/server/lifecycle.ts +2 -0
  457. package/src/server/link-turn.ts +137 -0
  458. package/src/server/management/advisor-routes.ts +10 -2
  459. package/src/server/management/agent-settings-routes.ts +50 -16
  460. package/src/server/management/anthropic-reset-grant-routes.ts +1 -1
  461. package/src/server/management/config-routes.ts +7 -1
  462. package/src/server/management/context.ts +9 -2
  463. package/src/server/management/desktop-authorization.ts +41 -0
  464. package/src/server/management/desktop-compatibility-routes.ts +9 -8
  465. package/src/server/management/desktop-compatibility-runtime-routes.ts +3 -2
  466. package/src/server/management/desktop-compatibility-settings-routes.ts +5 -3
  467. package/src/server/management/home-integration-decision.ts +89 -0
  468. package/src/server/management/integration-routes.ts +208 -81
  469. package/src/server/management/link-child-ops-routes.ts +218 -0
  470. package/src/server/management/link-child-preflight.ts +31 -0
  471. package/src/server/management/link-diagnostics-route.ts +29 -0
  472. package/src/server/management/link-enrollment.ts +199 -47
  473. package/src/server/management/link-operation.ts +609 -0
  474. package/src/server/management/link-recover-route.ts +103 -0
  475. package/src/server/management/link-route-edit.ts +173 -0
  476. package/src/server/management/link-route-request.ts +62 -0
  477. package/src/server/management/link-route-state.ts +92 -6
  478. package/src/server/management/link-routes.ts +563 -51
  479. package/src/server/management/link-traffic-status.ts +13 -0
  480. package/src/server/management/model-routes.ts +122 -36
  481. package/src/server/management/model-rows.ts +2 -1
  482. package/src/server/management/native-integration-routes.ts +176 -70
  483. package/src/server/management/oauth-account-routes.ts +69 -17
  484. package/src/server/management/protocol-routes.ts +7 -0
  485. package/src/server/management/provider-completion-test.ts +4 -4
  486. package/src/server/management/provider-overwrite-carry.ts +39 -3
  487. package/src/server/management/provider-routes.ts +80 -72
  488. package/src/server/management/provider-routing-quota.ts +45 -0
  489. package/src/server/management/route-registry.ts +25 -3
  490. package/src/server/management/route-to-routes.ts +257 -0
  491. package/src/server/management/system-restart.ts +4 -2
  492. package/src/server/management/usage-aggregate-cache.ts +101 -66
  493. package/src/server/management-api.ts +17 -3
  494. package/src/server/management-auth.ts +13 -1
  495. package/src/server/messages-native-preflight.ts +27 -4
  496. package/src/server/messages-native.ts +22 -5
  497. package/src/server/persistent-gui-session.ts +6 -3
  498. package/src/server/proxy-liveness.ts +33 -6
  499. package/src/server/relay-eager.ts +36 -12
  500. package/src/server/relay.ts +183 -116
  501. package/src/server/request-body-facts.ts +48 -0
  502. package/src/server/request-decompress.ts +65 -2
  503. package/src/server/request-log-account-rotation.ts +6 -0
  504. package/src/server/request-log-attempt-usage.ts +69 -0
  505. package/src/server/request-log-cache-affinity.ts +60 -0
  506. package/src/server/request-log-conversation.ts +45 -2
  507. package/src/server/request-log-failure-detail.ts +59 -1
  508. package/src/server/request-log-terminal-status.ts +210 -24
  509. package/src/server/request-log.ts +71 -79
  510. package/src/server/responses/adapter-continuation.ts +2 -1
  511. package/src/server/responses/adapter-delivery.ts +2 -0
  512. package/src/server/responses/adapter-dispatch.ts +40 -51
  513. package/src/server/responses/advisor-plan-slot.ts +33 -1
  514. package/src/server/responses/advisor-question.ts +21 -0
  515. package/src/server/responses/advisor-slot.ts +10 -3
  516. package/src/server/responses/bare-namespace-aliases.ts +18 -0
  517. package/src/server/responses/buffered-sse-json.ts +9 -3
  518. package/src/server/responses/code-mode-collab-surface.ts +11 -0
  519. package/src/server/responses/codex-tool-catalog.ts +156 -0
  520. package/src/server/responses/combo-required-tool-fulfillments.ts +4 -2
  521. package/src/server/responses/combo-stream-preflight.ts +701 -81
  522. package/src/server/responses/compact.ts +47 -12
  523. package/src/server/responses/context-overflow.ts +58 -2
  524. package/src/server/responses/core-codex-account.ts +17 -3
  525. package/src/server/responses/core-combo-failure.ts +37 -4
  526. package/src/server/responses/core-combo-native.ts +3 -1
  527. package/src/server/responses/core-combo.ts +62 -7
  528. package/src/server/responses/core-errors.ts +8 -3
  529. package/src/server/responses/core-lifetime.ts +3 -2
  530. package/src/server/responses/core-normalize.ts +3 -1
  531. package/src/server/responses/core-opaque-recovery.ts +45 -2
  532. package/src/server/responses/core-options.ts +18 -0
  533. package/src/server/responses/core.ts +2 -0
  534. package/src/server/responses/fetch-helpers.ts +15 -10
  535. package/src/server/responses/native-replay-guard.ts +57 -0
  536. package/src/server/responses/opengateway-completion-guard.ts +10 -4
  537. package/src/server/responses/outbound-request-body.ts +29 -0
  538. package/src/server/responses/passthrough-completion.ts +105 -8
  539. package/src/server/responses/passthrough-delivery.ts +31 -11
  540. package/src/server/responses/passthrough-dispatch.ts +99 -106
  541. package/src/server/responses/policy-fallback.ts +13 -1
  542. package/src/server/responses/request-prepare.ts +50 -6
  543. package/src/server/responses/request-transport.ts +53 -17
  544. package/src/server/responses/reset-replay.ts +104 -4
  545. package/src/server/responses/run-turn-execution.ts +58 -30
  546. package/src/server/responses/sidecar-execution.ts +14 -0
  547. package/src/server/responses/terminal-error-redaction.ts +222 -25
  548. package/src/server/responses/ws-upstream.ts +2 -2
  549. package/src/server/sse-payload-rewrite.ts +3 -2
  550. package/src/server/stop-service-route.ts +85 -0
  551. package/src/server/system-env-shell.ts +12 -1
  552. package/src/server/system-env.ts +5 -3
  553. package/src/server/windows-tcp-drop.ts +21 -4
  554. package/src/server/workflow-refusal.ts +8 -0
  555. package/src/server/ws-bridge.ts +191 -12
  556. package/src/service/cli-windows-stop.ts +189 -0
  557. package/src/service/cli.ts +41 -12
  558. package/src/service/disconnected-client-restart.ts +60 -0
  559. package/src/service/guarded-manager-target.ts +18 -1
  560. package/src/service/health.ts +99 -6
  561. package/src/service/launchd.ts +84 -31
  562. package/src/service/orchestration.ts +418 -91
  563. package/src/service/repair.ts +223 -6
  564. package/src/service/restart-proxy-stop.ts +79 -0
  565. package/src/service/service-child-ownership.ts +6 -2
  566. package/src/service/windows-checked-stop-live.ts +467 -0
  567. package/src/service/windows-checked-stop.ts +435 -0
  568. package/src/service/windows-command-line-token.ts +23 -0
  569. package/src/service/windows-guarded-manager.ts +77 -34
  570. package/src/service/windows-ops.ts +38 -56
  571. package/src/service/windows-process-evidence.ts +292 -0
  572. package/src/service/windows-process-native.ts +262 -0
  573. package/src/service/windows-service-stop.ts +321 -0
  574. package/src/service/windows-stop-binding.ts +187 -0
  575. package/src/service/windows-stop-budget.ts +123 -0
  576. package/src/service/windows-stop-confirm.ts +158 -0
  577. package/src/service/windows-stop-deadline.ts +56 -0
  578. package/src/service.ts +2 -2
  579. package/src/types/claude-tool-loading.ts +48 -0
  580. package/src/types/config.ts +47 -53
  581. package/src/types/link.ts +20 -0
  582. package/src/types/multi-agent.ts +13 -0
  583. package/src/types/provider.ts +68 -2
  584. package/src/types/request.ts +4 -0
  585. package/src/types.ts +4 -0
  586. package/src/update/guarded-runtime-ops.ts +5 -7
  587. package/src/update/index.ts +25 -10
  588. package/src/update/install-detection.mjs +3 -1
  589. package/src/update/job-pinned-start.ts +2 -0
  590. package/src/update/job-windows-restart.ts +19 -32
  591. package/src/update/job.ts +12 -5
  592. package/src/update/npm-install.d.mts +11 -0
  593. package/src/update/npm-install.mjs +44 -7
  594. package/src/update/orchestrated-entry.ts +1 -1
  595. package/src/update/orchestrated-node-driver.mjs +3 -2
  596. package/src/update/orchestrated-pnpm.d.mts +4 -0
  597. package/src/update/orchestrated-pnpm.mjs +50 -6
  598. package/src/update/orchestrated-session.d.mts +3 -1
  599. package/src/update/orchestrated-session.mjs +21 -6
  600. package/src/update/pnpm-global-install.d.mts +21 -3
  601. package/src/update/pnpm-global-install.mjs +322 -19
  602. package/src/update/pnpm-store-layout.mjs +46 -0
  603. package/src/update/sync-update-mutex.d.mts +3 -2
  604. package/src/update/sync-update-mutex.mjs +57 -8
  605. package/src/update/transactional-install.d.mts +3 -1
  606. package/src/update/transactional-install.mjs +545 -12
  607. package/src/update/windows-installer-marker.d.mts +1 -0
  608. package/src/update/windows-installer-marker.mjs +44 -0
  609. package/src/usage/expected-prices.ts +8 -0
  610. package/src/usage/filter-index.ts +326 -77
  611. package/src/usage/ledger-scanner.ts +15 -0
  612. package/src/usage/link-log-fields.ts +48 -0
  613. package/src/usage/log.ts +43 -2
  614. package/src/usage/request-body.ts +37 -0
  615. package/src/web-search/loop.ts +3 -0
  616. package/src/web-search/parse.ts +21 -2
  617. package/gui/dist/assets/App-g3Cm2xhZ.js +0 -59
  618. package/gui/dist/assets/Tray-BMDkAiXy.js +0 -1
  619. package/gui/dist/assets/index-Bziu8gTy.css +0 -2
  620. package/gui/dist/assets/index-OYzhQUNP.js +0 -94
  621. package/gui/dist/classic/assets/App-CgPBKUP-.js +0 -58
  622. package/gui/dist/classic/assets/index-BR-HhNrp.js +0 -94
  623. package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +0 -1
  624. package/src/server/management/desktop-compatibility-authorization.ts +0 -12
@@ -152,6 +152,7 @@ import { requiresPlaintextReasoningReplay } from "../../adapters/openai-response
152
152
  import { destinationDecodesNativeCompactionBlob, isOpenAiOperatedResponsesDestination } from "../../providers/openai-tiers-destination";
153
153
  import { bindRouteReasoningReplayScope } from "./core-replay";
154
154
  import { commitReasoningReplayServingIdentity } from "../../responses/reasoning-replay-cache";
155
+ import { rewriteRoutedCustomToolsForUpstream, RoutedCustomToolCompatError, validateFinalCustomToolCompatibility } from "../../responses/custom-tool-compat";
155
156
  import { findInvalidRetainedCompactionEnvelope, InvalidRetainedCompactionEnvelopeError } from "../../responses/retained-compaction";
156
157
  import { nativeCompactResponseSchema } from "../../responses/schema";
157
158
  import { NATIVE_RESERVE_MODEL } from "../../codex/catalog/native-models";
@@ -177,11 +178,13 @@ import {
177
178
  DecompressedBodyTooLargeError,
178
179
  UnsupportedContentEncodingError,
179
180
  } from "../request-decompress";
180
- import { resolveAdapter, resolveWireProtocolOverride } from "../adapter-resolve";
181
+ import { projectCapturedCustomToolPolicy, resolveAdapter, resolveWireProtocolOverride } from "../adapter-resolve";
181
182
  import { hasKeyPoolFailover, rotateProviderTransportOn429, selectProactiveApiKeyTransport, transientRetryPolicyFor } from "../../providers/key-failover";
182
183
  import { transientSendCapFor } from "./request-send-budget";
183
184
  import { distributedKeyPhysicalFetch, recordDistributedResponseFailure } from "../../providers/api-key-response-ownership";
184
- import { providerApiKeySelectionIsCurrent, resolveCurrentProviderApiKeyTransport } from "../../providers/api-key-selection";
185
+ import { passiveKeyPhysicalFetch } from "../../providers/passive-key-observation";
186
+ import { isProviderApiKeyPaused, ProviderApiKeyPausedError } from "../../providers/api-key-pause";
187
+ import { providerAffinityGenerationIsCurrent, providerApiKeySelectionIsCurrent, resolveCurrentProviderApiKeyTransport } from "../../providers/api-key-selection";
185
188
  import { stampApiKeyAccountLabel } from "../../providers/label";
186
189
  import { shouldAttemptImageTierRetry } from "../image-retry";
187
190
  import { resolveProviderTransport } from "../../providers/xai-transport";
@@ -235,9 +238,10 @@ import { fetchWithHeaderTimeout, providerFetch, safeHostLabel, safeOriginLabel,
235
238
  import { requestPacingOverloadResponse } from "./pacing-overload";
236
239
  import { shouldRetryCodexPoolAccountQuota, shouldRetryCodexPoolAccountTransient } from "./core-codex-account";
237
240
  import { mapCodexAuthContextErrorToResponse, nativeMainRefreshFailureResponse } from "./codex-auth-error";
238
- import { linkRequestSessionLane, sessionLaneIdFromRequest, reasoningReplayConversationIdFromResponsesRequest, sessionIdHeaderFromRequest } from "../request-log-conversation";
241
+ import { affinityLaneFromRequest, linkRequestSessionLane, reasoningReplayConversationIdFromResponsesRequest, sessionIdHeaderFromRequest, sessionLaneIdFromRequest } from "../request-log-conversation";
239
242
  import { recallComboForLane } from "./combo-session-recall";
240
243
  import { redactHostedImageDisplayPaths } from "../responses-hosted-image-display";
244
+ import { warnEagerCodexToolCatalog } from "./codex-tool-catalog";
241
245
 
242
246
  export const COMPACT_RESPONSE_MAX_BYTES = 32 * 1024 * 1024;
243
247
 
@@ -696,6 +700,8 @@ export async function handleResponsesCompact(
696
700
  }
697
701
  const clientModelLabel = options.clientModelLabel ?? clientFacingModelLabel(options.compactionRoutingOverride?.sourceModel ?? (body as { model?: unknown }).model);
698
702
  options = { ...options, clientModelLabel };
703
+ // Compaction body `input` is forwarded history, so only the top-level catalog is counted.
704
+ warnEagerCodexToolCatalog(body, req.headers, { surface: "compact", logicalRequest: logCtx });
699
705
  // Compaction forwards client history upstream too; keep local artifact paths out of it.
700
706
  redactHostedImageDisplayPaths(body);
701
707
  if (!options.compactionRoutingOverride) {
@@ -957,22 +963,33 @@ export async function handleResponsesCompact(
957
963
  const base = isCanonicalOpenAiForwardProvider(compactProvider)
958
964
  ? CODEX_FORWARD_BASE_URL
959
965
  : (compactProvider.baseUrl ?? "").replace(/\/+$/, "");
960
- if (compactProvider.authMode !== "forward" && compactProvider.apiKey) {
966
+ if (compactProvider.authMode !== "forward" && (compactProvider.apiKey || compactProvider.apiKeyPool?.length)) {
961
967
  // Native compact never enters handleResponses, so it needs its own pre-dispatch key
962
968
  // pick. Kept inside this branch on purpose: the overlay above owns the forward and
963
969
  // codexAccountMode cases, and the picker returns null for them anyway.
964
970
  // Transport variant, for the same reason as the Responses core: the persisted row has no
965
971
  // registry backfills, and compactProvider is read for its transport fields below.
966
972
  let warmKeyProvider;
967
- try { warmKeyProvider = selectProactiveApiKeyTransport(config, route.providerName, compactProvider); }
973
+ const affinityLane = affinityLaneFromRequest(req, logCtx, config, admission);
974
+ if (affinityLane) logCtx.affinityLane = affinityLane;
975
+ try { warmKeyProvider = selectProactiveApiKeyTransport(config, route.providerName, compactProvider, undefined, Date.now(), { lane: affinityLane, model: route.modelId, log: logCtx }); }
968
976
  catch (error) {
969
977
  const refusal = requestPacingOverloadResponse(error);
970
- if (refusal) return refusal;
978
+ if (refusal) { logCtx.terminalSource = "synthetic"; return refusal; }
979
+ if (error instanceof ProviderApiKeyPausedError) {
980
+ logCtx.terminalSource = "synthetic";
981
+ return formatErrorResponse(403, "permission_error", error.message);
982
+ }
971
983
  throw error;
972
984
  }
973
985
  if (warmKeyProvider?.apiKey) compactProvider = warmKeyProvider;
974
- headers.set("authorization", `Bearer ${resolveProviderApiKey(compactProvider.apiKey)}`);
975
- stampApiKeyAccountLabel(logCtx, route.providerName, compactProvider);
986
+ if (compactProvider.apiKey) {
987
+ headers.set("authorization", `Bearer ${resolveProviderApiKey(compactProvider.apiKey)}`);
988
+ stampApiKeyAccountLabel(logCtx, route.providerName, compactProvider);
989
+ }
990
+ }
991
+ if (compactProvider.authMode !== "forward" && isProviderApiKeyPaused(compactProvider)) {
992
+ return formatErrorResponse(403, "permission_error", new ProviderApiKeyPausedError().message);
976
993
  }
977
994
  const { reasoning: _reasoning, ...compactBodyRaw } = raw as typeof raw & { reasoning?: unknown };
978
995
  const requireCompactPlaintextReasoning = !isOpenAiOperatedResponsesDestination(compactProvider)
@@ -1184,6 +1201,8 @@ export async function handleResponsesCompact(
1184
1201
  sendAuthCtx: CodexAuthContext,
1185
1202
  onPhysicalDispatch?: () => void,
1186
1203
  ): Promise<Response> => {
1204
+ // Only the captured custom-tool contract: native compact keeps the provider's own wire.
1205
+ sendProvider = projectCapturedCustomToolPolicy(sendProvider, route.staticPolicy);
1187
1206
  // A gateway send carries only its own transport headers, whatever recovery handed in.
1188
1207
  // An account-change scrub that removed the turn state from the send headers still applies.
1189
1208
  let wireHeaders = gatewayTransport ? new Headers(gatewayTransport.headers) : sendHeaders;
@@ -1220,8 +1239,17 @@ export async function handleResponsesCompact(
1220
1239
  replayBody = isolateCodexPoolClientMetadata(replayBody, sendAuthCtx.chatgptAccountId) as typeof replayBody;
1221
1240
  }
1222
1241
  // A queued key selection can refresh the destination; project only for this send.
1223
- return isOpenAiOperatedResponsesDestination(sendProvider)
1242
+ replayBody = isOpenAiOperatedResponsesDestination(sendProvider)
1224
1243
  ? repairUrlCitationAnnotations(replayBody) : stripCanonicalOnlyInputItems(stripCanonicalOnlyTopLevelFields(replayBody));
1244
+ // Only an explicit `false` lowers custom tools here; with no declaration, native compact
1245
+ // forwards every custom tool and its history exactly as before this capability existed.
1246
+ if (sendProvider.supportsResponsesCustomTools === false && !isCanonicalOpenAiForwardProvider(sendProvider)) {
1247
+ replayBody = rewriteRoutedCustomToolsForUpstream(
1248
+ replayBody, sendProvider.supportsResponsesCustomTools,
1249
+ ).body as typeof replayBody;
1250
+ validateFinalCustomToolCompatibility(replayBody, sendProvider.supportsResponsesCustomTools);
1251
+ }
1252
+ return replayBody;
1225
1253
  };
1226
1254
  const doFetch = (upstreamRecovery?: UpstreamSendRecovery) => fetchWithHeaderTimeout(
1227
1255
  compactUrl,
@@ -1244,6 +1272,7 @@ export async function handleResponsesCompact(
1244
1272
  dispatchOverride: sendProvider.authMode !== "forward" && sendProvider.apiKey
1245
1273
  ? async (_input, init, execute, reacquirePacing) => {
1246
1274
  for (let attempt = 0; !providerApiKeySelectionIsCurrent(config, route.providerName, sendProvider); attempt++) {
1275
+ if (!providerAffinityGenerationIsCurrent(config, route.providerName, sendProvider)) throw new Error("Provider affinity selection is no longer available");
1247
1276
  if (attempt >= 3) throw new Error("Provider key selection changed repeatedly before compact dispatch");
1248
1277
  let current = resolveCurrentProviderApiKeyTransport(config, route.providerName, sendProvider);
1249
1278
  if (!current && sendProvider.requestPacing?.enabled
@@ -1252,8 +1281,10 @@ export async function handleResponsesCompact(
1252
1281
  if (fresh) current = selectProactiveApiKeyTransport(config, route.providerName, fresh) ?? fresh;
1253
1282
  }
1254
1283
  if (!current?.apiKey || !supportsNativeResponsesCompactEndpoint(route.providerName, current)) {
1284
+ if (!current?.apiKey && isProviderApiKeyPaused(config.providers[route.providerName])) throw new ProviderApiKeyPausedError();
1255
1285
  throw new Error("Provider key selection is no longer available for compact");
1256
1286
  }
1287
+ current = projectCapturedCustomToolPolicy(current, route.staticPolicy);
1257
1288
  const rebuilt = new Headers(sendHeaders);
1258
1289
  for (const name of Object.keys(sendProvider.headers ?? {})) rebuilt.delete(name);
1259
1290
  for (const [name, value] of Object.entries(current.headers ?? {})) rebuilt.set(name, value);
@@ -1278,7 +1309,7 @@ export async function handleResponsesCompact(
1278
1309
  identityId: logCtx.accountLogLabel })) throw new SendBudgetExhaustedError(errorDestinationLabel(compactUrl));
1279
1310
  noteProviderAttemptSend(logCtx, route.providerName, sendProvider, logCtx.usageLogInputTokens, upstreamRecovery);
1280
1311
  const physicalFetch = ((input, physicalInit) => sendWithConnectionPolicy(
1281
- distributedKeyPhysicalFetch((sendProvider as { fetch?: typeof fetch }).fetch ?? execute, route.providerName, sendProvider, compactUrl), String(input),
1312
+ passiveKeyPhysicalFetch(distributedKeyPhysicalFetch((sendProvider as { fetch?: typeof fetch }).fetch ?? execute, route.providerName, sendProvider, compactUrl), config, route.providerName, sendProvider), String(input),
1282
1313
  physicalInit, { providerName: route.providerName, provider: sendProvider })) as typeof fetch;
1283
1314
  return fetchWithHeaderTimeout(compactUrl,
1284
1315
  { ...init, headers: sendHeaders, body: JSON.stringify({ ...buildCompactSendBody() as typeof compactBody, model: route.modelId }) },
@@ -1315,14 +1346,18 @@ export async function handleResponsesCompact(
1315
1346
  let outcomeCtx = authCtx;
1316
1347
  const localDispatchRefusal = (error: unknown): Response | undefined => {
1317
1348
  const cause = unwrapUpstreamRetryEvidenceError(error);
1318
- const response = cause instanceof InvalidRetainedCompactionEnvelopeError
1349
+ const response = (cause instanceof RoutedCustomToolCompatError
1350
+ ? formatErrorResponse(400, "invalid_request_error", redactSecretString(cause.message))
1351
+ : cause instanceof InvalidRetainedCompactionEnvelopeError
1319
1352
  ? formatErrorResponse(400, "invalid_request_error", cause.message)
1320
- : requestPacingOverloadResponse(cause) ?? spendLedgerStorageErrorResponse(error, logCtx) ?? (cause instanceof SendBudgetExhaustedError
1353
+ : cause instanceof ProviderApiKeyPausedError ? formatErrorResponse(403, "permission_error", cause.message) : undefined)
1354
+ ?? requestPacingOverloadResponse(cause) ?? spendLedgerStorageErrorResponse(error, logCtx) ?? (cause instanceof SendBudgetExhaustedError
1321
1355
  ? unboundPoolSpendRefusalResponse(logCtx) ?? formatErrorResponse(429, "request_send_budget_exhausted", cause.message)
1322
1356
  : mapCodexAuthContextErrorToResponse(cause, {
1323
1357
  now: Date.now(), accountSelector: route.codexAccountNamespace,
1324
1358
  }));
1325
1359
  if (response) {
1360
+ logCtx.terminalSource = "synthetic";
1326
1361
  releaseUpstreamHostAdmission(compactHostAdmissionLease);
1327
1362
  compactHostAdmissionLease = null;
1328
1363
  releaseCodexAuthContextProbeLease(outcomeCtx);
@@ -1,10 +1,10 @@
1
- import { bridgeToResponsesSSE, formatErrorResponse } from "../../bridge";
1
+ import { bridgeToResponsesSSE, buildResponseJSON, formatErrorResponse } from "../../bridge";
2
2
  import { OLLAMA_LATE_ATTRIBUTION_LIMIT_MESSAGE } from "../../adapters/ollama-native";
3
3
  import { isThroughputLimitText } from "../../claude/outbound";
4
4
  import { isDefiniteContextOverflow } from "../../combos/failover";
5
5
  import { classifyError, MODEL_NOT_IN_PLAN_STREAM_CODE } from "../../lib/errors";
6
6
  import type { TranslatorBudget } from "../../lib/translator-budget";
7
- import type { AdapterEvent } from "../../types";
7
+ import type { AdapterEvent, OcxUsage } from "../../types";
8
8
 
9
9
  /**
10
10
  * The Ollama late-attribution refusal as a client response: the existing translator-budget
@@ -221,3 +221,59 @@ export function streamingContextOverflowResponse(
221
221
  },
222
222
  });
223
223
  }
224
+
225
+ /**
226
+ * Return an incomplete JSON response with the target's usage and reason when combo candidates
227
+ * exhaust on zero-output token limits.
228
+ */
229
+ export function jsonIncompleteResponse(
230
+ modelId: string,
231
+ usage?: OcxUsage,
232
+ reason = "max_output_tokens",
233
+ ): Response {
234
+ const json = buildResponseJSON([
235
+ {
236
+ type: "incomplete",
237
+ reason,
238
+ ...(usage ? { usage } : {}),
239
+ },
240
+ ], modelId);
241
+ return Response.json(json, { status: 200, headers: { "Cache-Control": "no-store" } });
242
+ }
243
+
244
+ /**
245
+ * Return an incomplete SSE stream with the target's usage and reason when combo candidates
246
+ * exhaust on zero-output token limits.
247
+ */
248
+ export function streamingIncompleteResponse(
249
+ modelId: string,
250
+ usage?: OcxUsage,
251
+ reason = "max_output_tokens",
252
+ translatorBudget?: TranslatorBudget,
253
+ ): Response {
254
+ async function* incompleteEvents(): AsyncGenerator<AdapterEvent> {
255
+ yield {
256
+ type: "incomplete",
257
+ reason,
258
+ ...(usage ? { usage } : {}),
259
+ };
260
+ }
261
+ return new Response(bridgeToResponsesSSE(
262
+ incompleteEvents(),
263
+ modelId,
264
+ undefined,
265
+ undefined,
266
+ undefined,
267
+ undefined,
268
+ 2_000,
269
+ translatorBudget ? { translatorBudget } : undefined,
270
+ ), {
271
+ headers: {
272
+ "Content-Type": "text/event-stream",
273
+ "Cache-Control": "no-cache",
274
+ Connection: "keep-alive",
275
+ "X-Accel-Buffering": "no",
276
+ },
277
+ });
278
+ }
279
+
@@ -22,6 +22,7 @@ import {
22
22
  resetUpstreamHostHealth,
23
23
  } from "../../codex/upstream-host-health";
24
24
  import { safeOriginLabel, fetchWithHeaderTimeout, providerFetch } from "./fetch-helpers";
25
+ import type { AdapterRequest } from "../../adapters/base";
25
26
  import { classifyPoolRecoveryDispatch } from "../../routing/probe-lease";
26
27
  import { formatErrorResponse } from "../../bridge";
27
28
  import { readBoundedResponseBody } from "../../lib/bounded-body";
@@ -221,14 +222,25 @@ export class PoolPreOutputRefusals {
221
222
  }
222
223
 
223
224
 
225
+ // A recovery that can publish either of two physical attempts binds the proof to the published head.
226
+ const publishedMainQuotaDispatches = new WeakMap<Response, MainQuotaDispatch | null>();
227
+
228
+ /** Bind the quota proof of the attempt whose head `published` carries; none means no proof. */
229
+ export function bindPublishedMainQuotaDispatch(published: Response, dispatch: MainQuotaDispatch | undefined): void {
230
+ publishedMainQuotaDispatches.set(published, dispatch ?? null);
231
+ }
232
+
224
233
  /** Live proof that this plain-main response used the observed main credential. */
225
234
  export function liveMainQuotaDispatch(
226
- authCtx: CodexAuthContext, provider: OcxProviderConfig,
235
+ authCtx: CodexAuthContext, provider: OcxProviderConfig, published?: Response,
227
236
  ): MainQuotaDispatch | undefined {
228
- if (authCtx.kind !== "main" || !authCtx.mainQuotaDispatch) return undefined;
237
+ if (authCtx.kind !== "main") return undefined;
238
+ const dispatch = published && publishedMainQuotaDispatches.has(published)
239
+ ? publishedMainQuotaDispatches.get(published) : authCtx.mainQuotaDispatch;
240
+ if (!dispatch) return undefined;
229
241
  if (!isCanonicalOpenAiForwardProvider(provider)
230
242
  || provider.authMode !== "forward" || provider.adapter !== "openai-responses") return undefined;
231
- return isMainQuotaDispatchLive(authCtx.mainQuotaDispatch) ? authCtx.mainQuotaDispatch : undefined;
243
+ return isMainQuotaDispatchLive(dispatch) ? dispatch : undefined;
232
244
  }
233
245
 
234
246
  export function codexWsQuotaObserver(authCtx: CodexAuthContext, provider: OcxProviderConfig, modelId?: string): CodexWsQuotaObserver | undefined {
@@ -529,6 +541,7 @@ export interface CodexPoolAccountRetryArgs {
529
541
  httpOnly?: boolean;
530
542
  /** Pre-output refusal hold for the alternate's WebSocket send (#6969); the caller restores. */
531
543
  preOutputRefusalHold?: CodexWsPreOutputRefusalHold;
544
+ onPhysicalSend?: (request: AdapterRequest, body: BodyInit | null | undefined) => void;
532
545
  onResponse?: (
533
546
  response: Response,
534
547
  authCtx: CodexAuthContext,
@@ -1072,6 +1085,7 @@ export async function retryCodexPoolOnAlternateAccount(
1072
1085
  httpOnly,
1073
1086
  providerName: route.providerName,
1074
1087
  modelId: route.modelId,
1088
+ onPhysicalDispatch: body => args.onPhysicalSend?.(request, body),
1075
1089
  preOutputRefusalHold: args.preOutputRefusalHold,
1076
1090
  accountAutoPause: (name, provider, headers) => captureAccountAutoPauseAttempt(name, provider, { config, codex: retryAuthCtx }, headers),
1077
1091
  onCodexWsQuota: codexWsQuotaObserver(retryAuthCtx, route.provider, route.modelId),
@@ -1,9 +1,17 @@
1
- import { recordUpstreamValidationDetail, type FailureDetail } from "../request-log-failure-detail";
1
+ import { recordUpstreamProviderErrorDetail, recordUpstreamValidationDetail, type FailureDetail } from "../request-log-failure-detail";
2
2
  import { carryProxyErrorPresentation } from "../../lib/client-error-body";
3
3
  import { carryPolicyCandidateRefusal } from "./policy-request-scope";
4
4
  import { comboFailureEvidence, carryProxyError } from "../../lib/client-error-body";
5
5
  import { carryWorkflowRefusal } from "../workflow-refusal";
6
- import { codexAccountModelRefusal, codexAccountModelRefusalHardStopCode, type CodexAccountModelRefusal } from "../../combos/failover";
6
+ import {
7
+ codexAccountModelRefusal,
8
+ codexAccountModelRefusalHardStopCode,
9
+ isMalformedResponseFormatRequest,
10
+ isOpenRouterOpaque400Envelope,
11
+ isProviderModerationRefusal,
12
+ upstreamEnvelopeRootCode,
13
+ type CodexAccountModelRefusal,
14
+ } from "../../combos/failover";
7
15
  import { parseRetryAfterMs } from "../../combos";
8
16
  import type { ConsumedComboFailure, HandleResponsesOptions } from "./core-options";
9
17
  import type { OcxUsage } from "../../types";
@@ -47,6 +55,8 @@ export async function consumeComboFailure(
47
55
  signal?: AbortSignal,
48
56
  now = Date.now(),
49
57
  logCtx?: { failureDetail?: FailureDetail; causeHint?: RequestFailureCause },
58
+ /** True only when `response` is the provider's own HTTP answer, so its closed error class is evidence. */
59
+ rawUpstream = false,
50
60
  ): Promise<ConsumedComboFailure> {
51
61
  // Read before the body: the marker lives on this Response object, and the failure below is
52
62
  // rebuilt as a new one that would otherwise lose it.
@@ -55,8 +65,12 @@ export async function consumeComboFailure(
55
65
  const fallback = `Provider error ${response.status}`;
56
66
  let classificationText = fallback;
57
67
  let codexModelRefusal: CodexAccountModelRefusal | undefined;
68
+ let malformedResponseFormat: boolean | undefined;
69
+ let openRouterOpaque400: boolean | undefined;
70
+ let providerModerationRefusal: boolean | undefined;
58
71
  let usage: OcxUsage | undefined;
59
72
  let upstreamCode: string | undefined;
73
+ let upstreamRootCode: string | undefined;
60
74
  let upstreamMessage: string | undefined;
61
75
  let upstreamType: string | undefined;
62
76
  // Whether the body itself confirms a quota/rate-limit refusal, computed on the SAME read as
@@ -85,11 +99,24 @@ export async function consumeComboFailure(
85
99
  && isRateLimitOrQuotaFailureMessage(quotaMessage);
86
100
  }
87
101
  if (body.displaySafe && !body.truncated) {
88
- if (logCtx) recordUpstreamValidationDetail(logCtx, response.status, body.text);
102
+ if (logCtx && rawUpstream) recordUpstreamProviderErrorDetail(logCtx, response.status, body.text, response);
103
+ else if (logCtx) recordUpstreamValidationDetail(logCtx, response.status, body.text);
89
104
  // A combo child's row is attributed from the same evidence the parent uses: Meta's Muse
90
105
  // Code refusal is a plan restriction, not a rejected credential (#8352).
91
106
  if (logCtx) stampMetaMusePlanRefusal(logCtx, response.status, body.text);
92
- if (response.status === 400) codexModelRefusal = codexAccountModelRefusal(response.status, body.text);
107
+ if (response.status === 400) {
108
+ codexModelRefusal = codexAccountModelRefusal(response.status, body.text);
109
+ malformedResponseFormat = isMalformedResponseFormatRequest(response.status, body.text);
110
+ openRouterOpaque400 = isOpenRouterOpaque400Envelope(body.text);
111
+ }
112
+ // Judged on the whole body: the classification text below is cut at 500 characters, and a
113
+ // hard refusal after the cut must still veto a moderation hop.
114
+ if (response.status === 400 || response.status === 422) {
115
+ providerModerationRefusal = isProviderModerationRefusal(response.status, body.text, undefined, true);
116
+ }
117
+ // Status-independent: the nested record is what normalization selects, so a root verdict
118
+ // beside it has to be captured here or the conflict rule never sees it.
119
+ upstreamRootCode = upstreamEnvelopeRootCode(body.text);
93
120
  const normalized = normalizeUpstreamErrorText(body.text, fallback);
94
121
  if (utf8Trusted || isCyberPolicyCode(normalized.code) || isCyberPolicyMessage(normalized.safeText)) {
95
122
  classificationText = normalized.safeText;
@@ -167,7 +194,13 @@ export async function consumeComboFailure(
167
194
  ...(verifiedPlanRefusal ? { verifiedPlanRefusal: true } : {}),
168
195
  classificationText,
169
196
  ...(codexModelRefusal !== undefined ? { codexModelRefusal } : {}),
197
+ ...(malformedResponseFormat !== undefined ? { malformedResponseFormat } : {}),
198
+ ...(openRouterOpaque400 !== undefined ? { openRouterOpaque400 } : {}),
199
+ ...(providerModerationRefusal !== undefined ? { providerModerationRefusal } : {}),
170
200
  ...(normalizedUpstreamCode !== undefined ? { upstreamCode: normalizedUpstreamCode } : {}),
201
+ // A rewritten identity (policy, replay refusal) is the whole verdict; the root's own code
202
+ // would only re-open a decision that rewrite already settled.
203
+ ...(!cyberFailure && !replayRefusal && upstreamRootCode !== undefined ? { upstreamRootCode } : {}),
171
204
  ...(upstreamMessage !== undefined ? { upstreamMessage } : {}),
172
205
  ...(upstreamType !== undefined ? { upstreamType } : {}),
173
206
  ...(!cyberFailure && cooldownRetryAfter !== undefined ? { retryAfter: cooldownRetryAfter } : {}),
@@ -197,8 +197,10 @@ export function createComboProtocolLanes(input: {
197
197
  if (inbound === "messages") {
198
198
  const combo = getCombo(config, comboId);
199
199
  // ponytail: exact replay supports no combo effort rewrite; the existing bridge owns those policies.
200
+ const domain = credentialDomainFor(route.provider);
200
201
  if (!combo || combo.strategy !== "failover" || comboDefaultEffort(config, comboId)
201
- || combo.reasoningEffortMode !== "strict" || !credentialDomainFor(route.provider)?.firstPartyAnthropic
202
+ || combo.reasoningEffortMode !== "strict" || !domain
203
+ || (route.provider.authMode === "oauth" && !domain.firstPartyAnthropic)
202
204
  || supportedLadderFor({ provider: route.provider, modelId: route.modelId })?.length === 0) return false;
203
205
  }
204
206
  // The concrete selector, as the bridge child's body carries it; the wire model comes from
@@ -1,3 +1,5 @@
1
+ import { responseReplayOwnerKey } from "../../responses/state/replay-owner";
2
+ import { isPlaintextV2AgentMessagesEnabled } from "../../config/multi-agent-surface";
1
3
  import { comboLogLabel, comboTargetLogLabel } from "../../combos/resolve";
2
4
  import { clientFacingModelLabel, clientFacingModelText } from "../../lib/error-destination";
3
5
  import { projectLocalModelRefusalLog } from "../request-log-failure-detail";
@@ -21,6 +23,7 @@ import {
21
23
  } from "../../reasoning-effort";
22
24
  import { admissionMayUseMeteredComboTargets, resolveAdmissionModelScope, routeAllowedByScope } from "../admission-model-scope";
23
25
  import { recordAttemptRequestedEffort } from "../request-log";
26
+ import { failLinkTurnExpansion, markLinkTurnMissing, observeLinkTurnExpansion } from "../link-turn";
24
27
  import {
25
28
  CODEX_TEXT_GUARDED_BUDGET_POLICY,
26
29
  deriveRequestExecutionBudget,
@@ -30,7 +33,7 @@ import type {
30
33
  RequestExecutionBudgetPolicy,
31
34
  RequestExecutionBudget,
32
35
  } from "../../lib/request-execution-budget";
33
- import type { OcxComboDefaultEffort, OcxConfig } from "../../types";
36
+ import type { OcxComboDefaultEffort, OcxConfig, OcxUsage } from "../../types";
34
37
  import type { RequestLogContext } from "../request-log";
35
38
  import type { HandleResponsesOptions, ResponsesDispatchers, ConsumedComboFailure } from "./core-options";
36
39
  import type { TranslatorBudget } from "../../lib/translator-budget";
@@ -62,10 +65,12 @@ import { formatErrorResponse } from "../../bridge";
62
65
  import { SEND_BUDGET_EXHAUSTED_CODE } from "../../lib/errors";
63
66
  import {
64
67
  expandPreviousResponseInput,
68
+ previousResponseRestoredPrefixLength,
65
69
  previousResponseReplayFailure,
66
70
  previousResponseProviderState,
67
71
  } from "../../responses/state";
68
72
  import { hasUnreadableEncryptedAgentTask } from "./encrypted-payload";
73
+ import { eagerCodexToolCatalogSurface, warnEagerCodexToolCatalog } from "./codex-tool-catalog";
69
74
  import { captureRouteStaticPolicy, routeConcreteModel, comboRouteDecisionTrace } from "../../router";
70
75
  import { memoryModelRouteReason } from "./memory-models";
71
76
  import { baseProviderLabel, poolAccountProviderLabel } from "../../providers/label";
@@ -126,7 +131,13 @@ import {
126
131
  } from "../relay";
127
132
  import { preflightComboStreamResponse } from "./combo-stream-preflight";
128
133
  import { requiredToolContractOf } from "./combo-required-tool-contract";
129
- import { streamingContextOverflowResponse, jsonContextOverflowResponse, lateAttributionLimitResponse } from "./context-overflow";
134
+ import {
135
+ streamingContextOverflowResponse,
136
+ jsonContextOverflowResponse,
137
+ lateAttributionLimitResponse,
138
+ jsonIncompleteResponse,
139
+ streamingIncompleteResponse,
140
+ } from "./context-overflow";
130
141
  import { mandatoryResponsesReasoningReplayUnavailable } from "./core-replay";
131
142
  import { isReplayRefusalResponse, settleOperatorReplacement, UPSTREAM_RESET_REPLAY_REFUSED_CODE } from "../../lib/upstream-retry";
132
143
  import { attributeFinalRequest } from "../request-log-failure-attribution";
@@ -437,13 +448,17 @@ export async function executeComboResponses(
437
448
  // continuation that only references prior images still fails closed when
438
449
  // imageInput is disabled (and so targets see the full replayed input).
439
450
  const inboundClientThreadId = req.headers.get("x-codex-parent-thread-id")?.trim() || undefined;
440
- const body = expandPreviousResponseInput(rawBody, inboundClientThreadId);
451
+ const inboundOwnThreadId = req.headers.get("thread-id")?.trim() || undefined;
452
+ const strictReplay = options.plaintextV2Decision ?? isPlaintextV2AgentMessagesEnabled(config);
453
+ const replayOwnerKey = strictReplay ? responseReplayOwnerKey(replayPrincipal.clientPrincipalId, inboundOwnThreadId) : undefined;
454
+ const body = expandPreviousResponseInput(rawBody, strictReplay ? inboundOwnThreadId : inboundClientThreadId, replayOwnerKey);
441
455
  const replayFailure = previousResponseReplayFailure(body);
442
456
  if (replayFailure?.reason === "scope_mismatch") {
443
457
  console.warn("[opencodex] refusing continuation because the client task scope does not match replay state");
444
458
  }
445
459
  // Local replay failures require full client replay.
446
460
  if (replayFailure) {
461
+ failLinkTurnExpansion(options.linkTurn, req, logCtx, body, replayFailure.reason);
447
462
  return formatErrorResponse(
448
463
  400,
449
464
  "previous_response_not_found",
@@ -456,10 +471,15 @@ export async function executeComboResponses(
456
471
  // object (still carrying previous_response_id) and must not be treated as
457
472
  // unresolved — text-only stored continuations remain allowed.
458
473
  const requestedPreviousId = typeof (rawBody as { previous_response_id?: unknown } | null)?.previous_response_id === "string"
459
- ? (rawBody as { previous_response_id: string }).previous_response_id.trim()
474
+ ? (rawBody as { previous_response_id: string }).previous_response_id
460
475
  : "";
461
- const unresolvedPrevious = requestedPreviousId.length > 0 && body === rawBody;
476
+ const unresolvedPrevious = requestedPreviousId.trim().length > 0 && body === rawBody;
477
+ // Remote Link (design T4 5 and 9.1): the combo's own expansion is the request's one capture point; its
478
+ // children replay a snapshot and skip theirs.
479
+ observeLinkTurnExpansion(options.linkTurn, req, logCtx, body,
480
+ requestedPreviousId.trim().length > 0 ? (unresolvedPrevious ? "unexpanded" : "chained") : "none");
462
481
  if (combo.imageInput === "disabled" && unresolvedPrevious) {
482
+ markLinkTurnMissing(logCtx);
463
483
  return formatErrorResponse(
464
484
  400,
465
485
  "previous_response_not_found",
@@ -469,6 +489,16 @@ export async function executeComboResponses(
469
489
  if (combo.imageInput === "disabled" && comboRequestHasImageInput(body)) {
470
490
  return formatErrorResponse(400, "invalid_request_error", "This combo does not accept image input");
471
491
  }
492
+ // The combo ladder owns the whole logical request, so the catalog diagnostic is counted here for
493
+ // combo-routed turns; children run as concrete selections and would otherwise never report it.
494
+ // Counting after the replay expansion keeps restored history out of the tally.
495
+ if ((options.inboundWire ?? "responses") === "responses") {
496
+ warnEagerCodexToolCatalog(body, req.headers, {
497
+ surface: eagerCodexToolCatalogSurface(body, options.compactionRecoveryKind),
498
+ replayPrefixLength: previousResponseRestoredPrefixLength(body),
499
+ logicalRequest: logCtx,
500
+ });
501
+ }
472
502
  const comboReplaySnapshot = {
473
503
  sourceBody: body,
474
504
  previousResponseInputExpanded: body !== rawBody
@@ -909,6 +939,9 @@ export async function executeComboResponses(
909
939
  // is gone, so carry the loop's own classification decision instead of re-deriving a
910
940
  // weaker one from the status alone (#4149).
911
941
  let lastFailureClassifiesOverflow = false;
942
+ let zeroOutputLimitFailure: { childLog: RequestLogContext; usage?: OcxUsage } | undefined;
943
+ let lastFailureUpstreamCode: string | undefined;
944
+ const wantsStream = (rawBody as { stream?: unknown } | null)?.stream === true || (body as { stream?: unknown } | null)?.stream === true;
912
945
  // Local input admission refusals (#1524), while every failed target so far was one: such a
913
946
  // target sent nothing, so an exhausted ladder must not be reported as a provider rejection.
914
947
  let localAdmissionRefusals: string[] | undefined = [];
@@ -928,6 +961,12 @@ export async function executeComboResponses(
928
961
  adoptFailedChildLog(contextFailure.childLog);
929
962
  return contextFailure.response;
930
963
  }
964
+ if (lastFailure && lastFailureUpstreamCode === "zero_output_token_limit" && zeroOutputLimitFailure) {
965
+ adoptFailedChildLog(zeroOutputLimitFailure.childLog);
966
+ return wantsStream
967
+ ? streamingIncompleteResponse(responseModel, zeroOutputLimitFailure.usage, "max_output_tokens", options.translatorBudget)
968
+ : jsonIncompleteResponse(responseModel, zeroOutputLimitFailure.usage, "max_output_tokens");
969
+ }
931
970
  const returnsQuota = lastFailure && [400, 401, 403].includes(lastFailure.status) && quotaFailure;
932
971
  const failedChildLog = returnsQuota ? quotaFailedChildLog : lastFailedChildLog;
933
972
  if (failedChildLog) adoptFailedChildLog(failedChildLog);
@@ -1050,7 +1089,8 @@ export async function executeComboResponses(
1050
1089
  const childLog: RequestLogContext = {
1051
1090
  model: pick.target.model,
1052
1091
  provider: pick.target.provider,
1053
- ...(logCtx.conversationId ? { conversationId: logCtx.conversationId } : {}),
1092
+ ...(logCtx.conversationId ? { conversationId: logCtx.conversationId, conversationIdIsHermesFallback: logCtx.conversationIdIsHermesFallback } : {}),
1093
+ ...(logCtx.affinityLane ? { affinityLane: logCtx.affinityLane } : {}),
1054
1094
  ...(logCtx.surface ? { surface: logCtx.surface } : {}),
1055
1095
  };
1056
1096
  const targetReasoningEfforts = supportedLadderFor({
@@ -1212,6 +1252,7 @@ export async function executeComboResponses(
1212
1252
  },
1213
1253
  }) : await requestDispatchers.handleResponses(childRequest, config, childLog, {
1214
1254
  ...options,
1255
+ plaintextV2Decision: strictReplay,
1215
1256
  replayPrincipal,
1216
1257
  // A bridge child is a concrete route; the native source belongs to this loop only.
1217
1258
  ...(options.protocolSource ? { protocolSource: undefined } : {}),
@@ -1371,7 +1412,7 @@ export async function executeComboResponses(
1371
1412
  attempt,
1372
1413
  failure.response.status,
1373
1414
  Date.now() - started,
1374
- failure.usage,
1415
+ failure.usage ?? childLog.usage,
1375
1416
  );
1376
1417
  if (isReplayRefusalResponse(failure.response)) {
1377
1418
  // Numeric 429 is a client replay policy here, not an upstream quota observation.
@@ -1387,6 +1428,7 @@ export async function executeComboResponses(
1387
1428
  }
1388
1429
  attemptRetained = true;
1389
1430
  lastFailure = failure.response;
1431
+ lastFailureUpstreamCode = failure.upstreamCode;
1390
1432
  toolChoiceRefusalsOnly = (toolChoiceRefusalsOnly ?? true) && isMandatoryToolChoiceRefusal(failure.response);
1391
1433
  // A real target failure ends the session pin; the next turn is decided afresh (#7525).
1392
1434
  jevPin?.forget();
@@ -1416,8 +1458,12 @@ export async function executeComboResponses(
1416
1458
  : isPolicyCandidateRefusal(failure.response) ? "hop"
1417
1459
  : comboFailureDecision(failure.response.status, failure.classificationText, {
1418
1460
  code: failure.upstreamCode,
1461
+ rootCode: failure.upstreamRootCode,
1419
1462
  codexModelRefusal: failure.codexModelRefusal,
1420
1463
  verifiedPlanRefusal: failure.verifiedPlanRefusal,
1464
+ malformedResponseFormat: failure.malformedResponseFormat,
1465
+ openRouterOpaque400: failure.openRouterOpaque400,
1466
+ providerModerationRefusal: failure.providerModerationRefusal,
1421
1467
  // The adapter the failed leg actually resolved: a configured `kiro` provider can route a
1422
1468
  // model through another wire via `modelAdapters`, and an unresolved leg grants no hop.
1423
1469
  failedAdapter: childLog.providerAdapter,
@@ -1475,6 +1521,12 @@ export async function executeComboResponses(
1475
1521
  contextFailure = { childLog, response: formatErrorResponse(400, "invalid_request_error",
1476
1522
  failure.upstreamMessage ?? failure.classificationText, { code: "context_length_exceeded", classified: true }) };
1477
1523
  }
1524
+ if (failure.upstreamCode === "zero_output_token_limit") {
1525
+ zeroOutputLimitFailure = {
1526
+ childLog,
1527
+ usage: failure.usage ?? childLog.usage,
1528
+ };
1529
+ }
1478
1530
  // A bare status made a revoked credential read as a provider outage. Log the classified
1479
1531
  // condition (a closed member), never upstream-authored code or message text.
1480
1532
  const failureReason = classifyUpstreamCondition({
@@ -1488,6 +1540,9 @@ export async function executeComboResponses(
1488
1540
  const attemptedTargets = pick.attempted;
1489
1541
  const failureCooldownScope = isPolicyCandidateRefusal(failure.response) ? "none" : comboFailureCooldownScope(failure.response.status, failure.classificationText, {
1490
1542
  code: failure.upstreamCode,
1543
+ malformedResponseFormat: failure.malformedResponseFormat,
1544
+ openRouterOpaque400: failure.openRouterOpaque400,
1545
+ providerModerationRefusal: failure.providerModerationRefusal,
1491
1546
  });
1492
1547
  const failedTargetKey = targetKey(pick.target);
1493
1548
  let failedTargetCooldownRecorded = false;
@@ -1,6 +1,6 @@
1
1
  import type { ComboExclusionReasons } from "../../combos/resolve";
2
2
  import { markProxyError } from "../../lib/client-error-body";
3
- import { formatClientRetryAfter } from "../../lib/client-retry-after";
3
+ import { appendClientRetryIn, formatClientRetryAfter } from "../../lib/client-retry-after";
4
4
  import { readBoundedResponseBody } from "../../lib/bounded-body";
5
5
  import { redactSecretString } from "../../lib/redact";
6
6
  import { isCyberPolicyMessage, isCyberPolicyCode } from "../../lib/errors";
@@ -70,7 +70,9 @@ export function normalizeUpstreamErrorText(text: string, fallback: string): Norm
70
70
  message = redactSecretString(source.message.trim()).slice(0, 500);
71
71
  }
72
72
  if (typeof source.type === "string" && source.type.trim()) type = source.type.trim();
73
- if (typeof source.code === "string" && source.code.trim()) code = source.code.trim();
73
+ if (typeof source.code === "string" && source.code.trim()) {
74
+ code = source.code.trim();
75
+ }
74
76
  } catch {
75
77
  /* non-JSON upstream body — retain the bounded display-safe text */
76
78
  }
@@ -108,9 +110,12 @@ export function comboUnavailableResponse(
108
110
  // Advice leaves in this proxy's format, whatever form the earliest cooldown was recorded in.
109
111
  const advice = formatClientRetryAfter(options?.retryAfter);
110
112
  if (advice !== undefined) headers.set("Retry-After", advice);
113
+ // Name the earliest recovery in the body too: a client that drops the header still
114
+ // shows the user how long the combo stays cooled.
111
115
  return markProxyError(new Response(
112
116
  JSON.stringify({
113
- error: { message, type: "server_error", code: "combo_unavailable" },
117
+ // Built from the header value itself, so an HTTP-date cannot make the body and header disagree.
118
+ error: { message: appendClientRetryIn(message, advice), type: "server_error", code: "combo_unavailable" },
114
119
  }),
115
120
  { status: 503, headers },
116
121
  ), options?.presentation);
@@ -3,6 +3,7 @@ import type { TranslatorBudget } from "../../lib/translator-budget";
3
3
  import { carryResponseToolOwnership } from "./response-tool-ownership";
4
4
  import { carryPolicyCandidateRefusal } from "./policy-request-scope";
5
5
  import { finalizeTranslatorBudgetResponse } from "../../lib/translator-budget";
6
+ import { carryPacedStream, pacedQueuingStrategy } from "../../lib/paced-stream";
6
7
  import { carryReplayRefusal, isNonReplayableResponse, markResponseNonReplayable } from "../../lib/upstream-retry";
7
8
  import { isVerifiedModelNotInPlanResponse, markVerifiedModelNotInPlanResponse } from "../../lib/errors";
8
9
  import { carryCodexAccountCooldownResponse } from "../../codex/account-cooldown-response";
@@ -68,7 +69,7 @@ export function finalizeAccountLease(response: Response, release: () => void, on
68
69
  const reader = response.body.getReader();
69
70
  let done = false;
70
71
  const finish = () => { if (!done) { done = true; release(); } };
71
- const body = new ReadableStream<Uint8Array>({
72
+ const body = carryPacedStream(response.body, new ReadableStream<Uint8Array>({
72
73
  async pull(controller) {
73
74
  try {
74
75
  const next = await reader.read();
@@ -77,7 +78,7 @@ export function finalizeAccountLease(response: Response, release: () => void, on
77
78
  } catch (error) { finish(); controller.error(error); }
78
79
  },
79
80
  async cancel(reason) { onCancel?.(); try { await reader.cancel(reason); } finally { finish(); } },
80
- });
81
+ }, pacedQueuingStrategy(response.body)));
81
82
  const wrapped = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
82
83
  carryProxyError(response, wrapped);
83
84
  if (isNonReplayableResponse(response)) markResponseNonReplayable(wrapped);