@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
@@ -110,6 +110,10 @@ export function predictCursorEffort(
110
110
  }
111
111
 
112
112
  export interface ModelCapabilityInput {
113
+ supportsReasoning?: boolean;
114
+ supportsThinkingToggle?: boolean;
115
+ supportsReasoningEffort?: boolean;
116
+ defaultThinkingEnabled?: boolean;
113
117
  reasoningEfforts?: readonly string[];
114
118
  contextWindow?: number;
115
119
  /**
@@ -133,7 +137,10 @@ export interface ModelCapabilityFields {
133
137
  input_modalities?: string[];
134
138
  supports_tool_use: true;
135
139
  supports_streaming: true;
136
- supports_reasoning: boolean;
140
+ supports_reasoning?: boolean;
141
+ supports_thinking_toggle?: boolean;
142
+ supports_reasoning_effort?: boolean;
143
+ default_thinking_enabled?: boolean;
137
144
  supports_vision?: boolean;
138
145
  reasoning_effort?: string[];
139
146
  };
@@ -166,7 +173,15 @@ function positiveInt(value: unknown): number | undefined {
166
173
  }
167
174
 
168
175
  export function modelCapabilityFields(input: ModelCapabilityInput): ModelCapabilityFields {
169
- const efforts = (input.reasoningEfforts ?? []).filter(effort => typeof effort === "string" && effort.length > 0);
176
+ const efforts = input.supportsReasoning === false || input.supportsReasoningEffort === false ? []
177
+ : (input.reasoningEfforts ?? []).filter(effort => typeof effort === "string" && effort.length > 0);
178
+ // Legacy discovery used an explicit empty ladder to withhold Cursor reasoning controls.
179
+ // Independent capability declarations replace that compatibility inference per axis.
180
+ const legacyEmptyLadder = input.reasoningEfforts?.length === 0
181
+ && input.supportsThinkingToggle === undefined && input.supportsReasoningEffort === undefined;
182
+ const supportsReasoning = input.supportsReasoning
183
+ ?? (input.supportsThinkingToggle === true || input.supportsReasoningEffort === true || efforts.length > 0
184
+ ? true : legacyEmptyLadder ? false : undefined);
170
185
  const contextLength = positiveInt(input.contextWindow);
171
186
  const longContextLength = positiveInt(input.longContextWindow);
172
187
  const maxOutputTokens = positiveInt(input.maxOutputTokens);
@@ -187,7 +202,10 @@ export function modelCapabilityFields(input: ModelCapabilityInput): ModelCapabil
187
202
  ...(modalities !== undefined && modalities.length > 0 ? { input_modalities: [...modalities] } : {}),
188
203
  supports_tool_use: true,
189
204
  supports_streaming: true,
190
- supports_reasoning: efforts.length > 0,
205
+ ...(supportsReasoning !== undefined ? { supports_reasoning: supportsReasoning } : {}),
206
+ ...(input.supportsThinkingToggle !== undefined ? { supports_thinking_toggle: input.supportsThinkingToggle } : {}),
207
+ ...(input.supportsReasoningEffort !== undefined ? { supports_reasoning_effort: input.supportsReasoningEffort } : {}),
208
+ ...(input.defaultThinkingEnabled !== undefined ? { default_thinking_enabled: input.defaultThinkingEnabled } : {}),
191
209
  ...(supportsVision !== undefined ? { supports_vision: supportsVision } : {}),
192
210
  ...(efforts.length > 0 ? { reasoning_effort: [...efforts] } : {}),
193
211
  },
@@ -405,22 +405,37 @@ async function runOwnerLookup(file: string, args: string[], timeoutMs: number):
405
405
  return stdout;
406
406
  }
407
407
 
408
+ export type LoopbackOwnerLookupResult = {
409
+ kind: "match" | "mismatch" | "lookup_error" | "deadline";
410
+ elapsedMs: number;
411
+ };
412
+
408
413
  export interface LoopbackOwnerLookupIo {
409
414
  platform?: NodeJS.Platform;
415
+ nowMs?: () => number;
416
+ scheduleDeadline?: (callback: () => void, timeoutMs: number) => () => void;
410
417
  readProc?: (path: string) => Promise<string>;
411
418
  listFds?: (path: string) => Promise<string[]>;
412
419
  readFdLink?: (path: string) => Promise<string>;
413
420
  run?: (file: string, args: string[], timeoutMs: number) => Promise<string>;
414
421
  }
415
422
 
416
- /** Async, bounded proof that this PID owns the IPv4 loopback LISTEN socket used by the relay. */
417
- export async function ownsIpv4LoopbackListener(
423
+ /**
424
+ * Classify fresh IPv4 loopback LISTEN ownership within the bounded lookup deadline.
425
+ * Only match proves the expected PID; mismatch, inspection failure and timeout remain distinct.
426
+ * elapsedMs uses a monotonic clock by default, and no raw OS output is returned.
427
+ */
428
+ export async function inspectIpv4LoopbackListener(
418
429
  port: number,
419
430
  expectedPid: number,
420
431
  io: LoopbackOwnerLookupIo = {},
421
- ): Promise<boolean> {
432
+ ): Promise<LoopbackOwnerLookupResult> {
433
+ const now = io.nowMs ?? (() => performance.now());
434
+ const startedAt = now();
435
+ const result = (kind: LoopbackOwnerLookupResult["kind"]): LoopbackOwnerLookupResult =>
436
+ ({ kind, elapsedMs: Math.max(0, now() - startedAt) });
422
437
  if (!Number.isInteger(port) || port < 1 || port > 65535
423
- || !Number.isSafeInteger(expectedPid) || expectedPid < 1) return false;
438
+ || !Number.isSafeInteger(expectedPid) || expectedPid < 1) return result("mismatch");
424
439
  const platform = io.platform ?? process.platform;
425
440
  const lookup = async (): Promise<boolean> => {
426
441
  if (platform === "linux") {
@@ -458,13 +473,40 @@ export async function ownsIpv4LoopbackListener(
458
473
  }
459
474
  return false;
460
475
  };
461
- let timer: ReturnType<typeof setTimeout> | undefined;
462
- const deadline = new Promise<false>(resolve => {
463
- timer = setTimeout(() => resolve(false), OWNER_LOOKUP_TIMEOUT_MS);
476
+ const scheduleDeadline = io.scheduleDeadline ?? ((callback, timeoutMs) => {
477
+ const timer = setTimeout(callback, timeoutMs);
464
478
  timer.unref?.();
479
+ return () => clearTimeout(timer);
465
480
  });
466
- try { return await Promise.race([lookup().catch(() => false), deadline]); }
467
- finally { if (timer) clearTimeout(timer); }
481
+ let cancelDeadline: (() => void) | undefined;
482
+ const deadline = new Promise<LoopbackOwnerLookupResult["kind"]>(resolve => {
483
+ cancelDeadline = scheduleDeadline(() => resolve("deadline"), OWNER_LOOKUP_TIMEOUT_MS);
484
+ });
485
+ const inspected = lookup().then(
486
+ matches => matches ? "match" as const : "mismatch" as const,
487
+ error => {
488
+ const failure = error as {
489
+ killed?: boolean; signal?: string | null; code?: unknown; stdout?: unknown; stderr?: unknown;
490
+ } | null;
491
+ // lsof exits 1 with no output when no socket matches its selectors.
492
+ if (platform === "darwin" && failure?.code === 1 && !failure.killed
493
+ && failure.signal == null && failure.stdout === "" && failure.stderr === "") return "mismatch" as const;
494
+ // execFile's timeout kills with SIGTERM; other spawn/exit/buffer errors are lookup failures.
495
+ return failure?.killed === true && failure.signal === "SIGTERM" && failure.code === null
496
+ ? "deadline" as const : "lookup_error" as const;
497
+ },
498
+ );
499
+ try { return result(await Promise.race([inspected, deadline])); }
500
+ finally { cancelDeadline?.(); }
501
+ }
502
+
503
+ /** Boolean compatibility API: only a proven match admits the listener. */
504
+ export async function ownsIpv4LoopbackListener(
505
+ port: number,
506
+ expectedPid: number,
507
+ io: LoopbackOwnerLookupIo = {},
508
+ ): Promise<boolean> {
509
+ return (await inspectIpv4LoopbackListener(port, expectedPid, io)).kind === "match";
468
510
  }
469
511
 
470
512
  /**
@@ -172,6 +172,55 @@ export function conversationIdFromResponsesRequest(input: {
172
172
  );
173
173
  }
174
174
 
175
+ /**
176
+ * Hermes Agent session affinity header for log correlation (#330).
177
+ * Kept separate from runtime/session identities so it cannot affect lanes or routing.
178
+ */
179
+ export function conversationIdFromHermesHeader(headers: Headers): string | undefined {
180
+ return normalizeLogConversationId(headers.get("x-hermes-conversation-id"));
181
+ }
182
+
183
+ /**
184
+ * Validates and normalizes native header candidates in priority order for logging:
185
+ * parent-thread -> session_id -> session-id -> thread-id.
186
+ * Each candidate spelling is evaluated and normalized independently so an empty or
187
+ * whitespace-only candidate (e.g. empty session_id) cannot suppress a subsequent valid candidate.
188
+ */
189
+ export function nativeLogConversationIdFromHeaders(headers: Headers): string | undefined {
190
+ return (
191
+ normalizeLogConversationId(headers.get("x-codex-parent-thread-id")) ??
192
+ normalizeLogConversationId(headers.get("session_id")) ??
193
+ normalizeLogConversationId(headers.get("session-id")) ??
194
+ normalizeLogConversationId(headers.get("thread-id"))
195
+ );
196
+ }
197
+
198
+ /** The request-log context's conversation slot; structural so callers need not import request-log. */
199
+ export interface LogConversationSlot {
200
+ conversationId?: string;
201
+ conversationIdIsHermesFallback?: boolean;
202
+ }
203
+
204
+ /**
205
+ * Record a native log identity. Fills an empty slot or replaces the log-only Hermes fallback,
206
+ * so a native id found late (Responses preparation, a Cursor conversation created mid-turn)
207
+ * still wins. A caller-owned id already in the slot (routed Claude metadata) is kept.
208
+ */
209
+ export function assignNativeLogConversationId(slot: LogConversationSlot, nativeId: string | undefined): void {
210
+ if (!nativeId || (slot.conversationId && !slot.conversationIdIsHermesFallback)) return;
211
+ slot.conversationId = nativeId;
212
+ delete slot.conversationIdIsHermesFallback;
213
+ }
214
+
215
+ /** Fill an empty slot with the log-only Hermes digest, marked so any native id replaces it. */
216
+ export function fillHermesLogConversationFallback(slot: LogConversationSlot, headers: Headers): void {
217
+ if (slot.conversationId) return;
218
+ const hermes = conversationIdFromHermesHeader(headers);
219
+ if (!hermes) return;
220
+ slot.conversationId = hermes;
221
+ slot.conversationIdIsHermesFallback = true;
222
+ }
223
+
175
224
  /**
176
225
  * Claude Code metadata.user_id only — never the system-hash Desktop fallback.
177
226
  * Hashes the raw user_id once (same opacity goal as inbound prompt_cache_key).
@@ -150,6 +150,8 @@ export interface RequestLogContext extends UpstreamErrorDiagnostics {
150
150
  lastOutputAt?: number;
151
151
  /** Best-effort chat/session correlation for Logs grouping (#330). Opaque; omit when unknown. */
152
152
  conversationId?: string;
153
+ /** In-memory only: conversationId holds the log-only Hermes digest, which a native id replaces. */
154
+ conversationIdIsHermesFallback?: boolean;
153
155
  surface?: "claude" | "claude-desktop" | "grok";
154
156
  /** The matched configured key's id. Set ONLY for admissionKind "configured" —
155
157
  * never a sentinel, so a hand-edited entry whose id happens to be "loopback"
@@ -28,6 +28,7 @@ import { sanitizeNonReplayableUpstreamError } from "./non-replayable-error";
28
28
  import { isNonReplayableResponse } from "../../lib/upstream-retry";
29
29
  import { isCanonicalOpenAiForwardProvider } from "../../providers/openai-tiers";
30
30
  import { guardEmptyToolCatalogEvents, guardEmptyToolCatalogStream } from "../../lib/empty-tool-catalog";
31
+ import { guardCompactionSummary } from "../../responses/compaction-summary";
31
32
 
32
33
  /** One responsibility of the Responses request pipeline; state owners are explicit. */
33
34
  export async function deliverAdapterResponse(
@@ -183,7 +184,9 @@ export async function deliverAdapterResponse(
183
184
  continuation: fetchGuardedEmptyCompletionRetry,
184
185
  })
185
186
  : advisorStream;
186
- const guardedEventStream = guardEmptyToolCatalogStream(completionGuardedEventStream, clientToolCatalog, translatorBudget);
187
+ const catalogGuardedEventStream = guardEmptyToolCatalogStream(completionGuardedEventStream, clientToolCatalog, translatorBudget);
188
+ const guardedEventStream = routedCompaction && transportState.activeAdapter.name === "anthropic"
189
+ ? guardCompactionSummary(catalogGuardedEventStream, translatorBudget) : catalogGuardedEventStream;
187
190
  const { toolNsMap, declaredToolNames, toolParameterSchemas, freeformToolNames, bareCustomToolNames, toolSearchToolNames } = deliveryToolBridgeMaps;
188
191
  // One completion owner for both deliveries: the bridge calls it from its terminal, the
189
192
  // direct client encoder from the fold of the same events.
@@ -329,6 +332,13 @@ export async function deliverAdapterResponse(
329
332
  } else {
330
333
  events = guardedEvents;
331
334
  }
335
+ if (routedCompaction && transportState.activeAdapter.name === "anthropic") {
336
+ const summaryEvents: AdapterEvent[] = [];
337
+ for await (const event of guardCompactionSummary((async function* () { yield* events; })(), translatorBudget)) {
338
+ summaryEvents.push(event);
339
+ }
340
+ events = summaryEvents;
341
+ }
332
342
  } catch (error) {
333
343
  if (error instanceof ResponseBodyInactivityError) {
334
344
  return formatErrorResponse(504, "upstream_error", "Upstream response body stalled before completing");
@@ -20,7 +20,7 @@ import type { ResponsesSendBudget } from "./request-send-budget";
20
20
  import { linkAbortSignal } from "./core-lifetime";
21
21
  import type { AdapterRequest } from "../../adapters/base";
22
22
  import type { AdapterEvent } from "../../types";
23
- import { bridgeToResponsesSSE, buildResponseJSON, formatErrorResponse } from "../../bridge";
23
+ import { bridgeToResponsesSSE, buildResponseJSON, formatErrorResponse, formatUpstreamFailureResponse } from "../../bridge";
24
24
  import { trackStreamLifetime } from "../lifecycle";
25
25
  import {
26
26
  recordAdapterReasoning,
@@ -1962,7 +1962,7 @@ export async function prepareAdapterExchange(
1962
1962
  upstreamRetryAfter,
1963
1963
  includeDefault: !(transportState.anthropicPoolAccountId && classifyAnthropic429(upstreamResponse.headers) === "request-scoped-unknown"),
1964
1964
  });
1965
- return formatErrorResponse(
1965
+ return formatUpstreamFailureResponse(upstreamResponse, normalized.code,
1966
1966
  upstreamResponse.status,
1967
1967
  normalized.cyberPolicy ? (normalized.type ?? CYBER_POLICY_ERROR_CODE) : "upstream_error",
1968
1968
  message,
@@ -130,6 +130,7 @@ export function createAnthropicThinkingRecovery(
130
130
  || response.status !== "completed" || !Array.isArray(response.output) || response.output.length === 0
131
131
  || !rejectedScope
132
132
  || rejectedScope.clientThreadId !== parsed._reasoningReplayScope?.clientThreadId
133
+ || rejectedScope.clientPrincipalId !== parsed._reasoningReplayScope?.clientPrincipalId
133
134
  || JSON.stringify(rejectedScope.current) !== JSON.stringify(parsed._reasoningReplayScope?.current)) return;
134
135
  remembered = true;
135
136
  rememberReasoningReplayOpaqueBlobRejection(rejectedScope, rejectedPayloads);
@@ -8,7 +8,8 @@ import { CodexWsMetadata, type CodexWsQuotaObserver } from "./codex-ws-metadata"
8
8
  import { CODEX_RESPONSES_HTTP_URL, type PreparedCodexWsRequest } from "./codex-ws-request";
9
9
  import { CodexWsCorrelation } from "./codex-ws-correlation";
10
10
  import type { CodexWsSession } from "./codex-ws-session";
11
- import { UPGRADE_DEADLINE_MS, CODEX_WS_LIVENESS_PING_INTERVAL_MS, CODEX_WS_RESPONSE_PRELUDE_TIMEOUT_MS, MAX_CODEX_WS_FRAME_BYTES,
11
+ import { UPGRADE_DEADLINE_MS, CODEX_WS_LIVENESS_PING_INTERVAL_MS, CODEX_WS_RESPONSE_PRELUDE_TIMEOUT_MS,
12
+ CODEX_WS_COMMITTED_SILENT_INTERVALS, MAX_CODEX_WS_FRAME_BYTES,
12
13
  MAX_CODEX_WS_QUEUE_BYTES, markCodexWsResponse, markCodexWsPreludeProjection, normalizeResponsesWsRelayEvent, closedBeforeTerminalMessage,
13
14
  codexWsCreateFrameExceedsLimit, codexWsFailureDetail, codexWsPreResponseFailure, markCodexWsStage, codexWsOcxVersion,
14
15
  markCodexWsSocketDeath, codexWsWrapperStatus, isCodexWsTerminalEvent, type CodexWsFailureStage, type CodexWsStageRecord,
@@ -155,8 +156,11 @@ export function codexWsExchange(options: ExchangeOptions): Promise<Response> {
155
156
  // Liveness while waiting for the first response event (metadata path only): the
156
157
  // silence timer is re-armed by every inbound frame or pong; the pinger runs on a fixed
157
158
  // interval so a peer that answers pings can never trip the silence bound while alive.
159
+ // After the commit, each ping tick checks whether any frame or pong arrived since the last.
158
160
  let silenceTimer: ReturnType<typeof setTimeout> | undefined;
159
161
  let pingTimer: ReturnType<typeof setTimeout> | undefined;
162
+ let inboundAtLastTick = 0;
163
+ let silentIntervals = 0;
160
164
  // The resolved 200, retained so a later body failure can replace its
161
165
  // success-shaped stage record with the failure-shaped one (#4191).
162
166
  let committedResponse: Response | null = null;
@@ -260,6 +264,7 @@ export function codexWsExchange(options: ExchangeOptions): Promise<Response> {
260
264
  markCodexWsStage(response, stageRecord(null));
261
265
  committedResponse = response;
262
266
  resolve(response);
267
+ startCommittedLiveness();
263
268
  };
264
269
 
265
270
  /**
@@ -377,18 +382,40 @@ export function codexWsExchange(options: ExchangeOptions): Promise<Response> {
377
382
  CODEX_WS_RESPONSE_PRELUDE_TIMEOUT_MS,
378
383
  );
379
384
  };
380
- /** Ping on a fixed interval until the response starts; a socket without ping() is never pinged. */
385
+ const pingable = () => typeof (ws as WebSocket & { ping?: unknown }).ping === "function";
386
+ /** False when ping() threw. It may also close the socket and settle the exchange. */
387
+ const sendPing = (): boolean => {
388
+ if (!pingable()) return false;
389
+ try { (ws as WebSocket & { ping: (data?: string) => void }).ping(); } catch { return false; }
390
+ pings += 1;
391
+ return true;
392
+ };
393
+ /** Ping on a fixed interval for the life of the exchange; a socket without ping() is never pinged. */
381
394
  const schedulePing = () => {
382
- const ping = (ws as WebSocket & { ping?: (data?: string) => void }).ping;
383
- if (typeof ping !== "function" || responseCommitted || terminal) return;
395
+ if (!pingable() || terminal) return;
384
396
  pingTimer = setTimeout(() => {
385
- if (responseCommitted || terminal) return;
386
- try { ping.call(ws); } catch { return; }
387
- pings += 1;
388
- // ping() may close the socket synchronously and settle the exchange; re-check.
397
+ if (terminal) return;
398
+ if (responseCommitted && pongs > 0) {
399
+ const inbound = upstreamFrames + pongs;
400
+ silentIntervals = inbound === inboundAtLastTick ? silentIntervals + 1 : 0;
401
+ inboundAtLastTick = inbound;
402
+ if (silentIntervals >= CODEX_WS_COMMITTED_SILENT_INTERVALS) {
403
+ failStream(`codex websocket stopped answering after the response started${codexWsFailureDetail(failureStage())}`);
404
+ return;
405
+ }
406
+ }
407
+ sendPing();
389
408
  if (!terminal) schedulePing();
390
409
  }, CODEX_WS_LIVENESS_PING_INTERVAL_MS);
391
410
  };
411
+ /** Only a peer that has ponged is judged by its silence, so probe again if none has yet. */
412
+ const startCommittedLiveness = () => {
413
+ if (!metadata || terminal || !pingable()) return;
414
+ inboundAtLastTick = upstreamFrames + pongs;
415
+ silentIntervals = 0;
416
+ if (pongs === 0) sendPing();
417
+ if (!terminal) schedulePing();
418
+ };
392
419
  const onPong = () => {
393
420
  if (terminal) return;
394
421
  pongs += 1;
@@ -559,7 +586,10 @@ export function codexWsExchange(options: ExchangeOptions): Promise<Response> {
559
586
  if (!metadata) commitResponse();
560
587
  else if (!responseCommitted && !terminal) {
561
588
  armSilence();
562
- schedulePing();
589
+ // Probe now, not one interval in: the path can die seconds after the send, before a
590
+ // held commit, and the committed check needs a pong from before that.
591
+ sendPing();
592
+ if (!terminal) schedulePing();
563
593
  }
564
594
  };
565
595
 
@@ -1,6 +1,43 @@
1
1
  import { readCodexWsUpgradeHeaders } from "./codex-ws-metadata";
2
2
 
3
3
  export const MAX_CODEX_WS_SESSION_EXCHANGES = 32;
4
+ export const CODEX_WS_SESSION_CLOSE_GRACE_MS = 1_000;
5
+
6
+ /** A disposed lease must not leave a private socket waiting on an unresponsive peer. */
7
+ function closeSessionSocket(socket: WebSocket & { terminate?: () => void }, immediate: boolean): void {
8
+ if (immediate) {
9
+ // Preserve the retained pool's immediate physical-capacity release.
10
+ try { socket.close(); } catch { /* already closing */ }
11
+ try { socket.terminate?.(); } catch { /* already closed */ }
12
+ return;
13
+ }
14
+ if (socket.readyState === 3) return;
15
+ if (typeof socket.terminate !== "function") {
16
+ // A close observer cannot force teardown without the optional native method.
17
+ try { socket.close(); } catch { /* best-effort graceful teardown */ }
18
+ return;
19
+ }
20
+ let timer: ReturnType<typeof setTimeout> | undefined;
21
+ const cleanup = (): void => {
22
+ if (timer !== undefined) clearTimeout(timer);
23
+ timer = undefined;
24
+ socket.removeEventListener("close", cleanup);
25
+ };
26
+ const terminate = (): void => {
27
+ cleanup();
28
+ if (socket.readyState !== 3) {
29
+ try { socket.terminate?.(); } catch { /* best-effort physical teardown */ }
30
+ }
31
+ };
32
+ // Install before close(): older runtimes and test peers may close synchronously.
33
+ // Capture only the socket, not the disposed session or its former exchange owner.
34
+ socket.addEventListener("close", cleanup, { once: true });
35
+ timer = setTimeout(terminate, CODEX_WS_SESSION_CLOSE_GRACE_MS);
36
+ timer.unref?.();
37
+ try { socket.close(); } catch { terminate(); }
38
+ // close() may synchronously change the state narrowed by the earlier guard.
39
+ if ((socket.readyState as number) === 3) cleanup();
40
+ }
4
41
 
5
42
  /** Owns one physical socket; request listeners belong to the exchange, not this object. */
6
43
  export class CodexWsSession {
@@ -69,10 +106,7 @@ export class CodexWsSession {
69
106
  try { owner?.(reason); } finally {
70
107
  this.busy = false;
71
108
  this.completedIds.clear();
72
- try { this.socket.close(); } catch { /* already closing */ }
73
- if (this.retainable) {
74
- try { (this.socket as WebSocket & { terminate?: () => void }).terminate?.(); } catch { /* already closed */ }
75
- }
109
+ closeSessionSocket(this.socket, this.retainable);
76
110
  this.changed();
77
111
  }
78
112
  }
@@ -25,6 +25,11 @@ export const UPGRADE_DEADLINE_MS = 10_000;
25
25
  // keeps exactly the previous 90 s bound; a peer that does can never trip it while alive.
26
26
  export const CODEX_WS_LIVENESS_PING_INTERVAL_MS = 15_000;
27
27
  export const CODEX_WS_RESPONSE_PRELUDE_TIMEOUT_MS = 90_000;
28
+ // The pinger keeps running after the commit: a tunnel restart or Wi-Fi rejoin can drop the path
29
+ // without a FIN or RST, and codex-rs would wait out its 300 s idle timeout. A peer that has ponged
30
+ // and then sends no frame and no pong for this many intervals is gone, and the stream fails so the
31
+ // client retries. One missed pong is not a verdict.
32
+ export const CODEX_WS_COMMITTED_SILENT_INTERVALS = 2;
28
33
  // Keep the push-based WS transport inside the same memory envelope as the
29
34
  // bounded SSE relays that consume this response. Unlike fetch response bodies,
30
35
  // a WebSocket cannot be paused when a ReadableStream applies backpressure, so
@@ -404,7 +409,7 @@ export type CodexWsFailureStage = {
404
409
  firstResponseMs: number | null;
405
410
  /** Milliseconds from send to this failure; null when the failure predates the send. */
406
411
  elapsedMs: number | null;
407
- /** Liveness pings the exchange sent while waiting for the first response event. */
412
+ /** Liveness pings the exchange sent, before and after the first response event. */
408
413
  pings: number;
409
414
  /** Pongs the peer answered with; zero on a peer that never answers pings. */
410
415
  pongs: number;
@@ -0,0 +1,103 @@
1
+ import { REQUIRED_TOOL_CONTRACT_CODE } from "../../lib/errors";
2
+ import { applyReplayRefusalClientHeaders, isNonReplayableResponse, markResponseNonReplayable } from "../../lib/upstream-retry";
3
+ import { clientWireOf } from "../inference/client-wire";
4
+ import { isPreinspectedJsonResponse, markPreinspectedJsonResponse } from "../relay";
5
+ import { isAuthorizedProviderExecutedCall } from "../responses-undeclared-tool-guard";
6
+ import { carryResponseToolOwnership, responseToolOwnership } from "./response-tool-ownership";
7
+
8
+ export type RequiredToolContract =
9
+ | { kind: "any"; hostedCallTypes: ReadonlySet<string> }
10
+ | { kind: "named"; name: string };
11
+
12
+ const hostedCalls = new Map([
13
+ ["web_search", "web_search_call"], ["web_search_preview", "web_search_call"],
14
+ ["file_search", "file_search_call"], ["code_interpreter", "code_interpreter_call"],
15
+ ["image_generation", "image_generation_call"], ["image_gen", "image_generation_call"],
16
+ ["mcp", "mcp_call"], ["computer_use", "computer_call"],
17
+ ["computer_use_preview", "computer_call"],
18
+ ]);
19
+
20
+ /** Unknown declarations abstain: their successful output spelling is not ours to guess. */
21
+ export function requiredToolContractOf(rawBody: unknown): RequiredToolContract | undefined {
22
+ if (!rawBody || typeof rawBody !== "object" || Array.isArray(rawBody)) return;
23
+ const { tools, tool_choice: choice } = rawBody as Record<string, unknown>;
24
+ if (!Array.isArray(tools) || tools.length === 0) return;
25
+ if (choice === "required") {
26
+ const hostedCallTypes = new Set<string>();
27
+ for (const tool of tools) {
28
+ if (!tool || typeof tool !== "object" || Array.isArray(tool)) return;
29
+ const type = (tool as Record<string, unknown>).type;
30
+ if (type === "function" || type === "custom") continue;
31
+ const callType = typeof type === "string" ? hostedCalls.get(type) : undefined;
32
+ if (!callType) return;
33
+ hostedCallTypes.add(callType);
34
+ }
35
+ return { kind: "any", hostedCallTypes };
36
+ }
37
+ if (choice && typeof choice === "object" && !Array.isArray(choice)) {
38
+ const named = choice as Record<string, unknown>;
39
+ if ((named.type === "function" || named.type === "custom")
40
+ && typeof named.name === "string" && named.name.trim()) {
41
+ return { kind: "named", name: named.name };
42
+ }
43
+ }
44
+ }
45
+
46
+ /** Only a parsed completed output array can prove a missing required call. */
47
+ export async function judgeBufferedRequiredTool(response: Response, requirement: RequiredToolContract): Promise<Response> {
48
+ const text = await response.text();
49
+ let payload: Record<string, unknown> | undefined;
50
+ try {
51
+ const parsed: unknown = JSON.parse(text);
52
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) payload = parsed as Record<string, unknown>;
53
+ } catch { /* An opaque body is not evidence of a required-tool violation. */ }
54
+ const output = payload?.output;
55
+ if (payload?.status === "completed" && Array.isArray(output)) {
56
+ const calls = output.filter((item): item is Record<string, unknown> =>
57
+ !!item && typeof item === "object" && !Array.isArray(item));
58
+ const ownership = responseToolOwnership(response);
59
+ const providerExecuted = (call: Record<string, unknown>) =>
60
+ ownership !== undefined && isAuthorizedProviderExecutedCall(call, ownership);
61
+ const satisfied = calls.some(call => {
62
+ if (requirement.kind === "any" && requirement.hostedCallTypes.has(String(call.type))) return true;
63
+ if (providerExecuted(call)) return false;
64
+ if (call.type !== "function_call" && call.type !== "custom_tool_call") return false;
65
+ // Name-less calls cannot prove a selected-name mismatch.
66
+ return requirement.kind === "any" || typeof call.name !== "string" || call.name === requirement.name;
67
+ });
68
+ if (!satisfied) {
69
+ const hostedEffect = calls.some(call => providerExecuted(call)
70
+ || (typeof call.type === "string" && call.type.endsWith("_call")
71
+ && call.type !== "function_call" && call.type !== "custom_tool_call"));
72
+ const failure = Response.json({
73
+ error: {
74
+ type: "upstream_error", code: REQUIRED_TOOL_CONTRACT_CODE,
75
+ message: "Target completed the response without the tool call required by tool_choice",
76
+ },
77
+ ...(payload.usage !== undefined ? { usage: payload.usage } : {}),
78
+ }, { status: hostedEffect ? 400 : 502 });
79
+ // Hosted/unknown call items can already have executed remotely. Report the violation,
80
+ // but never buy another execution merely because the required client call is missing.
81
+ if (hostedEffect) {
82
+ markResponseNonReplayable(failure);
83
+ applyReplayRefusalClientHeaders(failure.headers);
84
+ }
85
+ return failure;
86
+ }
87
+ }
88
+ const headers = new Headers(response.headers);
89
+ headers.delete("content-encoding");
90
+ headers.delete("content-length");
91
+ const rebuilt = new Response(text, { status: response.status, statusText: response.statusText, headers });
92
+ if (isPreinspectedJsonResponse(response)) markPreinspectedJsonResponse(rebuilt);
93
+ return carryResponseToolOwnership(response, rebuilt);
94
+ }
95
+
96
+ /** Native buffered Responses only; translated Chat and runTurn retain their terminal owners. */
97
+ export async function guardBufferedComboRequiredTool(response: Response, rawBody: unknown, adapter?: string): Promise<Response> {
98
+ if (!response.ok || adapter !== "openai-responses" || clientWireOf(response) !== undefined
99
+ || isNonReplayableResponse(response)
100
+ || !(response.headers.get("content-type") ?? "").includes("application/json")) return response;
101
+ const requirement = requiredToolContractOf(rawBody);
102
+ return requirement ? judgeBufferedRequiredTool(response, requirement) : response;
103
+ }
@@ -29,6 +29,10 @@ const TERMINAL_EVENTS = new Set([
29
29
  "response.incomplete",
30
30
  ]);
31
31
 
32
+ // A failed terminal carrying one of these codes is a contract verdict, not a transient
33
+ // upstream failure: another target would spend a request the adapter already refused.
34
+ const NON_REPLAYABLE_FAILED_CODES = new Set(["required_tool_not_called"]);
35
+
32
36
  const RETRYABLE_ZERO_OUTPUT_INCOMPLETE_REASONS = new Set([
33
37
  "adapter_eof",
34
38
  "missing_terminal_event",
@@ -118,7 +122,10 @@ function retryableZeroOutputTerminal(payload: unknown): boolean {
118
122
  response?: { incomplete_details?: { reason?: unknown }; output?: unknown };
119
123
  };
120
124
  if (bareErrorIsRetryable(event)) return true;
121
- if (event.type === "response.failed") return true;
125
+ if (event.type === "response.failed") {
126
+ const code = (event.response as { error?: { code?: unknown } } | undefined)?.error?.code;
127
+ return !(typeof code === "string" && NON_REPLAYABLE_FAILED_CODES.has(code));
128
+ }
122
129
  if (event.type !== "response.incomplete") return false;
123
130
  const reason = event.response?.incomplete_details?.reason;
124
131
  // A terminal-only upstream can carry output without preceding delta/item events.
@@ -25,7 +25,7 @@ import { parseRequest } from "../../responses/parser";
25
25
  import { buildCompactV1Output, COMPACT_PROMPT, decodeCompactionSummary, extractCompactUserMessages } from "../../responses/compaction";
26
26
  import { applyReasoningRetention, appendRetentionNotice, type ReasoningRetentionResult } from "../../responses/reasoning-retention";
27
27
  import { FORWARD_HEADERS, sanitizeReasoningInputContent } from "../../adapters/openai-responses";
28
- import { stripProviderInputItemMetadata } from "../../adapters/openai-responses/request-strips";
28
+ import { repairUrlCitationAnnotations, stripProviderInputItemMetadata } from "../../adapters/openai-responses/request-strips";
29
29
  import { expandPreviousResponseInput, previousResponseProviderState, rememberResponseState } from "../../responses/state";
30
30
  import { repairLegacyDottedToolCallNames } from "../../responses/legacy-dotted-tool-name-repair";
31
31
  import { NoEligiblePolicyCandidateError, routeCompactionModel } from "../../router";
@@ -129,6 +129,7 @@ import {
129
129
  ForwardAdmissionCredentialError,
130
130
  contextPrincipalIdOf,
131
131
  hasForwardableCodexBearer,
132
+ resolveContextPrincipal,
132
133
  validateForwardAdmissionCredential,
133
134
  } from "../auth-cors";
134
135
  import type { DataPlaneAdmission } from "../auth-cors";
@@ -948,7 +949,7 @@ export async function handleResponsesCompact(
948
949
  // #5095: the compact endpoint forwards `raw` directly, so it needs the same legacy dotted
949
950
  // call-name repair the adapter applies. A damaged item here refuses the compaction itself,
950
951
  // which is the request a long task depends on to keep going.
951
- // This branch is OpenAI-only and bypasses the adapter's Google replay projection (#7111).
952
+ // Direct compact bypasses the adapter's Google replay projection (#7111).
952
953
  const compactBody = repairLegacyDottedToolCallNames(
953
954
  stripProviderInputItemMetadata(sanitizeReasoningInputContent(compactBodyRaw, {
954
955
  preserveRawReasoningContent: !isOpenAiOperatedResponsesDestination(compactProvider)
@@ -1002,7 +1003,12 @@ export async function handleResponsesCompact(
1002
1003
  cursorConversationId: gatewayReplayParsed._cursorConversationId,
1003
1004
  sessionIdHeader: sessionIdHeaderFromRequest(req.headers),
1004
1005
  });
1005
- if (clientThreadId) gatewayReplayParsed._reasoningReplayScope = { clientThreadId };
1006
+ if (clientThreadId) {
1007
+ gatewayReplayParsed._reasoningReplayScope = {
1008
+ clientThreadId,
1009
+ clientPrincipalId: resolveContextPrincipal(req, config, admission),
1010
+ };
1011
+ }
1006
1012
  }
1007
1013
  let compactUrl = gatewayTransport ? `${gatewayTransport.url.replace(/\/+$/, "")}/compact` : `${base}/responses/compact`;
1008
1014
  const compactTargetKey = `${route.providerName}|${route.modelId}|compact`;
@@ -1154,8 +1160,9 @@ export async function handleResponsesCompact(
1154
1160
  if (!isOpenAiOperatedResponsesDestination(sendProvider) && sendProvider.preserveResponsesMessageMetadata !== true) {
1155
1161
  replayBody = stripInternalChatMessageMetadataPassthrough(replayBody) as typeof replayBody;
1156
1162
  }
1163
+ // A queued key selection can refresh the destination; project only for this send.
1157
1164
  return isOpenAiOperatedResponsesDestination(sendProvider)
1158
- ? replayBody : stripCanonicalOnlyInputItems(stripCanonicalOnlyTopLevelFields(replayBody));
1165
+ ? repairUrlCitationAnnotations(replayBody) : stripCanonicalOnlyInputItems(stripCanonicalOnlyTopLevelFields(replayBody));
1159
1166
  };
1160
1167
  const doFetch = (upstreamRecovery?: UpstreamSendRecovery) => fetchWithHeaderTimeout(
1161
1168
  compactUrl,
@@ -1723,7 +1730,9 @@ export async function handleResponsesCompact(
1723
1730
  // The routed compaction turn is a handoff inside the same logical request, so it draws the
1724
1731
  // REMAINDER. Minting here is what let a native attempt spend three sends and the routed
1725
1732
  // fallback spend four more.
1726
- const response = await handleResponses(internalReq, config, logCtx, { abortSignal: req.signal, turnAdmissionLease, sendBudget, compactionRecoveryKind: "compaction-v1", compactionRoutingOverride: options.compactionRoutingOverride, ...(admission ? { admission } : {}) });
1733
+ // internalReq keeps only FORWARD_HEADERS, so the caller principal is resolved from req.
1734
+ const replayPrincipal = { clientPrincipalId: resolveContextPrincipal(req, config, admission) };
1735
+ const response = await handleResponses(internalReq, config, logCtx, { abortSignal: req.signal, turnAdmissionLease, sendBudget, compactionRecoveryKind: "compaction-v1", compactionRoutingOverride: options.compactionRoutingOverride, replayPrincipal, ...(admission ? { admission } : {}) });
1727
1736
  if (req.signal.aborted) {
1728
1737
  void response.body?.cancel(req.signal.reason).catch(() => undefined);
1729
1738
  return formatErrorResponse(499, "client_cancelled", "Client cancelled compact request");