@bitkyc08/opencodex 2.95.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
  3. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +21 -7
  16. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  17. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  18. package/src/adapters/openai-responses/passthrough.ts +8 -8
  19. package/src/adapters/openai-responses/reasoning.ts +9 -4
  20. package/src/adapters/openai-responses/request-strips.ts +1 -1
  21. package/src/adapters/openai-responses/transport.ts +17 -26
  22. package/src/adapters/physical-send.ts +3 -3
  23. package/src/adapters/qoder/adapter.ts +1 -1
  24. package/src/adapters/qoder/image-input.ts +5 -2
  25. package/src/adapters/zed-openai-stream.ts +2 -1
  26. package/src/bridge/errors.ts +11 -2
  27. package/src/bridge/response-json.ts +2 -1
  28. package/src/bridge/sse.ts +14 -6
  29. package/src/chat/failure-verdict.ts +21 -0
  30. package/src/chat/outbound.ts +139 -21
  31. package/src/claude/outbound.ts +49 -2
  32. package/src/cli/agent.ts +44 -15
  33. package/src/cli/capabilities-agents-routing.ts +9 -0
  34. package/src/cli/capabilities-base.ts +25 -3
  35. package/src/cli/capabilities-command.ts +12 -3
  36. package/src/cli/capability-contracts.ts +2 -0
  37. package/src/cli/codex-launch-auth.ts +30 -1
  38. package/src/cli/codex-launcher.ts +12 -5
  39. package/src/cli/codex-shim-autorestore.ts +5 -4
  40. package/src/cli/dispatch.ts +11 -176
  41. package/src/cli/ensure-desired-integrations.ts +4 -3
  42. package/src/cli/help.ts +2 -2
  43. package/src/cli/index.ts +9 -2
  44. package/src/cli/link.ts +1 -1
  45. package/src/cli/message-command.ts +2 -1
  46. package/src/cli/message-mcp-command.ts +29 -0
  47. package/src/cli/registry.ts +12 -4
  48. package/src/cli/root.ts +8 -0
  49. package/src/cli/sync-command.ts +243 -0
  50. package/src/cli/sync-fanout-process.ts +92 -0
  51. package/src/cli/sync-fanout.ts +150 -0
  52. package/src/cli/sync-flags.ts +10 -0
  53. package/src/cli/sync-link-status.ts +39 -0
  54. package/src/cli/sync-update-guard.ts +18 -0
  55. package/src/client/connect.ts +31 -14
  56. package/src/client/link-home.ts +3 -2
  57. package/src/client/machine-listener.ts +3 -0
  58. package/src/client/restore-ownership.ts +19 -1
  59. package/src/client/runtime-restart.ts +12 -4
  60. package/src/client/runtime.ts +40 -11
  61. package/src/client/stop-routing.ts +62 -0
  62. package/src/client/sync-runtime.ts +65 -0
  63. package/src/clients/config-export.ts +32 -3
  64. package/src/codex/account-store.ts +1 -0
  65. package/src/codex/auth-context-provider.ts +15 -0
  66. package/src/codex/auth-context.ts +59 -122
  67. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  68. package/src/codex/catalog/provider-models.ts +6 -8
  69. package/src/codex/forward-transport-headers.ts +65 -36
  70. package/src/codex/inject/config-toml.ts +88 -0
  71. package/src/codex/inject/multi-agent-v2.ts +30 -4
  72. package/src/codex/inject/plan.ts +34 -7
  73. package/src/codex/inject-coordination.ts +11 -0
  74. package/src/codex/inject.ts +18 -7
  75. package/src/codex/installation-id.ts +72 -0
  76. package/src/codex/lineage.ts +13 -7
  77. package/src/codex/quota.ts +22 -6
  78. package/src/codex/request-owned-affinity-key.ts +11 -0
  79. package/src/codex/request-owned-affinity.ts +118 -0
  80. package/src/codex/request-owned-main-pin.ts +86 -0
  81. package/src/codex/role-capability.ts +52 -41
  82. package/src/codex/routing/active-account.ts +13 -5
  83. package/src/codex/routing/selection.ts +40 -1
  84. package/src/codex/routing/thread-affinity-store.ts +916 -0
  85. package/src/codex/routing/thread-affinity.ts +90 -12
  86. package/src/codex/toml-source-lines.ts +72 -13
  87. package/src/combos/failover.ts +6 -109
  88. package/src/combos/request.ts +2 -2
  89. package/src/combos/resolve.ts +29 -11
  90. package/src/config/process-state.ts +5 -0
  91. package/src/config/schema/leaf-validators.ts +1 -0
  92. package/src/generated/compatibility-version.json +496 -192
  93. package/src/grok/sync.ts +10 -1
  94. package/src/images/loop.ts +2 -1
  95. package/src/lib/client-error-body.ts +184 -0
  96. package/src/lib/client-retry-after.ts +66 -0
  97. package/src/lib/config-ownership.ts +4 -0
  98. package/src/lib/context-overflow-verdict.ts +113 -0
  99. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  100. package/src/lib/desktop-cli-handoff.mjs +11 -1
  101. package/src/lib/empty-tool-catalog.ts +25 -3
  102. package/src/lib/error-destination.ts +47 -0
  103. package/src/lib/failure-detail.ts +66 -0
  104. package/src/lib/model-identity.ts +44 -0
  105. package/src/lib/private-sqlite-path.ts +124 -0
  106. package/src/lib/response-service-tier.ts +17 -0
  107. package/src/lib/retry-after.ts +3 -0
  108. package/src/lib/spend-ledger-owner.ts +43 -4
  109. package/src/lib/upstream-condition.ts +142 -0
  110. package/src/lib/upstream-retry.ts +14 -11
  111. package/src/lib/windows-owner-acl.ts +13 -6
  112. package/src/lib/windows-secret-acl.ts +2 -2
  113. package/src/link/remote-platform.ts +14 -0
  114. package/src/link/remote-windows.ts +51 -9
  115. package/src/link/ssh-argv.ts +63 -10
  116. package/src/messaging/mcp-queue-rpc.ts +102 -0
  117. package/src/messaging/mcp-queue-server.ts +42 -0
  118. package/src/messaging/mcp-queue-tools.ts +39 -0
  119. package/src/oauth/anthropic-identity.ts +2 -6
  120. package/src/oauth/generic-account-failover.ts +13 -11
  121. package/src/oauth/index.ts +41 -74
  122. package/src/oauth/oauth-errors.ts +67 -0
  123. package/src/oauth/store.ts +1 -1
  124. package/src/protocols/codecs/ollama.ts +197 -0
  125. package/src/protocols/encoders/adapter-events.ts +4 -0
  126. package/src/protocols/encoders/chat.ts +18 -10
  127. package/src/protocols/trace.ts +18 -0
  128. package/src/providers/anthropic-subscription.ts +25 -0
  129. package/src/providers/claude-cli-usage.ts +15 -67
  130. package/src/providers/fastwire.ts +3 -2
  131. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  132. package/src/providers/quota/anthropic-usage-windows.ts +65 -0
  133. package/src/providers/quota/vendor-probes-key.ts +60 -24
  134. package/src/providers/request-pacing.ts +3 -2
  135. package/src/responses/apply-patch-envelope.ts +45 -19
  136. package/src/responses/compaction-history-framing.ts +5 -1
  137. package/src/responses/freeform-wrapper-scan.ts +5 -3
  138. package/src/responses/parser-tools.ts +1 -0
  139. package/src/responses/progressive-freeform-input.ts +354 -45
  140. package/src/responses/schema.ts +5 -2
  141. package/src/routing/fallback-policy.ts +3 -1
  142. package/src/server/admission-model-scope.ts +17 -6
  143. package/src/server/admitted-http-turn.ts +56 -0
  144. package/src/server/audio-dictation.ts +3 -0
  145. package/src/server/audio-live.ts +8 -2
  146. package/src/server/audio-upstream.ts +2 -0
  147. package/src/server/auth-cors.ts +5 -0
  148. package/src/server/chat-completions.ts +45 -20
  149. package/src/server/chat-native-sse.ts +52 -7
  150. package/src/server/chat-native.ts +60 -35
  151. package/src/server/claude-bridge-pool-session.ts +59 -0
  152. package/src/server/claude-messages.ts +57 -27
  153. package/src/server/context-history.ts +14 -7
  154. package/src/server/images.ts +14 -5
  155. package/src/server/inbound-body-admission.ts +11 -4
  156. package/src/server/index/live-sideband.ts +16 -2
  157. package/src/server/index/ollama-routes.ts +89 -0
  158. package/src/server/index/serve-options.ts +22 -4
  159. package/src/server/index/websocket-handler.ts +5 -3
  160. package/src/server/index.ts +6 -36
  161. package/src/server/inference/client-encoder-delivery.ts +4 -2
  162. package/src/server/json-serialized-bytes.ts +44 -0
  163. package/src/server/live.ts +30 -5
  164. package/src/server/management/agent-settings-routes.ts +24 -21
  165. package/src/server/management/codex-cli-update-routes.ts +2 -1
  166. package/src/server/management/route-registry.ts +1 -1
  167. package/src/server/messages-native-scope.ts +2 -1
  168. package/src/server/messages-native-tool-guard.ts +1 -1
  169. package/src/server/messages-native.ts +12 -7
  170. package/src/server/messages-shared.ts +6 -2
  171. package/src/server/native-final-log.ts +93 -0
  172. package/src/server/ollama-inbound.ts +349 -0
  173. package/src/server/ollama-native-paths.ts +21 -0
  174. package/src/server/ollama-route-policy.ts +73 -0
  175. package/src/server/relay.ts +22 -3
  176. package/src/server/request-decompress.ts +4 -2
  177. package/src/server/request-log-failure-attribution.ts +22 -0
  178. package/src/server/request-log-failure-detail.ts +80 -0
  179. package/src/server/request-log-terminal-status.ts +4 -2
  180. package/src/server/request-log.ts +79 -42
  181. package/src/server/response-log-body.ts +6 -1
  182. package/src/server/responses/account-change-state.ts +17 -6
  183. package/src/server/responses/adapter-continuation.ts +9 -4
  184. package/src/server/responses/adapter-delivery.ts +5 -4
  185. package/src/server/responses/adapter-dispatch.ts +36 -30
  186. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  187. package/src/server/responses/codex-auth-error.ts +22 -17
  188. package/src/server/responses/codex-ws-exchange.ts +11 -8
  189. package/src/server/responses/codex-ws-metadata.ts +94 -21
  190. package/src/server/responses/codex-ws-request.ts +3 -1
  191. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  192. package/src/server/responses/compact.ts +89 -41
  193. package/src/server/responses/compaction-recovery.ts +4 -2
  194. package/src/server/responses/compaction-routing.ts +9 -4
  195. package/src/server/responses/core-auth.ts +32 -14
  196. package/src/server/responses/core-codex-account.ts +34 -12
  197. package/src/server/responses/core-combo-failure.ts +5 -1
  198. package/src/server/responses/core-combo-native.ts +2 -1
  199. package/src/server/responses/core-combo.ts +51 -33
  200. package/src/server/responses/core-errors.ts +22 -20
  201. package/src/server/responses/core-lifetime.ts +6 -3
  202. package/src/server/responses/core-normalize.ts +8 -1
  203. package/src/server/responses/core-options.ts +7 -0
  204. package/src/server/responses/core-pipeline.ts +4 -3
  205. package/src/server/responses/fetch-helpers.ts +7 -1
  206. package/src/server/responses/input-admission.ts +28 -2
  207. package/src/server/responses/native-injection.ts +1 -1
  208. package/src/server/responses/native-response-json.ts +13 -4
  209. package/src/server/responses/native-response-output.ts +1 -2
  210. package/src/server/responses/non-replayable-error.ts +2 -1
  211. package/src/server/responses/pacing-overload.ts +3 -2
  212. package/src/server/responses/passthrough-build-error.ts +36 -0
  213. package/src/server/responses/passthrough-delivery.ts +55 -14
  214. package/src/server/responses/passthrough-dispatch.ts +26 -39
  215. package/src/server/responses/passthrough-error.ts +9 -9
  216. package/src/server/responses/policy-fallback.ts +2 -1
  217. package/src/server/responses/request-prepare.ts +67 -48
  218. package/src/server/responses/request-sidecar-auth.ts +3 -1
  219. package/src/server/responses/request-transport.ts +35 -31
  220. package/src/server/responses/run-turn-execution.ts +6 -6
  221. package/src/server/responses/sidecar-execution.ts +16 -12
  222. package/src/server/responses/spend-storage-error.ts +2 -1
  223. package/src/server/responses/ws-upstream.ts +9 -0
  224. package/src/server/responses-custom-tool-repair.ts +14 -3
  225. package/src/server/responses-terminal-repair.ts +5 -2
  226. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  227. package/src/server/safe-response-headers.ts +162 -13
  228. package/src/server/search.ts +13 -4
  229. package/src/server/turn-state-handles.ts +164 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/server/ws-bridge.ts +5 -2
  232. package/src/service/ownership-mutation-lease.d.mts +11 -2
  233. package/src/service/ownership-mutation-lease.mjs +53 -11
  234. package/src/types/config.ts +2 -0
  235. package/src/update/index.ts +133 -25
  236. package/src/update/npm-install.d.mts +8 -0
  237. package/src/update/npm-install.mjs +20 -1
  238. package/src/update/orchestrated-admission.d.mts +4 -0
  239. package/src/update/orchestrated-admission.mjs +12 -0
  240. package/src/update/orchestrated-arguments.d.mts +12 -0
  241. package/src/update/orchestrated-arguments.mjs +64 -0
  242. package/src/update/orchestrated-child.d.mts +12 -0
  243. package/src/update/orchestrated-child.mjs +70 -0
  244. package/src/update/orchestrated-entry.ts +234 -0
  245. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  246. package/src/update/orchestrated-identity.ts +53 -0
  247. package/src/update/orchestrated-live-identity.ts +48 -0
  248. package/src/update/orchestrated-node-driver.mjs +99 -0
  249. package/src/update/orchestrated-outcome.d.mts +21 -0
  250. package/src/update/orchestrated-outcome.mjs +40 -0
  251. package/src/update/orchestrated-plan.ts +49 -0
  252. package/src/update/orchestrated-pnpm.d.mts +8 -0
  253. package/src/update/orchestrated-pnpm.mjs +33 -0
  254. package/src/update/orchestrated-session.d.mts +37 -0
  255. package/src/update/orchestrated-session.mjs +264 -0
  256. package/src/update/orchestrated-token.d.mts +10 -0
  257. package/src/update/orchestrated-token.mjs +21 -0
  258. package/src/update/orchestrated-token.ts +3 -0
  259. package/src/update/orchestrated-tree.d.mts +1 -0
  260. package/src/update/orchestrated-tree.mjs +14 -0
  261. package/src/update/pnpm-global-install.d.mts +6 -0
  262. package/src/update/pnpm-global-install.mjs +9 -2
  263. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  264. package/src/update/posix-install-supervisor.d.mts +10 -0
  265. package/src/update/posix-install-supervisor.mjs +88 -0
  266. package/src/update/sync-update-mutex.d.mts +10 -0
  267. package/src/update/sync-update-mutex.mjs +164 -0
  268. package/src/update/sync-update-mutex.ts +1 -0
  269. package/src/update/test-home-guard.mjs +33 -0
  270. package/src/update/transactional-install.mjs +2 -2
  271. package/src/usage/error-detail.ts +225 -0
  272. package/src/usage/log.ts +60 -27
  273. package/src/vision/describe.ts +4 -7
  274. package/src/web-search/executor.ts +4 -7
  275. package/src/web-search/loop.ts +31 -5
  276. package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
@@ -1,3 +1,6 @@
1
+ import { attachComboFailureEvidence, ownedChatErrorPayload, type ClientErrorContract } from "../lib/client-error-body";
2
+ import type { FailureVerdictSink } from "../chat/failure-verdict";
3
+ import { normalizeChatChoiceErrors } from "./chat-native-sse";
1
4
  import { captureAccountAutoPauseAttempt, wasAccountAutoPaused } from "../oauth/account-auto-pause";
2
5
  import { createPhysicalSendReporter } from "../lib/request-execution-budget";
3
6
  import { createInferenceSendBudget } from "./inference/context";
@@ -7,6 +10,7 @@ import type { AdapterRequest, ProviderAdapter } from "../adapters/base";
7
10
  import { isNativeChatRouteEligible } from "./chat-native-eligibility";
8
11
  import {
9
12
  chatCompletionsErrorBody,
13
+ ChatCompletionsCollectorSource,
10
14
  chatCompletionsErrorResponse,
11
15
  collectChatCompletion,
12
16
  isChatCompletionsStreamError,
@@ -27,7 +31,7 @@ import type { AdmissionLease } from "../lib/admission";
27
31
  import { resolveContextPrincipal, type DataPlaneAdmission } from "./auth-cors";
28
32
  import { readBoundedResponseBody } from "../lib/bounded-body";
29
33
  import { redactSecretString } from "../lib/redact";
30
- import { resolveClientRetryAfter } from "../lib/retry-after";
34
+ import { formatClientRetryAfter, resolveClientRetryAfter } from "../lib/retry-after";
31
35
  import {
32
36
  applyUpstreamRecoveryInit,
33
37
  fetchWithResetRetry,
@@ -39,7 +43,7 @@ import {
39
43
  REPLAY_REFUSAL_CLIENT_HEADERS,
40
44
  REPLAY_REFUSED_STATUS,
41
45
  retainReplayRefusal,
42
- SendBudgetExhaustedError,
46
+ SendBudgetExhaustedError, errorDestinationLabel,
43
47
  TRANSIENT_RETRY_MAX_ATTEMPTS,
44
48
  UpstreamRetryEvidenceError,
45
49
  type UpstreamSendRecovery,
@@ -86,6 +90,7 @@ import { attachRequestSpendTracker } from "./responses/request-spend";
86
90
  import { workflowRefusalResponse } from "./workflow-refusal";
87
91
  import type { ComboProtocolSource } from "./responses/core-combo-native";
88
92
  import type { ProtocolEnvelope } from "../protocols/envelope";
93
+ import { protocolTraceSuppressed } from "../protocols/trace";
89
94
  import { nativeChatReplayScope, bindNativeChatReplayScope, nativeChatReasoningCapture } from "./chat-native-reasoning";
90
95
  import { resolveMistralTransport } from "../providers/mistral-transport";
91
96
 
@@ -225,7 +230,7 @@ export interface NativeChatExecution extends HandleNativeChatOptions {
225
230
  */
226
231
  export async function handleNativeChatCompletions(options: HandleNativeChatOptions): Promise<Response> {
227
232
  const { logCtx, logIds, route } = options;
228
- logCtx.inboundProtocol = "chat";
233
+ if (!protocolTraceSuppressed(logCtx)) logCtx.inboundProtocol = "chat";
229
234
  const attemptHandle = beginInferenceAttempt(logCtx, {
230
235
  provider: route.providerName,
231
236
  model: route.modelId,
@@ -299,12 +304,22 @@ export async function runNativeChatAttempt(
299
304
  const notifyFirstOutput = execution.onFirstOutput
300
305
  ?? (logIds ? () => recordFirstOutput(logCtx, logIds.start) : undefined);
301
306
  const onFirstOutput = () => { outputDelivered = true; notifyFirstOutput?.(); };
302
- const fail = (status: number, message: string, type?: string, code?: string | null): Response => {
307
+ const failLocal = (status: number, message: string, type?: string, code?: string | null): Response => {
303
308
  const safeMessage = redactSecretString(message);
304
309
  finishLog(status, safeMessage);
305
310
  return chatCompletionsErrorResponse(status, safeMessage, type, code);
306
311
  };
307
312
 
313
+ const failUpstream = (status: number, message: string, type?: string, code?: string | null, contract?: ClientErrorContract): Response => {
314
+ const legacy = chatCompletionsErrorBody(status, redactSecretString(message), type, code);
315
+ finishLog(status, redactSecretString(message));
316
+ const error = legacy.error as { type: string; code: string | null };
317
+ const finalStatus = error.code === CYBER_POLICY_ERROR_CODE ? 400 : status;
318
+ return attachComboFailureEvidence(new Response(JSON.stringify(ownedChatErrorPayload({ status: finalStatus, type: error.type, code: error.code, contract,
319
+ evidence: { status, type, code: code ?? undefined, message } })),
320
+ { status: finalStatus, headers: { "Content-Type": "application/json" } }), JSON.stringify(legacy));
321
+ };
322
+
308
323
  normalizePinnedChatEffort(execution);
309
324
  logCtx.requestedServiceTier = typeof execution.chatBody.service_tier === "string"
310
325
  ? execution.chatBody.service_tier
@@ -341,8 +356,9 @@ export async function runNativeChatAttempt(
341
356
  } catch (error) {
342
357
  cleanupAbort(); upstream.abort();
343
358
  if (!(error instanceof RequestPacingQueueOverloadError)) throw error;
344
- const refusal = fail(429, error.message, "rate_limit_error");
345
- refusal.headers.set("Retry-After", String(error.retryAfterSeconds));
359
+ const refusal = failLocal(429, error.message, "rate_limit_error");
360
+ const advice = formatClientRetryAfter(error.retryAfterSeconds);
361
+ if (advice !== undefined) refusal.headers.set("Retry-After", advice);
346
362
  return refusal;
347
363
  }
348
364
  // Key selection re-resolves the transport; a single-key route still needs canonical Mistral pacing.
@@ -391,9 +407,9 @@ export async function runNativeChatAttempt(
391
407
  cleanupAbort();
392
408
  upstream.abort();
393
409
  if (isTranslatorBudgetExceededError(error)) {
394
- return fail(413, "request translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit");
410
+ return failLocal(413, "request translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit");
395
411
  }
396
- return fail(400, error instanceof Error ? error.message : String(error), "invalid_request_error");
412
+ return failLocal(400, error instanceof Error ? error.message : String(error), "invalid_request_error");
397
413
  }
398
414
 
399
415
  // One inbound request owns one transient send allowance. Capture the policy before any
@@ -452,7 +468,7 @@ export async function runNativeChatAttempt(
452
468
  // Backstop for sends the helper cannot see coming (a reset replay). The first
453
469
  // report settles the combo's booking; each later one is charged and booked.
454
470
  if (physicalSends > 0 && sendBudget.remainingBaseSends(sharedSendCap) <= 0) {
455
- throw new SendBudgetExhaustedError(safeHostLabel(url));
471
+ throw new SendBudgetExhaustedError(errorDestinationLabel(url));
456
472
  }
457
473
  physicalSends += 1;
458
474
  reportDispatchSends(sendBudget, 1, execution.comboDispatchPermit);
@@ -470,7 +486,7 @@ export async function runNativeChatAttempt(
470
486
  // #2643: opted-in key-auth openai-chat providers retry pre-stream transient statuses on
471
487
  // the native chat lane too; everyone else keeps reset-only semantics.
472
488
  const remaining = remainingTransientSends();
473
- if (sendBudget && remaining <= 0) throw new SendBudgetExhaustedError(safeHostLabel(request.url));
489
+ if (sendBudget && remaining <= 0) throw new SendBudgetExhaustedError(errorDestinationLabel(request.url));
474
490
  if (requestTransientPolicy && remaining <= 0) {
475
491
  throw new Error("native Chat transient send budget exhausted before recovery dispatch");
476
492
  }
@@ -584,7 +600,7 @@ export async function runNativeChatAttempt(
584
600
  dispatch,
585
601
  {
586
602
  abortSignal: upstream.signal,
587
- label: safeHostLabel(request.url),
603
+ label: safeHostLabel(request.url), destination: errorDestinationLabel(request.url),
588
604
  ...(requestTransientPolicy
589
605
  ? {
590
606
  attempts: remaining,
@@ -675,16 +691,17 @@ export async function runNativeChatAttempt(
675
691
  releaseRetainedRequest();
676
692
  cleanupAbort();
677
693
  upstream.abort();
678
- if (req.signal.aborted) return fail(499, "Client cancelled request", "client_cancelled");
694
+ if (req.signal.aborted) return failLocal(499, "Client cancelled request", "client_cancelled");
679
695
  const sendError = error instanceof UpstreamRetryEvidenceError ? error.cause : error;
680
696
  if (sendError instanceof RequestPacingQueueOverloadError) {
681
- const refusal = fail(429, sendError.message, "rate_limit_error");
682
- refusal.headers.set("Retry-After", String(sendError.retryAfterSeconds));
697
+ const refusal = failLocal(429, sendError.message, "rate_limit_error");
698
+ const advice = formatClientRetryAfter(sendError.retryAfterSeconds);
699
+ if (advice !== undefined) refusal.headers.set("Retry-After", advice);
683
700
  return refusal;
684
701
  }
685
702
  if (sendError instanceof SendBudgetExhaustedError) {
686
703
  // A decision this process made, answered as the Responses path answers it: 429, not 502.
687
- return fail(429, sendError.message, SEND_BUDGET_EXHAUSTED_CODE, SEND_BUDGET_EXHAUSTED_CODE);
704
+ return failLocal(429, sendError.message, SEND_BUDGET_EXHAUSTED_CODE, SEND_BUDGET_EXHAUSTED_CODE);
688
705
  }
689
706
  if (sendError instanceof NativeChatSpendRefusal) {
690
707
  const refusal = workflowRefusalResponse("workflow-spend-exhausted", logCtx);
@@ -692,9 +709,9 @@ export async function runNativeChatAttempt(
692
709
  return refusal;
693
710
  }
694
711
  if (isTranslatorBudgetExceededError(error)) {
695
- return fail(413, "request translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit");
712
+ return failLocal(413, "request translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit");
696
713
  }
697
- return fail(502, error instanceof Error ? error.message : String(error), "server_error");
714
+ return failUpstream(502, error instanceof Error ? error.message : String(error), "server_error", undefined, "transport_failed");
698
715
  }
699
716
  releaseRetainedRequest();
700
717
 
@@ -710,7 +727,7 @@ export async function runNativeChatAttempt(
710
727
  cleanupAbort();
711
728
  if (req.signal.aborted) {
712
729
  upstream.abort();
713
- return fail(499, "Client cancelled request", "client_cancelled");
730
+ return failLocal(499, "Client cancelled request", "client_cancelled");
714
731
  }
715
732
  const detail = activeAdapter.formatErrorBody?.(response.status, response.headers, bodyText) ?? "";
716
733
  let upstreamType: string | undefined;
@@ -772,14 +789,17 @@ export async function runNativeChatAttempt(
772
789
  upstreamRetryAfter: response.headers.get("retry-after"),
773
790
  });
774
791
  finishLog(status, classified.message);
775
- const rewritten = new Response(JSON.stringify(chatCompletionsErrorBody(status, classified.message, classified.type, classified.code)), {
792
+ const rewritten = new Response(JSON.stringify(ownedChatErrorPayload({ status, type: classified.type, code: classified.code,
793
+ evidence: { status: response.status, type: upstreamType, code: upstreamCode ?? undefined, message: upstreamMessage ?? detail },
794
+ localReason: wasAccountAutoPaused(response) ? "credentials_paused" : undefined })), {
776
795
  status,
777
796
  headers: {
778
797
  "Content-Type": "application/json",
779
- ...(retryAfter ? { "Retry-After": retryAfter } : {}),
798
+ ...(formatClientRetryAfter(retryAfter) ? { "Retry-After": formatClientRetryAfter(retryAfter)! } : {}),
780
799
  ...(replayRefusal ? REPLAY_REFUSAL_CLIENT_HEADERS : {}),
781
800
  },
782
801
  });
802
+ attachComboFailureEvidence(rewritten, JSON.stringify(chatCompletionsErrorBody(status, classified.message, classified.type, classified.code)));
783
803
  return replayRefusal ? retainReplayRefusal(rewritten) : rewritten;
784
804
  }
785
805
 
@@ -802,7 +822,7 @@ export async function runNativeChatAttempt(
802
822
  },
803
823
  {
804
824
  abortSignal: upstream.signal,
805
- label: safeHostLabel(activeRequest.url),
825
+ label: safeHostLabel(activeRequest.url), destination: errorDestinationLabel(activeRequest.url),
806
826
  attempts: remainingTransientSends(),
807
827
  // The origin returned a head and may already be running the turn, so this is the
808
828
  // ambiguous row of the stage table. Only the operator allowance the Responses stream
@@ -815,7 +835,11 @@ export async function runNativeChatAttempt(
815
835
  (replacement.headers.get("content-type") ?? "").toLowerCase().includes("text/event-stream"),
816
836
  },
817
837
  );
838
+ const failureVerdictSink: FailureVerdictSink = {};
839
+ const collectorSource = requestedStream ? undefined : new ChatCompletionsCollectorSource(translatorBudget);
818
840
  const stream = nativeChatSse(resilientBody, {
841
+ failureVerdictSink,
842
+ collectorSource,
819
843
  requestedModel,
820
844
  translatorBudget,
821
845
  signal: upstream.signal,
@@ -867,13 +891,13 @@ export async function runNativeChatAttempt(
867
891
  });
868
892
  }
869
893
  try {
870
- const completion = await collectChatCompletion(stream, requestedModel, translatorBudget);
894
+ const completion = await collectChatCompletion(stream, requestedModel, translatorBudget, failureVerdictSink, collectorSource);
871
895
  cleanupAbort();
872
896
  // A cancelled native relay closes its downstream body. EOF alone must not
873
897
  // promote the buffered prefix to a successful Chat completion. A terminal
874
898
  // already accepted by the relay retains precedence over a later abort.
875
899
  if (req.signal.aborted && terminalStatus === undefined) {
876
- return fail(499, "Client cancelled request", "client_cancelled");
900
+ return failLocal(499, "Client cancelled request", "client_cancelled");
877
901
  }
878
902
  finishLog(200);
879
903
  return Response.json(completion);
@@ -881,12 +905,12 @@ export async function runNativeChatAttempt(
881
905
  cleanupAbort();
882
906
  upstream.abort();
883
907
  if (req.signal.aborted && terminalStatus === undefined) {
884
- return fail(499, "Client cancelled request", "client_cancelled");
908
+ return failLocal(499, "Client cancelled request", "client_cancelled");
885
909
  }
886
910
  if (isChatCompletionsStreamError(error)) {
887
- return fail(error.status, error.message, error.type, error.code);
911
+ return failUpstream(error.status, error.message, error.type, error.code);
888
912
  }
889
- return fail(502, error instanceof Error ? error.message : String(error), "upstream_error");
913
+ return failUpstream(502, error instanceof Error ? error.message : String(error), "upstream_error", undefined, "transport_failed");
890
914
  }
891
915
  }
892
916
 
@@ -902,24 +926,25 @@ export async function runNativeChatAttempt(
902
926
  } catch (error) {
903
927
  cleanupAbort();
904
928
  upstream.abort();
905
- if (req.signal.aborted) return fail(499, "Client cancelled request", "client_cancelled");
906
- return fail(502, error instanceof Error ? error.message : String(error), "upstream_error");
929
+ if (req.signal.aborted) return failLocal(499, "Client cancelled request", "client_cancelled");
930
+ return failUpstream(502, error instanceof Error ? error.message : String(error), "upstream_error", undefined, "transport_failed");
907
931
  }
908
932
  cleanupAbort();
909
933
  if (body.oversized) {
910
934
  upstream.abort();
911
- return fail(502, "upstream response exceeded the safe limit", "upstream_error", "translation_buffer_limit");
935
+ return failUpstream(502, "upstream response exceeded the safe limit", "upstream_error", "translation_buffer_limit");
912
936
  }
913
937
  let parsedJson: unknown;
914
938
  try {
915
939
  parsedJson = JSON.parse(body.text);
916
940
  } catch {
917
- return fail(502, "upstream returned malformed Chat Completions JSON", "upstream_error");
941
+ return failUpstream(502, "upstream returned malformed Chat Completions JSON", "upstream_error");
918
942
  }
919
943
  const error = structuredError(parsedJson);
920
- if (error) return fail(error.status ?? 502, error.message, error.type, error.code);
921
- const completion = chatCompletionJson(parsedJson);
922
- if (!completion) return fail(502, "upstream response contained no choices", "upstream_error");
944
+ if (error) return failUpstream(error.status ?? 502, error.message, error.type, error.code);
945
+ const originalCompletion = chatCompletionJson(parsedJson);
946
+ const completion = originalCompletion ? normalizeChatChoiceErrors(originalCompletion) : null;
947
+ if (!completion) return failUpstream(502, "upstream response contained no choices", "upstream_error");
923
948
  reasoningCapture.json(completion);
924
949
  const usage = usageFromChat(completion.usage);
925
950
  if (usage) {
@@ -929,7 +954,7 @@ export async function runNativeChatAttempt(
929
954
  }
930
955
  }
931
956
  if (clientDeclaredEmptyToolCatalog && chatResponseHasUndeclaredToolCalls(completion, declaredLegacyFunctionNames)) {
932
- return fail(502, UNDECLARED_CHAT_TOOL_MESSAGE, "upstream_error", UNDECLARED_TOOL_CALL_ERROR_CODE);
957
+ return failUpstream(502, UNDECLARED_CHAT_TOOL_MESSAGE, "upstream_error", UNDECLARED_TOOL_CALL_ERROR_CODE);
933
958
  }
934
959
  onFirstOutput?.();
935
960
  try {
@@ -946,7 +971,7 @@ export async function runNativeChatAttempt(
946
971
  });
947
972
  } catch (error) {
948
973
  if (isTranslatorBudgetExceededError(error)) {
949
- return fail(502, "upstream translation buffer exceeded the safe limit", "upstream_error", "translation_buffer_limit");
974
+ return failUpstream(502, "upstream translation buffer exceeded the safe limit", "upstream_error", "translation_buffer_limit");
950
975
  }
951
976
  throw error;
952
977
  }
@@ -0,0 +1,59 @@
1
+ /** Private pool identity for translated Claude turns; replay headers remain unchanged. */
2
+ import { createHmac, randomBytes } from "node:crypto";
3
+ import { codexPoolAffinityKey } from "../codex/auth-context";
4
+ import { contextPrincipalIdOf, type DataPlaneAdmission } from "./auth-cors";
5
+ import { safeCallerSessionId } from "./caller-session-identity";
6
+ import { isThreadSpawnRequest } from "./effort-policy";
7
+ import type { RouteResult } from "../router";
8
+ import type { HandleResponsesOptions } from "./responses/core-options";
9
+
10
+ /**
11
+ * Process-local, like the lineage key: a synthesized identity never leaves the process (replay and
12
+ * upstream headers stay uncompleted), so no caller can name it, not even as a complete
13
+ * session-id + thread-id pair, which reaches the pool unscoped.
14
+ */
15
+ const BRIDGE_POOL_KEY = randomBytes(32);
16
+
17
+ export function resolveClaudeBridgePoolSession(args: {
18
+ ingress: Headers; replay: Headers; metadataSessionId?: string; admission?: DataPlaneAdmission;
19
+ }): string | undefined {
20
+ const { ingress, replay, metadataSessionId, admission } = args;
21
+ if (!admission || isThreadSpawnRequest(ingress) || isThreadSpawnRequest(replay)) return undefined;
22
+ if (ingress.has("x-codex-parent-thread-id") || ingress.has("thread-id")) return undefined;
23
+ if (codexPoolAffinityKey(replay) !== undefined) return undefined;
24
+ let value: string | undefined;
25
+ if (ingress.has("session_id") || ingress.has("session-id")) {
26
+ const first = ingress.get("session_id");
27
+ const second = ingress.get("session-id");
28
+ if (first && second && first !== second) return undefined;
29
+ value = safeCallerSessionId(first || second);
30
+ } else {
31
+ value = safeCallerSessionId(metadataSessionId ?? ingress.get("x-claude-code-session-id"));
32
+ }
33
+ if (!value) return undefined;
34
+ // Every identity this bridge names, caller aliases included, is bound to its admission scope:
35
+ // a shared or guessed value must never select another principal's conversation key.
36
+ let scope: unknown = "loopback";
37
+ if (admission.kind !== "loopback") {
38
+ const principal = contextPrincipalIdOf(admission);
39
+ if (!principal) return undefined;
40
+ scope = ["principal", principal];
41
+ }
42
+ return createHmac("sha256", BRIDGE_POOL_KEY)
43
+ .update(JSON.stringify(["opencodex-claude-bridge-pool-v1", scope, value])).digest("hex");
44
+ }
45
+
46
+ export function completeClaudeBridgePoolIdentity(headers: Headers, options: Pick<HandleResponsesOptions, "claudeBridgePoolSession">): Headers {
47
+ const session = options.claudeBridgePoolSession;
48
+ if (!session || headers.get("x-codex-parent-thread-id") || headers.get("thread-id")
49
+ || codexPoolAffinityKey(headers) !== undefined) return headers;
50
+ const completed = new Headers(headers);
51
+ completed.set("session-id", session);
52
+ completed.set("thread-id", session);
53
+ return completed;
54
+ }
55
+
56
+ export function applyClaudeBridgePoolSession(headers: Headers, route: Pick<RouteResult, "codexAccountMode">,
57
+ options: Pick<HandleResponsesOptions, "claudeBridgePoolSession">): Headers {
58
+ return route.codexAccountMode !== undefined ? completeClaudeBridgePoolIdentity(headers, options) : headers;
59
+ }
@@ -1,3 +1,7 @@
1
+ import { clientFacingModelLabel, clientFacingModelText } from "../lib/error-destination";
2
+ import { classifyUpstreamCondition } from "../lib/upstream-condition";
3
+ import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
4
+ import { recordLocalFailureDetail, type FailureDetail } from "./request-log-failure-detail";
1
5
  /**
2
6
  * Anthropic Messages inbound (/v1/messages + /v1/messages/count_tokens) for Claude Code.
3
7
  *
@@ -7,8 +11,9 @@
7
11
  * unchanged. The Responses output (SSE or JSON) is converted back to Anthropic shape.
8
12
  */
9
13
  import { FORWARD_HEADERS } from "../adapters/openai-responses";
14
+ import { resolveClaudeBridgePoolSession } from "./claude-bridge-pool-session";
10
15
  import {
11
- admissionModelDeniedResponse,
16
+ admissionModelDeniedResponse, projectAdmissionModelDeniedLog,
12
17
  AdmissionModelDeniedError,
13
18
  assertRouteAllowedByScope,
14
19
  resolveAdmissionModelScope,
@@ -49,13 +54,14 @@ import {
49
54
  UPSTREAM_RESET_REPLAY_REFUSED_CODE,
50
55
  } from "../lib/upstream-retry";
51
56
  import { isClientClosedMessage, recognizedUpstreamError, UNDECLARED_TOOL_CALL_ERROR_CODE } from "../lib/errors";
52
- import { resolveClientRetryAfter } from "../lib/retry-after";
57
+ import { formatClientRetryAfter, resolveClientRetryAfter } from "../lib/retry-after";
53
58
  import { anthropicRateLimitHeaders } from "./anthropic-rate-limit-headers";
54
59
  import { upstreamMessagesRequestIdHeaders } from "./messages-response-headers";
55
60
  import {
56
61
  anthropicErrorBody,
57
62
  anthropicErrorResponse,
58
63
  collectAnthropicMessage,
64
+ isContextOverflowError,
59
65
  responsesJsonToAnthropicMessage,
60
66
  responsesSseToAnthropicSse,
61
67
  } from "../claude/outbound";
@@ -334,9 +340,10 @@ async function anthropicNativePassthrough(
334
340
  const finalize = createFinalRequestLog(logIds, logCtx).finish;
335
341
  // Locally generated diagnostics are fixed text plus validated guard limits. Runtime
336
342
  // fetch errors retain their existing client response but use a fixed stored reason.
337
- const fail = (status: number, closeReason: PassthroughCloseReason | "non_stream", message: string, type: string, storedReason = message) => {
343
+ const fail = (status: number, closeReason: PassthroughCloseReason | "non_stream", message: string, type: string,
344
+ detail: FailureDetail, storedReason = message) => {
338
345
  const safeMessage = redactSecretString(message);
339
- logCtx.upstreamError = storedReason.slice(0, 500);
346
+ recordLocalFailureDetail(logCtx, storedReason, detail);
340
347
  finalize(status, { closeReason });
341
348
  return anthropicErrorResponse(status, safeMessage, type);
342
349
  };
@@ -368,11 +375,11 @@ async function anthropicNativePassthrough(
368
375
  req.signal,
369
376
  );
370
377
  if (result.kind === "timeout") {
371
- return fail(504, "non_stream", "anthropic passthrough timed out waiting for response headers", "timeout_error");
378
+ return fail(504, "non_stream", "anthropic passthrough timed out waiting for response headers", "timeout_error", { code: "header_timeout" });
372
379
  }
373
380
  if (result.kind === "error") {
374
381
  const err = result.error;
375
- return fail(502, "non_stream", `anthropic passthrough failed: ${err instanceof Error ? err.message : String(err)}`, "api_error", "anthropic passthrough failed: upstream connection error");
382
+ return fail(502, "non_stream", `anthropic passthrough failed: ${err instanceof Error ? err.message : String(err)}`, "api_error", { code: "connect_failed" }, "anthropic passthrough failed: upstream connection error");
376
383
  }
377
384
  const upstream = result.upstream;
378
385
 
@@ -397,13 +404,15 @@ async function anthropicNativePassthrough(
397
404
  // idle/size bounds — headers are NOT yet sent here, so real statuses are available.
398
405
  const bodyResult = await readBoundedPassthroughBody(upstream, bodyGuard);
399
406
  if (bodyResult.kind === "client_cancel") {
400
- return fail(499, "client_cancel", "client closed request during anthropic passthrough", "api_error");
407
+ return fail(499, "client_cancel", "client closed request during anthropic passthrough", "api_error", { code: "client_closed" });
401
408
  }
402
409
  if (bodyResult.kind === "stall") {
403
- return fail(504, "body_stall", `anthropic passthrough body stalled: no upstream bytes for ${Math.round(bodyGuard.stallMs / 1000)}s`, "timeout_error");
410
+ return fail(504, "body_stall", `anthropic passthrough body stalled: no upstream bytes for ${Math.round(bodyGuard.stallMs / 1000)}s`, "timeout_error",
411
+ { code: "body_stall", value: bodyGuard.stallMs });
404
412
  }
405
413
  if (bodyResult.kind === "overflow") {
406
- return fail(502, "body_overflow", `anthropic passthrough body exceeded ${bodyGuard.maxBytes} bytes`, "api_error");
414
+ return fail(502, "body_overflow", `anthropic passthrough body exceeded ${bodyGuard.maxBytes} bytes`, "api_error",
415
+ { code: "body_overflow", value: bodyGuard.maxBytes });
407
416
  }
408
417
  const text = bodyResult.text;
409
418
  if (upstream.ok) {
@@ -415,20 +424,25 @@ async function anthropicNativePassthrough(
415
424
  // Upstream text is untrusted: retain only a closed type vocabulary in history.
416
425
  // Bound parsing work independently of the larger response-relay body limit.
417
426
  const statusReason = `Provider error ${upstream.status}`;
418
- logCtx.upstreamError = statusReason;
427
+ recordLocalFailureDetail(logCtx, statusReason, { code: "provider_error" }, { upstreamEvidence: true });
419
428
  if (text.length <= PASSTHROUGH_ERROR_DETAIL_MAX_CHARS) {
420
429
  try {
421
430
  const parsed: unknown = JSON.parse(text);
422
431
  if (isRec(parsed) && parsed.type === "error" && isRec(parsed.error)) {
423
432
  const upstreamType = parsed.error.type;
424
433
  const knownType = PASSTHROUGH_ERROR_TYPES.find(type => type === upstreamType);
425
- if (knownType) logCtx.upstreamError = `${statusReason}: ${knownType}`;
434
+ if (knownType) {
435
+ recordLocalFailureDetail(logCtx, `${statusReason}: ${knownType}`, { code: "provider_error", type: knownType }, { upstreamEvidence: true });
436
+ }
437
+ // The condition is classified here from the upstream message; only the closed member is kept.
438
+ const upstreamMessage = typeof parsed.error.message === "string" ? parsed.error.message : undefined;
439
+ logCtx.upstreamCondition = classifyUpstreamCondition({ status: upstream.status, type: knownType, message: upstreamMessage });
426
440
  }
427
441
  } catch { /* Malformed errors keep the fixed status-only diagnostic. */ }
428
442
  }
429
443
  }
430
444
  finalize(upstream.status, { closeReason: "non_stream" });
431
- const retryAfter = upstream.headers.get("retry-after");
445
+ const retryAfter = formatClientRetryAfter(upstream.headers.get("retry-after"));
432
446
  return new Response(text, {
433
447
  status: upstream.status,
434
448
  headers: { ...rateLimitHeaders, "Content-Type": contentType, ...(retryAfter ? { "Retry-After": retryAfter } : {}) },
@@ -618,6 +632,7 @@ async function handleClaudeMessagesWithBudget(
618
632
  let effortRow: ParsedEffortRowId | null = null;
619
633
  let fastRow: ParsedFastRowId | null = null;
620
634
  let requestedModel = "";
635
+ let clientModelLabel = clientFacingModelLabel(undefined);
621
636
  // Antigravity direct lane (off by default): planned before translation, kept only if routing
622
637
  // settles on the route the plan was made for.
623
638
  let directPlan: MessagesDirectPlan | undefined;
@@ -630,6 +645,7 @@ async function handleClaudeMessagesWithBudget(
630
645
  const advisorAdmissionPolicy = logIds?.advisorAdmissionPolicy ?? captureAdmissionPolicy(config, logIds?.admission);
631
646
  try {
632
647
  anthropicBody = await readAnthropicBody(req, translatorBudget, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes));
648
+ clientModelLabel = clientFacingModelLabel(isRec(anthropicBody) ? anthropicBody.model : undefined);
633
649
  // Defensive [1m] strip (devlog 138): clients normally remove the context-variant
634
650
  // marker themselves; the 1M signal we act on is the anthropic-beta header.
635
651
  // Case-insensitive — the CLI matches /\[1m\]/i (audit 021 #7).
@@ -892,7 +908,7 @@ async function handleClaudeMessagesWithBudget(
892
908
  // the same billed Fast lane as their final Responses scope check.
893
909
  assertRouteAllowedByScope(
894
910
  resolveAdmissionModelScope(config, logIds?.admission),
895
- String(internalBody.model ?? ""),
911
+ clientModelLabel,
896
912
  { providerName: route.providerName, modelId: previewXaiOauthWireModel({ options: {
897
913
  serviceTier: typeof internalBody.service_tier === "string" ? internalBody.service_tier : undefined,
898
914
  } }, route, config, "anthropic") },
@@ -903,7 +919,7 @@ async function handleClaudeMessagesWithBudget(
903
919
  // Before any route-specific shaping, so a request that leaves the lane is shaped as the bridge's.
904
920
  if (directPlan && !messagesDirectPlanHolds(directPlan, route, anthropicBody as Rec, config)) directLeaveError = leaveDirectPlan();
905
921
  if (directEncodersApply(config, route)) {
906
- clientEncoder = { protocol: "messages", stream, model: requestedModel, inputTokenFloor: claudeRequestTokenFloor() };
922
+ clientEncoder = { protocol: "messages", stream, model: clientFacingModelText(clientModelLabel), inputTokenFloor: claudeRequestTokenFloor() };
907
923
  }
908
924
  if (route.provider.adapter === "openai-responses") {
909
925
  // max_output_tokens is the caller's spend cap: the adapter strips it only for the canonical
@@ -933,8 +949,10 @@ async function handleClaudeMessagesWithBudget(
933
949
  } catch (err) {
934
950
  if (err instanceof AdmissionModelDeniedError) {
935
951
  logCtx.requestedModel = requestedModel;
952
+ projectAdmissionModelDeniedLog(err, logCtx);
953
+ const response = admissionModelDeniedResponse(err);
936
954
  if (logIds) addFinalRequestLog(logIds.requestId, logIds.start, logCtx, 403, { closeReason: "non_stream" });
937
- return admissionModelDeniedResponse(err);
955
+ return response;
938
956
  }
939
957
  if (err instanceof UnknownRoutingPolicyError) {
940
958
  logCtx.requestedModel = requestedModel;
@@ -954,7 +972,7 @@ async function handleClaudeMessagesWithBudget(
954
972
  // The direct lane answers through the direct encoder whatever `directEncoders` says: neither
955
973
  // direction passes through the internal Responses body.
956
974
  if (directRoute) {
957
- clientEncoder = { protocol: "messages", stream, model: requestedModel, inputTokenFloor: claudeRequestTokenFloor(), requestLane: "direct" };
975
+ clientEncoder = { protocol: "messages", stream, model: clientFacingModelText(clientModelLabel), inputTokenFloor: claudeRequestTokenFloor(), requestLane: "direct" };
958
976
  }
959
977
 
960
978
  // PF-08: a managed-key Anthropic route sends its Messages body natively. The caller-forward
@@ -1030,13 +1048,15 @@ async function handleClaudeMessagesWithBudget(
1030
1048
  openAiSidecar?.releaseProbeLease?.();
1031
1049
  throw req.signal.reason ?? err;
1032
1050
  }
1033
- if (!(err instanceof errors.CodexPoolAuthenticationError) && !(err instanceof errors.CodexAuthContextError)
1051
+ if (err instanceof CodexInstallationIdUnavailableError) {
1052
+ // An unavailable optional helper cannot displace an independent native route.
1053
+ nativeSelector.webSearchBackendAvailable = false;
1054
+ } else if (!(err instanceof errors.CodexPoolAuthenticationError) && !(err instanceof errors.CodexAuthContextError)
1034
1055
  && !(err instanceof errors.CodexAccountCooldownError) && !(err instanceof errors.CodexThreadAffinityExpiredError)
1035
1056
  && !(err instanceof errors.CodexMainProfileDrainingError)) {
1036
1057
  openAiSidecar?.releaseProbeLease?.();
1037
1058
  throw err;
1038
- }
1039
- if (probeLease && candidates.some(candidate => candidate.accountMode === "pool")) nativeSelector.webSearchBackendAvailable = true;
1059
+ } else if (probeLease && candidates.some(candidate => candidate.accountMode === "pool")) nativeSelector.webSearchBackendAvailable = true;
1040
1060
  } finally { probeLease?.release(); }
1041
1061
  }
1042
1062
  try {
@@ -1115,7 +1135,7 @@ async function handleClaudeMessagesWithBudget(
1115
1135
  const { handleNativeMessages } = await import("./messages-native");
1116
1136
  return await handleNativeMessages({
1117
1137
  req, config, logCtx, ...(logIds ? { logIds } : {}),
1118
- route: nativeMessagesRoute, body: nativeBody, requestedModel, translatorBudget, selector: nativeSelector,
1138
+ route: nativeMessagesRoute, body: nativeBody, requestedModel: clientFacingModelText(clientModelLabel), translatorBudget, selector: nativeSelector,
1119
1139
  modelScope: resolveAdmissionModelScope(config, logIds?.admission),
1120
1140
  // Compatibility identity is an opaque request-local handle, separate from credentials.
1121
1141
  clientIdentity: captureAnthropicClientIdentity(req.headers),
@@ -1173,6 +1193,9 @@ async function handleClaudeMessagesWithBudget(
1173
1193
  ?? normalizeLogConversationId(req.headers.get("x-opencode-session"))
1174
1194
  ?? metadataGoLane
1175
1195
  ?? getOrAllocateRequestSessionLane(req);
1196
+ const claudeBridgePoolSession = resolveClaudeBridgePoolSession({
1197
+ ingress: req.headers, replay: headers, metadataSessionId: claudeNativeSessionId, admission: logIds?.admission,
1198
+ });
1176
1199
  let internalReq: Request;
1177
1200
  try {
1178
1201
  // The UTF-16 JSON string and the Request's UTF-8 body coexist until dispatch.
@@ -1236,6 +1259,7 @@ async function handleClaudeMessagesWithBudget(
1236
1259
  ? { tools: anthropicBody.tools, messages: anthropicBody.messages, tool_choice: anthropicBody.tool_choice } : undefined,
1237
1260
  claudeGoAffinity: { sessionLane: claudeGoSessionLane },
1238
1261
  claudeNativeSessionId,
1262
+ ...(claudeBridgePoolSession ? { claudeBridgePoolSession } : {}),
1239
1263
  stripClaudeMainAuthForNoncanonicalForward: true,
1240
1264
  ...(trustedClaudeMainAuth ? { trustedClaudeMainAuth } : {}),
1241
1265
  // Claude's internal stored-main enrichment is not an original caller credential.
@@ -1245,6 +1269,7 @@ async function handleClaudeMessagesWithBudget(
1245
1269
  ...(logIds ? { onFirstOutput: () => recordFirstOutput(logCtx, logIds.start) } : {}),
1246
1270
  onNativePassthroughTerminal: status => finalizeNativeLog(httpStatusForRequestLogTerminal(status, logCtx), { terminalStatus: status, closeReason: "terminal" }),
1247
1271
  onNativePassthroughCancel: () => finalizeNativeLog(499, { closeReason: "client_cancel" }),
1272
+ clientModelLabel,
1248
1273
  ...(clientEncoder ? { clientEncoder } : {}),
1249
1274
  ...(directRoute && directPlan
1250
1275
  ? { directRequest: messagesDirectRequestOption(directPlan, anthropicBody, cc, translatorBudget) }
@@ -1266,11 +1291,15 @@ async function handleClaudeMessagesWithBudget(
1266
1291
  const text = await response.text();
1267
1292
  try {
1268
1293
  const parsed = JSON.parse(text) as { error?: { message?: string; type?: string; code?: unknown } | string; message?: string };
1269
- contextError = typeof parsed?.error === "object" && parsed.error?.code === "context_length_exceeded";
1270
1294
  catalogRefusal = typeof parsed?.error === "object" && parsed.error?.code === UNDECLARED_TOOL_CALL_ERROR_CODE;
1271
1295
  const nested = typeof parsed?.error === "object" && parsed.error ? parsed.error.message : undefined;
1272
1296
  const flat = typeof parsed?.error === "string" ? parsed.error : parsed?.message;
1273
1297
  message = nested || flat || (text ? `upstream error (${response.status}): ${text.slice(0, 400)}` : message);
1298
+ const errorObject = typeof parsed?.error === "object" && parsed.error ? parsed.error : {};
1299
+ // An uncoded overflow counts too (#8127); a rate-limit or credential status never does.
1300
+ contextError = errorObject.code === "context_length_exceeded"
1301
+ || (![401, 403, 429].includes(response.status) && Boolean(nested || flat)
1302
+ && isContextOverflowError(errorObject, message));
1274
1303
  } catch {
1275
1304
  if (text) message = `upstream error (${response.status}): ${text.slice(0, 400)}`;
1276
1305
  }
@@ -1304,7 +1333,8 @@ async function handleClaudeMessagesWithBudget(
1304
1333
  ? REPLAY_REFUSED_STATUS
1305
1334
  : nativeMainFence ? 503 : contextError ? 400 : transient ? 529 : response.status;
1306
1335
  const outHeaders = new Headers({ "Content-Type": "application/json" });
1307
- if (retryAfter) outHeaders.set("Retry-After", retryAfter);
1336
+ const clientRetryAfter = formatClientRetryAfter(retryAfter);
1337
+ if (clientRetryAfter) outHeaders.set("Retry-After", clientRetryAfter);
1308
1338
  else if (transient) outHeaders.set("Retry-After", "2");
1309
1339
  if (replayRefusal) applyReplayRefusalClientHeaders(outHeaders);
1310
1340
  const out = new Response(JSON.stringify(anthropicErrorBody(
@@ -1325,7 +1355,7 @@ async function handleClaudeMessagesWithBudget(
1325
1355
 
1326
1356
  const contentType = response.headers.get("content-type") ?? "";
1327
1357
  if (contentType.includes("text/event-stream") && response.body) {
1328
- const anthropicSse = responsesSseToAnthropicSse(response.body, requestedModel, {
1358
+ const anthropicSse = responsesSseToAnthropicSse(response.body, clientFacingModelText(clientModelLabel), {
1329
1359
  translatorBudget,
1330
1360
  nativeReasoningTagFor: blob => nativeReasoningTag(nativeReasoningMint.owner, blob),
1331
1361
  // Only a floor, and only for the first frame: an upstream that reports usage early wins
@@ -1345,7 +1375,7 @@ async function handleClaudeMessagesWithBudget(
1345
1375
  }
1346
1376
  let message: Rec;
1347
1377
  try {
1348
- message = await collectAnthropicMessage(anthropicSse, requestedModel, translatorBudget);
1378
+ message = await collectAnthropicMessage(anthropicSse, clientFacingModelText(clientModelLabel), translatorBudget);
1349
1379
  } catch (error) {
1350
1380
  if (isTranslatorBudgetExceededError(error)) {
1351
1381
  return anthropicErrorResponse(413, error.message, "request_too_large", error.code);
@@ -1399,14 +1429,14 @@ async function handleClaudeMessagesWithBudget(
1399
1429
  "translation_buffer_limit",
1400
1430
  );
1401
1431
  }
1402
- if (error?.code === "context_length_exceeded") {
1403
- return anthropicErrorResponse(400, error.message ?? "upstream context limit exceeded", "invalid_request_error", error.code);
1432
+ if (error && isContextOverflowError(error, typeof error.message === "string" ? error.message : "")) {
1433
+ return anthropicErrorResponse(400, error.message ?? "upstream context limit exceeded", "invalid_request_error", "context_length_exceeded");
1404
1434
  }
1405
1435
  return anthropicErrorResponse(502, error?.message ?? "upstream request failed", "api_error");
1406
1436
  }
1407
1437
  let message: Rec;
1408
1438
  try {
1409
- message = responsesJsonToAnthropicMessage(json, requestedModel, translatorBudget, blob => nativeReasoningTag(nativeReasoningMint.owner, blob));
1439
+ message = responsesJsonToAnthropicMessage(json, clientFacingModelText(clientModelLabel), translatorBudget, blob => nativeReasoningTag(nativeReasoningMint.owner, blob));
1410
1440
  } catch (err) {
1411
1441
  if (!isTranslatorBudgetExceededError(err)) throw err;
1412
1442
  return anthropicErrorResponse(413, "upstream translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit");