@bitkyc08/opencodex 2.96.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 (240) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-bwugJRKn.js → App-DuNhggE1.js} +15 -15
  3. package/gui/dist/assets/{Tray-BOPQyDbH.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-6HsrHQAy.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 +11 -1
  16. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  17. package/src/adapters/openai-responses/passthrough.ts +5 -4
  18. package/src/adapters/openai-responses/reasoning.ts +9 -4
  19. package/src/adapters/openai-responses/request-strips.ts +1 -1
  20. package/src/adapters/physical-send.ts +3 -3
  21. package/src/adapters/zed-openai-stream.ts +2 -1
  22. package/src/bridge/errors.ts +11 -2
  23. package/src/bridge/response-json.ts +2 -1
  24. package/src/bridge/sse.ts +14 -6
  25. package/src/chat/failure-verdict.ts +21 -0
  26. package/src/chat/outbound.ts +139 -21
  27. package/src/claude/outbound.ts +49 -2
  28. package/src/cli/capabilities-base.ts +25 -3
  29. package/src/cli/capabilities-command.ts +12 -3
  30. package/src/cli/capability-contracts.ts +2 -0
  31. package/src/cli/codex-launch-auth.ts +30 -1
  32. package/src/cli/codex-launcher.ts +12 -5
  33. package/src/cli/codex-shim-autorestore.ts +5 -4
  34. package/src/cli/dispatch.ts +11 -176
  35. package/src/cli/help.ts +2 -2
  36. package/src/cli/index.ts +5 -1
  37. package/src/cli/link.ts +1 -1
  38. package/src/cli/registry.ts +11 -3
  39. package/src/cli/root.ts +8 -0
  40. package/src/cli/sync-command.ts +243 -0
  41. package/src/cli/sync-fanout-process.ts +92 -0
  42. package/src/cli/sync-fanout.ts +150 -0
  43. package/src/cli/sync-flags.ts +10 -0
  44. package/src/cli/sync-link-status.ts +39 -0
  45. package/src/cli/sync-update-guard.ts +18 -0
  46. package/src/client/connect.ts +31 -14
  47. package/src/client/link-home.ts +3 -2
  48. package/src/client/machine-listener.ts +3 -0
  49. package/src/client/restore-ownership.ts +19 -1
  50. package/src/client/runtime-restart.ts +12 -4
  51. package/src/client/runtime.ts +40 -11
  52. package/src/client/stop-routing.ts +62 -0
  53. package/src/client/sync-runtime.ts +65 -0
  54. package/src/clients/config-export.ts +32 -3
  55. package/src/codex/auth-context.ts +49 -103
  56. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  57. package/src/codex/catalog/provider-models.ts +6 -8
  58. package/src/codex/forward-transport-headers.ts +35 -6
  59. package/src/codex/inject/config-toml.ts +88 -0
  60. package/src/codex/inject/multi-agent-v2.ts +30 -4
  61. package/src/codex/inject/plan.ts +34 -7
  62. package/src/codex/inject-coordination.ts +11 -0
  63. package/src/codex/inject.ts +18 -7
  64. package/src/codex/lineage.ts +13 -7
  65. package/src/codex/quota.ts +22 -6
  66. package/src/codex/request-owned-affinity-key.ts +11 -0
  67. package/src/codex/request-owned-affinity.ts +118 -0
  68. package/src/codex/request-owned-main-pin.ts +86 -0
  69. package/src/codex/role-capability.ts +52 -41
  70. package/src/codex/routing/active-account.ts +13 -5
  71. package/src/codex/routing/selection.ts +40 -1
  72. package/src/codex/routing/thread-affinity-store.ts +916 -0
  73. package/src/codex/routing/thread-affinity.ts +90 -12
  74. package/src/codex/toml-source-lines.ts +72 -13
  75. package/src/combos/failover.ts +6 -109
  76. package/src/combos/request.ts +2 -2
  77. package/src/combos/resolve.ts +29 -11
  78. package/src/config/process-state.ts +5 -0
  79. package/src/config/schema/leaf-validators.ts +1 -0
  80. package/src/generated/compatibility-version.json +433 -165
  81. package/src/images/loop.ts +2 -1
  82. package/src/lib/client-error-body.ts +184 -0
  83. package/src/lib/client-retry-after.ts +66 -0
  84. package/src/lib/config-ownership.ts +4 -0
  85. package/src/lib/context-overflow-verdict.ts +113 -0
  86. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  87. package/src/lib/desktop-cli-handoff.mjs +11 -1
  88. package/src/lib/empty-tool-catalog.ts +25 -3
  89. package/src/lib/error-destination.ts +47 -0
  90. package/src/lib/failure-detail.ts +66 -0
  91. package/src/lib/model-identity.ts +44 -0
  92. package/src/lib/private-sqlite-path.ts +124 -0
  93. package/src/lib/response-service-tier.ts +17 -0
  94. package/src/lib/retry-after.ts +3 -0
  95. package/src/lib/spend-ledger-owner.ts +43 -4
  96. package/src/lib/upstream-condition.ts +142 -0
  97. package/src/lib/upstream-retry.ts +14 -11
  98. package/src/lib/windows-owner-acl.ts +13 -6
  99. package/src/link/remote-platform.ts +14 -0
  100. package/src/link/remote-windows.ts +51 -9
  101. package/src/link/ssh-argv.ts +63 -10
  102. package/src/oauth/generic-account-failover.ts +13 -11
  103. package/src/oauth/index.ts +36 -74
  104. package/src/oauth/oauth-errors.ts +67 -0
  105. package/src/oauth/store.ts +1 -1
  106. package/src/protocols/codecs/ollama.ts +197 -0
  107. package/src/protocols/encoders/adapter-events.ts +4 -0
  108. package/src/protocols/encoders/chat.ts +18 -10
  109. package/src/protocols/trace.ts +18 -0
  110. package/src/providers/fastwire.ts +3 -2
  111. package/src/providers/quota/anthropic-usage-windows.ts +13 -3
  112. package/src/providers/quota/vendor-probes-key.ts +60 -24
  113. package/src/providers/request-pacing.ts +3 -2
  114. package/src/responses/apply-patch-envelope.ts +45 -19
  115. package/src/responses/compaction-history-framing.ts +5 -1
  116. package/src/responses/freeform-wrapper-scan.ts +5 -3
  117. package/src/responses/progressive-freeform-input.ts +354 -45
  118. package/src/routing/fallback-policy.ts +3 -1
  119. package/src/server/admission-model-scope.ts +17 -6
  120. package/src/server/admitted-http-turn.ts +56 -0
  121. package/src/server/auth-cors.ts +5 -0
  122. package/src/server/chat-completions.ts +45 -20
  123. package/src/server/chat-native-sse.ts +52 -7
  124. package/src/server/chat-native.ts +60 -35
  125. package/src/server/claude-bridge-pool-session.ts +59 -0
  126. package/src/server/claude-messages.ts +51 -24
  127. package/src/server/context-history.ts +5 -1
  128. package/src/server/inbound-body-admission.ts +11 -4
  129. package/src/server/index/ollama-routes.ts +89 -0
  130. package/src/server/index/serve-options.ts +21 -4
  131. package/src/server/index/websocket-handler.ts +4 -2
  132. package/src/server/index.ts +6 -36
  133. package/src/server/inference/client-encoder-delivery.ts +4 -2
  134. package/src/server/json-serialized-bytes.ts +44 -0
  135. package/src/server/management/agent-settings-routes.ts +24 -21
  136. package/src/server/management/codex-cli-update-routes.ts +2 -1
  137. package/src/server/management/route-registry.ts +1 -1
  138. package/src/server/messages-native-scope.ts +2 -1
  139. package/src/server/messages-native-tool-guard.ts +1 -1
  140. package/src/server/messages-native.ts +12 -7
  141. package/src/server/messages-shared.ts +6 -2
  142. package/src/server/native-final-log.ts +93 -0
  143. package/src/server/ollama-inbound.ts +349 -0
  144. package/src/server/ollama-native-paths.ts +21 -0
  145. package/src/server/ollama-route-policy.ts +73 -0
  146. package/src/server/relay.ts +22 -3
  147. package/src/server/request-decompress.ts +4 -2
  148. package/src/server/request-log-failure-attribution.ts +22 -0
  149. package/src/server/request-log-failure-detail.ts +80 -0
  150. package/src/server/request-log-terminal-status.ts +4 -2
  151. package/src/server/request-log.ts +79 -42
  152. package/src/server/response-log-body.ts +6 -1
  153. package/src/server/responses/account-change-state.ts +17 -6
  154. package/src/server/responses/adapter-continuation.ts +9 -4
  155. package/src/server/responses/adapter-delivery.ts +5 -4
  156. package/src/server/responses/adapter-dispatch.ts +31 -30
  157. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  158. package/src/server/responses/codex-auth-error.ts +19 -18
  159. package/src/server/responses/codex-ws-exchange.ts +11 -8
  160. package/src/server/responses/codex-ws-metadata.ts +94 -21
  161. package/src/server/responses/codex-ws-request.ts +3 -1
  162. package/src/server/responses/compact.ts +53 -23
  163. package/src/server/responses/compaction-recovery.ts +4 -2
  164. package/src/server/responses/compaction-routing.ts +9 -4
  165. package/src/server/responses/core-auth.ts +32 -14
  166. package/src/server/responses/core-codex-account.ts +17 -6
  167. package/src/server/responses/core-combo-failure.ts +5 -1
  168. package/src/server/responses/core-combo-native.ts +2 -1
  169. package/src/server/responses/core-combo.ts +41 -27
  170. package/src/server/responses/core-errors.ts +22 -20
  171. package/src/server/responses/core-lifetime.ts +6 -3
  172. package/src/server/responses/core-normalize.ts +1 -0
  173. package/src/server/responses/core-options.ts +7 -0
  174. package/src/server/responses/core-pipeline.ts +4 -3
  175. package/src/server/responses/fetch-helpers.ts +7 -1
  176. package/src/server/responses/input-admission.ts +28 -2
  177. package/src/server/responses/native-injection.ts +1 -1
  178. package/src/server/responses/native-response-json.ts +13 -4
  179. package/src/server/responses/native-response-output.ts +1 -2
  180. package/src/server/responses/non-replayable-error.ts +2 -1
  181. package/src/server/responses/pacing-overload.ts +3 -2
  182. package/src/server/responses/passthrough-delivery.ts +55 -14
  183. package/src/server/responses/passthrough-dispatch.ts +19 -17
  184. package/src/server/responses/passthrough-error.ts +9 -9
  185. package/src/server/responses/policy-fallback.ts +2 -1
  186. package/src/server/responses/request-prepare.ts +67 -48
  187. package/src/server/responses/request-transport.ts +35 -31
  188. package/src/server/responses/run-turn-execution.ts +6 -6
  189. package/src/server/responses/sidecar-execution.ts +16 -12
  190. package/src/server/responses/spend-storage-error.ts +2 -1
  191. package/src/server/responses/ws-upstream.ts +9 -0
  192. package/src/server/responses-custom-tool-repair.ts +14 -3
  193. package/src/server/responses-terminal-repair.ts +5 -2
  194. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  195. package/src/server/safe-response-headers.ts +162 -13
  196. package/src/server/turn-state-handles.ts +164 -0
  197. package/src/server/workflow-refusal.ts +2 -1
  198. package/src/service/ownership-mutation-lease.d.mts +11 -2
  199. package/src/service/ownership-mutation-lease.mjs +53 -11
  200. package/src/types/config.ts +2 -0
  201. package/src/update/index.ts +133 -25
  202. package/src/update/npm-install.d.mts +8 -0
  203. package/src/update/npm-install.mjs +20 -1
  204. package/src/update/orchestrated-admission.d.mts +4 -0
  205. package/src/update/orchestrated-admission.mjs +12 -0
  206. package/src/update/orchestrated-arguments.d.mts +12 -0
  207. package/src/update/orchestrated-arguments.mjs +64 -0
  208. package/src/update/orchestrated-child.d.mts +12 -0
  209. package/src/update/orchestrated-child.mjs +70 -0
  210. package/src/update/orchestrated-entry.ts +234 -0
  211. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  212. package/src/update/orchestrated-identity.ts +53 -0
  213. package/src/update/orchestrated-live-identity.ts +48 -0
  214. package/src/update/orchestrated-node-driver.mjs +99 -0
  215. package/src/update/orchestrated-outcome.d.mts +21 -0
  216. package/src/update/orchestrated-outcome.mjs +40 -0
  217. package/src/update/orchestrated-plan.ts +49 -0
  218. package/src/update/orchestrated-pnpm.d.mts +8 -0
  219. package/src/update/orchestrated-pnpm.mjs +33 -0
  220. package/src/update/orchestrated-session.d.mts +37 -0
  221. package/src/update/orchestrated-session.mjs +264 -0
  222. package/src/update/orchestrated-token.d.mts +10 -0
  223. package/src/update/orchestrated-token.mjs +21 -0
  224. package/src/update/orchestrated-token.ts +3 -0
  225. package/src/update/orchestrated-tree.d.mts +1 -0
  226. package/src/update/orchestrated-tree.mjs +14 -0
  227. package/src/update/pnpm-global-install.d.mts +6 -0
  228. package/src/update/pnpm-global-install.mjs +9 -2
  229. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  230. package/src/update/posix-install-supervisor.d.mts +10 -0
  231. package/src/update/posix-install-supervisor.mjs +88 -0
  232. package/src/update/sync-update-mutex.d.mts +10 -0
  233. package/src/update/sync-update-mutex.mjs +164 -0
  234. package/src/update/sync-update-mutex.ts +1 -0
  235. package/src/update/test-home-guard.mjs +33 -0
  236. package/src/update/transactional-install.mjs +2 -2
  237. package/src/usage/error-detail.ts +225 -0
  238. package/src/usage/log.ts +60 -27
  239. package/src/web-search/loop.ts +31 -5
  240. package/gui/dist/assets/index-ebuVUtB7.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,4 +1,7 @@
1
+ import { clientFacingModelLabel, clientFacingModelText } from "../lib/error-destination";
2
+ import { classifyUpstreamCondition } from "../lib/upstream-condition";
1
3
  import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
4
+ import { recordLocalFailureDetail, type FailureDetail } from "./request-log-failure-detail";
2
5
  /**
3
6
  * Anthropic Messages inbound (/v1/messages + /v1/messages/count_tokens) for Claude Code.
4
7
  *
@@ -8,8 +11,9 @@ import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
8
11
  * unchanged. The Responses output (SSE or JSON) is converted back to Anthropic shape.
9
12
  */
10
13
  import { FORWARD_HEADERS } from "../adapters/openai-responses";
14
+ import { resolveClaudeBridgePoolSession } from "./claude-bridge-pool-session";
11
15
  import {
12
- admissionModelDeniedResponse,
16
+ admissionModelDeniedResponse, projectAdmissionModelDeniedLog,
13
17
  AdmissionModelDeniedError,
14
18
  assertRouteAllowedByScope,
15
19
  resolveAdmissionModelScope,
@@ -50,13 +54,14 @@ import {
50
54
  UPSTREAM_RESET_REPLAY_REFUSED_CODE,
51
55
  } from "../lib/upstream-retry";
52
56
  import { isClientClosedMessage, recognizedUpstreamError, UNDECLARED_TOOL_CALL_ERROR_CODE } from "../lib/errors";
53
- import { resolveClientRetryAfter } from "../lib/retry-after";
57
+ import { formatClientRetryAfter, resolveClientRetryAfter } from "../lib/retry-after";
54
58
  import { anthropicRateLimitHeaders } from "./anthropic-rate-limit-headers";
55
59
  import { upstreamMessagesRequestIdHeaders } from "./messages-response-headers";
56
60
  import {
57
61
  anthropicErrorBody,
58
62
  anthropicErrorResponse,
59
63
  collectAnthropicMessage,
64
+ isContextOverflowError,
60
65
  responsesJsonToAnthropicMessage,
61
66
  responsesSseToAnthropicSse,
62
67
  } from "../claude/outbound";
@@ -335,9 +340,10 @@ async function anthropicNativePassthrough(
335
340
  const finalize = createFinalRequestLog(logIds, logCtx).finish;
336
341
  // Locally generated diagnostics are fixed text plus validated guard limits. Runtime
337
342
  // fetch errors retain their existing client response but use a fixed stored reason.
338
- 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) => {
339
345
  const safeMessage = redactSecretString(message);
340
- logCtx.upstreamError = storedReason.slice(0, 500);
346
+ recordLocalFailureDetail(logCtx, storedReason, detail);
341
347
  finalize(status, { closeReason });
342
348
  return anthropicErrorResponse(status, safeMessage, type);
343
349
  };
@@ -369,11 +375,11 @@ async function anthropicNativePassthrough(
369
375
  req.signal,
370
376
  );
371
377
  if (result.kind === "timeout") {
372
- 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" });
373
379
  }
374
380
  if (result.kind === "error") {
375
381
  const err = result.error;
376
- 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");
377
383
  }
378
384
  const upstream = result.upstream;
379
385
 
@@ -398,13 +404,15 @@ async function anthropicNativePassthrough(
398
404
  // idle/size bounds — headers are NOT yet sent here, so real statuses are available.
399
405
  const bodyResult = await readBoundedPassthroughBody(upstream, bodyGuard);
400
406
  if (bodyResult.kind === "client_cancel") {
401
- 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" });
402
408
  }
403
409
  if (bodyResult.kind === "stall") {
404
- 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 });
405
412
  }
406
413
  if (bodyResult.kind === "overflow") {
407
- 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 });
408
416
  }
409
417
  const text = bodyResult.text;
410
418
  if (upstream.ok) {
@@ -416,20 +424,25 @@ async function anthropicNativePassthrough(
416
424
  // Upstream text is untrusted: retain only a closed type vocabulary in history.
417
425
  // Bound parsing work independently of the larger response-relay body limit.
418
426
  const statusReason = `Provider error ${upstream.status}`;
419
- logCtx.upstreamError = statusReason;
427
+ recordLocalFailureDetail(logCtx, statusReason, { code: "provider_error" }, { upstreamEvidence: true });
420
428
  if (text.length <= PASSTHROUGH_ERROR_DETAIL_MAX_CHARS) {
421
429
  try {
422
430
  const parsed: unknown = JSON.parse(text);
423
431
  if (isRec(parsed) && parsed.type === "error" && isRec(parsed.error)) {
424
432
  const upstreamType = parsed.error.type;
425
433
  const knownType = PASSTHROUGH_ERROR_TYPES.find(type => type === upstreamType);
426
- 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 });
427
440
  }
428
441
  } catch { /* Malformed errors keep the fixed status-only diagnostic. */ }
429
442
  }
430
443
  }
431
444
  finalize(upstream.status, { closeReason: "non_stream" });
432
- const retryAfter = upstream.headers.get("retry-after");
445
+ const retryAfter = formatClientRetryAfter(upstream.headers.get("retry-after"));
433
446
  return new Response(text, {
434
447
  status: upstream.status,
435
448
  headers: { ...rateLimitHeaders, "Content-Type": contentType, ...(retryAfter ? { "Retry-After": retryAfter } : {}) },
@@ -619,6 +632,7 @@ async function handleClaudeMessagesWithBudget(
619
632
  let effortRow: ParsedEffortRowId | null = null;
620
633
  let fastRow: ParsedFastRowId | null = null;
621
634
  let requestedModel = "";
635
+ let clientModelLabel = clientFacingModelLabel(undefined);
622
636
  // Antigravity direct lane (off by default): planned before translation, kept only if routing
623
637
  // settles on the route the plan was made for.
624
638
  let directPlan: MessagesDirectPlan | undefined;
@@ -631,6 +645,7 @@ async function handleClaudeMessagesWithBudget(
631
645
  const advisorAdmissionPolicy = logIds?.advisorAdmissionPolicy ?? captureAdmissionPolicy(config, logIds?.admission);
632
646
  try {
633
647
  anthropicBody = await readAnthropicBody(req, translatorBudget, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes));
648
+ clientModelLabel = clientFacingModelLabel(isRec(anthropicBody) ? anthropicBody.model : undefined);
634
649
  // Defensive [1m] strip (devlog 138): clients normally remove the context-variant
635
650
  // marker themselves; the 1M signal we act on is the anthropic-beta header.
636
651
  // Case-insensitive — the CLI matches /\[1m\]/i (audit 021 #7).
@@ -893,7 +908,7 @@ async function handleClaudeMessagesWithBudget(
893
908
  // the same billed Fast lane as their final Responses scope check.
894
909
  assertRouteAllowedByScope(
895
910
  resolveAdmissionModelScope(config, logIds?.admission),
896
- String(internalBody.model ?? ""),
911
+ clientModelLabel,
897
912
  { providerName: route.providerName, modelId: previewXaiOauthWireModel({ options: {
898
913
  serviceTier: typeof internalBody.service_tier === "string" ? internalBody.service_tier : undefined,
899
914
  } }, route, config, "anthropic") },
@@ -904,7 +919,7 @@ async function handleClaudeMessagesWithBudget(
904
919
  // Before any route-specific shaping, so a request that leaves the lane is shaped as the bridge's.
905
920
  if (directPlan && !messagesDirectPlanHolds(directPlan, route, anthropicBody as Rec, config)) directLeaveError = leaveDirectPlan();
906
921
  if (directEncodersApply(config, route)) {
907
- clientEncoder = { protocol: "messages", stream, model: requestedModel, inputTokenFloor: claudeRequestTokenFloor() };
922
+ clientEncoder = { protocol: "messages", stream, model: clientFacingModelText(clientModelLabel), inputTokenFloor: claudeRequestTokenFloor() };
908
923
  }
909
924
  if (route.provider.adapter === "openai-responses") {
910
925
  // max_output_tokens is the caller's spend cap: the adapter strips it only for the canonical
@@ -934,8 +949,10 @@ async function handleClaudeMessagesWithBudget(
934
949
  } catch (err) {
935
950
  if (err instanceof AdmissionModelDeniedError) {
936
951
  logCtx.requestedModel = requestedModel;
952
+ projectAdmissionModelDeniedLog(err, logCtx);
953
+ const response = admissionModelDeniedResponse(err);
937
954
  if (logIds) addFinalRequestLog(logIds.requestId, logIds.start, logCtx, 403, { closeReason: "non_stream" });
938
- return admissionModelDeniedResponse(err);
955
+ return response;
939
956
  }
940
957
  if (err instanceof UnknownRoutingPolicyError) {
941
958
  logCtx.requestedModel = requestedModel;
@@ -955,7 +972,7 @@ async function handleClaudeMessagesWithBudget(
955
972
  // The direct lane answers through the direct encoder whatever `directEncoders` says: neither
956
973
  // direction passes through the internal Responses body.
957
974
  if (directRoute) {
958
- clientEncoder = { protocol: "messages", stream, model: requestedModel, inputTokenFloor: claudeRequestTokenFloor(), requestLane: "direct" };
975
+ clientEncoder = { protocol: "messages", stream, model: clientFacingModelText(clientModelLabel), inputTokenFloor: claudeRequestTokenFloor(), requestLane: "direct" };
959
976
  }
960
977
 
961
978
  // PF-08: a managed-key Anthropic route sends its Messages body natively. The caller-forward
@@ -1118,7 +1135,7 @@ async function handleClaudeMessagesWithBudget(
1118
1135
  const { handleNativeMessages } = await import("./messages-native");
1119
1136
  return await handleNativeMessages({
1120
1137
  req, config, logCtx, ...(logIds ? { logIds } : {}),
1121
- route: nativeMessagesRoute, body: nativeBody, requestedModel, translatorBudget, selector: nativeSelector,
1138
+ route: nativeMessagesRoute, body: nativeBody, requestedModel: clientFacingModelText(clientModelLabel), translatorBudget, selector: nativeSelector,
1122
1139
  modelScope: resolveAdmissionModelScope(config, logIds?.admission),
1123
1140
  // Compatibility identity is an opaque request-local handle, separate from credentials.
1124
1141
  clientIdentity: captureAnthropicClientIdentity(req.headers),
@@ -1176,6 +1193,9 @@ async function handleClaudeMessagesWithBudget(
1176
1193
  ?? normalizeLogConversationId(req.headers.get("x-opencode-session"))
1177
1194
  ?? metadataGoLane
1178
1195
  ?? getOrAllocateRequestSessionLane(req);
1196
+ const claudeBridgePoolSession = resolveClaudeBridgePoolSession({
1197
+ ingress: req.headers, replay: headers, metadataSessionId: claudeNativeSessionId, admission: logIds?.admission,
1198
+ });
1179
1199
  let internalReq: Request;
1180
1200
  try {
1181
1201
  // The UTF-16 JSON string and the Request's UTF-8 body coexist until dispatch.
@@ -1239,6 +1259,7 @@ async function handleClaudeMessagesWithBudget(
1239
1259
  ? { tools: anthropicBody.tools, messages: anthropicBody.messages, tool_choice: anthropicBody.tool_choice } : undefined,
1240
1260
  claudeGoAffinity: { sessionLane: claudeGoSessionLane },
1241
1261
  claudeNativeSessionId,
1262
+ ...(claudeBridgePoolSession ? { claudeBridgePoolSession } : {}),
1242
1263
  stripClaudeMainAuthForNoncanonicalForward: true,
1243
1264
  ...(trustedClaudeMainAuth ? { trustedClaudeMainAuth } : {}),
1244
1265
  // Claude's internal stored-main enrichment is not an original caller credential.
@@ -1248,6 +1269,7 @@ async function handleClaudeMessagesWithBudget(
1248
1269
  ...(logIds ? { onFirstOutput: () => recordFirstOutput(logCtx, logIds.start) } : {}),
1249
1270
  onNativePassthroughTerminal: status => finalizeNativeLog(httpStatusForRequestLogTerminal(status, logCtx), { terminalStatus: status, closeReason: "terminal" }),
1250
1271
  onNativePassthroughCancel: () => finalizeNativeLog(499, { closeReason: "client_cancel" }),
1272
+ clientModelLabel,
1251
1273
  ...(clientEncoder ? { clientEncoder } : {}),
1252
1274
  ...(directRoute && directPlan
1253
1275
  ? { directRequest: messagesDirectRequestOption(directPlan, anthropicBody, cc, translatorBudget) }
@@ -1269,11 +1291,15 @@ async function handleClaudeMessagesWithBudget(
1269
1291
  const text = await response.text();
1270
1292
  try {
1271
1293
  const parsed = JSON.parse(text) as { error?: { message?: string; type?: string; code?: unknown } | string; message?: string };
1272
- contextError = typeof parsed?.error === "object" && parsed.error?.code === "context_length_exceeded";
1273
1294
  catalogRefusal = typeof parsed?.error === "object" && parsed.error?.code === UNDECLARED_TOOL_CALL_ERROR_CODE;
1274
1295
  const nested = typeof parsed?.error === "object" && parsed.error ? parsed.error.message : undefined;
1275
1296
  const flat = typeof parsed?.error === "string" ? parsed.error : parsed?.message;
1276
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));
1277
1303
  } catch {
1278
1304
  if (text) message = `upstream error (${response.status}): ${text.slice(0, 400)}`;
1279
1305
  }
@@ -1307,7 +1333,8 @@ async function handleClaudeMessagesWithBudget(
1307
1333
  ? REPLAY_REFUSED_STATUS
1308
1334
  : nativeMainFence ? 503 : contextError ? 400 : transient ? 529 : response.status;
1309
1335
  const outHeaders = new Headers({ "Content-Type": "application/json" });
1310
- if (retryAfter) outHeaders.set("Retry-After", retryAfter);
1336
+ const clientRetryAfter = formatClientRetryAfter(retryAfter);
1337
+ if (clientRetryAfter) outHeaders.set("Retry-After", clientRetryAfter);
1311
1338
  else if (transient) outHeaders.set("Retry-After", "2");
1312
1339
  if (replayRefusal) applyReplayRefusalClientHeaders(outHeaders);
1313
1340
  const out = new Response(JSON.stringify(anthropicErrorBody(
@@ -1328,7 +1355,7 @@ async function handleClaudeMessagesWithBudget(
1328
1355
 
1329
1356
  const contentType = response.headers.get("content-type") ?? "";
1330
1357
  if (contentType.includes("text/event-stream") && response.body) {
1331
- const anthropicSse = responsesSseToAnthropicSse(response.body, requestedModel, {
1358
+ const anthropicSse = responsesSseToAnthropicSse(response.body, clientFacingModelText(clientModelLabel), {
1332
1359
  translatorBudget,
1333
1360
  nativeReasoningTagFor: blob => nativeReasoningTag(nativeReasoningMint.owner, blob),
1334
1361
  // Only a floor, and only for the first frame: an upstream that reports usage early wins
@@ -1348,7 +1375,7 @@ async function handleClaudeMessagesWithBudget(
1348
1375
  }
1349
1376
  let message: Rec;
1350
1377
  try {
1351
- message = await collectAnthropicMessage(anthropicSse, requestedModel, translatorBudget);
1378
+ message = await collectAnthropicMessage(anthropicSse, clientFacingModelText(clientModelLabel), translatorBudget);
1352
1379
  } catch (error) {
1353
1380
  if (isTranslatorBudgetExceededError(error)) {
1354
1381
  return anthropicErrorResponse(413, error.message, "request_too_large", error.code);
@@ -1402,14 +1429,14 @@ async function handleClaudeMessagesWithBudget(
1402
1429
  "translation_buffer_limit",
1403
1430
  );
1404
1431
  }
1405
- if (error?.code === "context_length_exceeded") {
1406
- 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");
1407
1434
  }
1408
1435
  return anthropicErrorResponse(502, error?.message ?? "upstream request failed", "api_error");
1409
1436
  }
1410
1437
  let message: Rec;
1411
1438
  try {
1412
- message = responsesJsonToAnthropicMessage(json, requestedModel, translatorBudget, blob => nativeReasoningTag(nativeReasoningMint.owner, blob));
1439
+ message = responsesJsonToAnthropicMessage(json, clientFacingModelText(clientModelLabel), translatorBudget, blob => nativeReasoningTag(nativeReasoningMint.owner, blob));
1413
1440
  } catch (err) {
1414
1441
  if (!isTranslatorBudgetExceededError(err)) throw err;
1415
1442
  return anthropicErrorResponse(413, "upstream translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit");
@@ -1,3 +1,4 @@
1
+ import { formatClientRetryAfter } from "../lib/client-retry-after";
1
2
  import { isolateCodexPoolClientMetadata, mergeCodexSelectedHeaders } from "../codex/forward-transport-headers";
2
3
  import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
3
4
  /** Native history/notes JSON relay. No interpretation of encrypted tool arguments or retries. */
@@ -185,7 +186,10 @@ async function relayContextHistory(
185
186
  if (result.oversized) return formatErrorResponse(502, "upstream_error", "Context response exceeded 16 MiB");
186
187
  const outputHeaders = new Headers();
187
188
  for (const key of RESPONSE_HEADERS) {
188
- const value = response.headers.get(key); if (value !== null) outputHeaders.set(key, value);
189
+ const raw = response.headers.get(key);
190
+ // Retry advice leaves as an integer this proxy formats, never the upstream bytes.
191
+ const value = key === "retry-after" ? formatClientRetryAfter(raw) ?? null : raw;
192
+ if (value !== null) outputHeaders.set(key, value);
189
193
  }
190
194
  // A context 403 is not evidence that the model credential is invalid. Don't mutate pool
191
195
  // health/quota or retry writes; preserve the real upstream result for the caller.