@bitkyc08/opencodex 2.100.1 → 2.100.2

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 (163) hide show
  1. package/gui/dist/assets/App-BpJOzw4F.js +59 -0
  2. package/gui/dist/assets/Tray-BcaI-VCr.js +1 -0
  3. package/gui/dist/assets/{brand-mark-nr3ziR-T.js → brand-mark-DU-0Vdkr.js} +1 -1
  4. package/gui/dist/assets/index-Bbor_y80.js +94 -0
  5. package/gui/dist/assets/index-DJEkIDAi.css +2 -0
  6. package/gui/dist/assets/{segment-thumb-features-DKCVUUTi.js → segment-thumb-features-e9A_FogJ.js} +1 -1
  7. package/gui/dist/classic/assets/{App-CgPBKUP-.js → App-BrIlUiLc.js} +18 -18
  8. package/gui/dist/classic/assets/{Tray-BedmOsE7.js → Tray-DT146AhS.js} +1 -1
  9. package/gui/dist/classic/assets/index-DyJHagvT.js +94 -0
  10. package/gui/dist/classic/assets/quota-summary-CakPe9Ni.js +1 -0
  11. package/gui/dist/classic/index.html +1 -1
  12. package/gui/dist/index.html +2 -2
  13. package/package.json +2 -2
  14. package/src/adapters/client-fingerprint.ts +5 -3
  15. package/src/adapters/cursor/native-exec.ts +3 -2
  16. package/src/adapters/cursor/tool-guidance.ts +3 -3
  17. package/src/adapters/cursor/tool-wording.ts +10 -1
  18. package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
  19. package/src/adapters/google-antigravity-wire.ts +13 -6
  20. package/src/adapters/google-truncation.ts +4 -2
  21. package/src/adapters/google.ts +8 -2
  22. package/src/adapters/openai-chat/tool-schema.ts +9 -0
  23. package/src/adapters/openai-responses/tool-schema.ts +18 -4
  24. package/src/adapters/run-turn-queue.ts +139 -5
  25. package/src/adapters/upstream-http-error.ts +4 -2
  26. package/src/bridge/sse.ts +8 -1
  27. package/src/claude/chat-tool-dispatch.ts +233 -0
  28. package/src/claude/inbound-tool-loading.ts +42 -17
  29. package/src/cli/account-api.ts +6 -0
  30. package/src/cli/account-extended.ts +60 -6
  31. package/src/cli/account-key-quota.ts +22 -2
  32. package/src/cli/account.ts +1 -1
  33. package/src/cli/capabilities-access-remote.ts +10 -0
  34. package/src/cli/capabilities-agents-routing.ts +2 -2
  35. package/src/cli/capabilities-base.ts +2 -2
  36. package/src/cli/claude.ts +19 -14
  37. package/src/cli/config-command.ts +24 -1
  38. package/src/cli/connect.ts +36 -3
  39. package/src/cli/gui-pair-client.ts +23 -2
  40. package/src/cli/help.ts +1 -1
  41. package/src/cli/hub.ts +18 -1
  42. package/src/cli/link-child-ops.ts +136 -0
  43. package/src/cli/link-status-child.ts +94 -0
  44. package/src/cli/link.ts +22 -9
  45. package/src/cli/registry.ts +3 -2
  46. package/src/cli/sync-command.ts +3 -1
  47. package/src/cli/sync-fanout.ts +8 -81
  48. package/src/client/link-readiness.ts +16 -6
  49. package/src/client/link-tunnel-status.ts +76 -0
  50. package/src/clients/config-export.ts +14 -1
  51. package/src/codex/account-resume-health.ts +41 -0
  52. package/src/codex/auth-api/login-flow.ts +6 -0
  53. package/src/codex/auth-api/routes.ts +35 -2
  54. package/src/codex/catalog/gather-capture.ts +2 -0
  55. package/src/codex/catalog/provider-models.ts +13 -8
  56. package/src/codex/convergence-types.ts +2 -0
  57. package/src/codex/quota.ts +111 -6
  58. package/src/combos/cooldown-store.ts +208 -0
  59. package/src/combos/failover.ts +432 -35
  60. package/src/config/salvage.ts +1 -0
  61. package/src/config/schema/config-schema.ts +6 -3
  62. package/src/config/schema/leaf-validators.ts +34 -12
  63. package/src/generated/compatibility-version.json +213 -121
  64. package/src/lib/catalog-etag.ts +10 -0
  65. package/src/lib/client-error-body.ts +15 -0
  66. package/src/lib/context-overflow-verdict.ts +266 -9
  67. package/src/lib/failure-detail.ts +72 -3
  68. package/src/lib/hard-refusal.ts +259 -0
  69. package/src/link/child-activity.ts +57 -0
  70. package/src/link/child-catalog-freshness.ts +149 -0
  71. package/src/link/child-gated-ocx.ts +117 -0
  72. package/src/link/child-observations.ts +205 -0
  73. package/src/link/child-observe.ts +121 -0
  74. package/src/link/child-ops-engine.ts +162 -0
  75. package/src/link/child-update-contract.ts +165 -0
  76. package/src/link/paths.ts +5 -0
  77. package/src/link/remote-windows.ts +42 -6
  78. package/src/link/ssh-argv.ts +126 -32
  79. package/src/link/status-projection.ts +73 -0
  80. package/src/link/sync-fanout-classify.ts +98 -0
  81. package/src/link/tunnel-state.ts +10 -4
  82. package/src/messaging/mcp-queue-rpc.ts +2 -1
  83. package/src/messaging/mcp-queue-server.ts +5 -0
  84. package/src/messaging/mcp-reply-tools.ts +24 -9
  85. package/src/messaging/mcp-reply-wait.ts +70 -0
  86. package/src/oauth/account-resume-health.ts +60 -0
  87. package/src/oauth/index.ts +1 -0
  88. package/src/oauth/store.ts +44 -1
  89. package/src/providers/api-key-pause-state.ts +23 -0
  90. package/src/providers/api-key-pause.ts +68 -10
  91. package/src/providers/api-key-selection-capture.ts +3 -1
  92. package/src/providers/api-key-selection.ts +3 -2
  93. package/src/providers/api-keys.ts +18 -5
  94. package/src/providers/claude-cli-usage-state.ts +11 -6
  95. package/src/providers/claude-cli-usage.ts +27 -9
  96. package/src/providers/codex-capacity.ts +11 -2
  97. package/src/providers/key-failover.ts +13 -6
  98. package/src/providers/model-discovery-config.ts +31 -0
  99. package/src/providers/model-discovery-diagnostic.ts +34 -3
  100. package/src/providers/model-discovery.ts +43 -7
  101. package/src/providers/model-rename-fields.ts +2 -0
  102. package/src/providers/openai-sidecar.ts +15 -2
  103. package/src/providers/provider-id-rewrite.ts +3 -0
  104. package/src/providers/quota/account-cache.ts +52 -34
  105. package/src/providers/quota/anthropic-usage-windows.ts +19 -9
  106. package/src/providers/quota/report-cache.ts +53 -5
  107. package/src/providers/quota/vendor-probes-key.ts +73 -0
  108. package/src/providers/quota/vendor-probes-oauth.ts +57 -3
  109. package/src/providers/quota-key-accounts.ts +12 -5
  110. package/src/providers/quota-mistral-budget.ts +18 -0
  111. package/src/providers/quota-types.ts +25 -0
  112. package/src/providers/quota.ts +22 -22
  113. package/src/providers/reasoning-metadata.ts +1051 -12
  114. package/src/quota/reset-observer.ts +4 -2
  115. package/src/quota/reset-seen-store.ts +9 -0
  116. package/src/quota/window-mapping.ts +1 -0
  117. package/src/quota-pool/assemble.ts +4 -1
  118. package/src/responses/hosted-tool-policy.ts +56 -12
  119. package/src/router.ts +2 -0
  120. package/src/server/auth-cors.ts +11 -8
  121. package/src/server/catalog-download.ts +3 -5
  122. package/src/server/chat-native.ts +11 -2
  123. package/src/server/claude-messages.ts +2 -1
  124. package/src/server/images.ts +41 -13
  125. package/src/server/index/link-listener.ts +16 -2
  126. package/src/server/index/link-relay-sessions.ts +43 -2
  127. package/src/server/index/optional-listeners.ts +18 -0
  128. package/src/server/management/config-routes.ts +7 -1
  129. package/src/server/management/context.ts +1 -1
  130. package/src/server/management/link-child-ops-routes.ts +116 -0
  131. package/src/server/management/link-route-state.ts +10 -0
  132. package/src/server/management/link-routes.ts +10 -0
  133. package/src/server/management/oauth-account-routes.ts +33 -4
  134. package/src/server/management/provider-overwrite-carry.ts +28 -3
  135. package/src/server/management/provider-routes.ts +16 -11
  136. package/src/server/management/route-registry.ts +3 -0
  137. package/src/server/messages-native.ts +5 -0
  138. package/src/server/request-log-failure-detail.ts +59 -1
  139. package/src/server/responses/adapter-dispatch.ts +35 -44
  140. package/src/server/responses/combo-stream-preflight.ts +146 -29
  141. package/src/server/responses/compact.ts +16 -5
  142. package/src/server/responses/context-overflow.ts +58 -2
  143. package/src/server/responses/core-combo-failure.ts +29 -4
  144. package/src/server/responses/core-combo-native.ts +3 -1
  145. package/src/server/responses/core-combo.ts +30 -3
  146. package/src/server/responses/core-errors.ts +3 -1
  147. package/src/server/responses/core-opaque-recovery.ts +45 -2
  148. package/src/server/responses/core-options.ts +12 -0
  149. package/src/server/responses/passthrough-dispatch.ts +30 -38
  150. package/src/server/responses/request-transport.ts +43 -14
  151. package/src/server/responses/reset-replay.ts +58 -2
  152. package/src/server/responses/run-turn-execution.ts +56 -30
  153. package/src/types/claude-tool-loading.ts +48 -0
  154. package/src/types/config.ts +5 -35
  155. package/src/types/provider.ts +21 -0
  156. package/src/types.ts +1 -0
  157. package/src/web-search/parse.ts +21 -2
  158. package/gui/dist/assets/App-g3Cm2xhZ.js +0 -59
  159. package/gui/dist/assets/Tray-BMDkAiXy.js +0 -1
  160. package/gui/dist/assets/index-Bziu8gTy.css +0 -2
  161. package/gui/dist/assets/index-OYzhQUNP.js +0 -94
  162. package/gui/dist/classic/assets/index-BR-HhNrp.js +0 -94
  163. package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +0 -1
@@ -1,8 +1,8 @@
1
- import { recordUpstreamValidationDetail } from "../request-log-failure-detail";
1
+ import { recordUpstreamProviderErrorDetail } from "../request-log-failure-detail";
2
2
  import { clientFacingModelText } from "../../lib/error-destination";
3
3
  import { responsesSpendTarget } from "./request-spend-target";
4
4
  import { projectLocalModelRefusalLog } from "../request-log-failure-detail";
5
- import { markProxyError, carryProxyError } from "../../lib/client-error-body";
5
+ import { markProxyError, carryProxyError, isProxyError } from "../../lib/client-error-body";
6
6
  import { codexAdapterBuildRefusal } from "./passthrough-build-error";
7
7
  import { createAutoPauseRefreshErrorMapper, recoverAutoPausedAccount } from "./account-auto-pause-recovery";
8
8
  import { wasAccountAutoPaused, wasPermanentAccountRefusal } from "../../oauth/account-auto-pause";
@@ -96,13 +96,12 @@ import {
96
96
  attemptOpaqueBlobRecovery,
97
97
  consoleGoUploadRejectionBody,
98
98
  CONSOLE_GO_UPLOAD_RETRY_DELAY_MS,
99
- reasoningEffortRejectionText,
99
+ refusedReasoningEffortDowngrade,
100
100
  anthropicFastRefused,
101
101
  } from "./core-opaque-recovery";
102
102
  import { createAnthropicThinkingRecovery } from "./anthropic-thinking-recovery";
103
103
  import { shouldAttemptImageTierRetry } from "../image-retry";
104
104
  import { isTransientConsoleGoUploadRejection } from "../../providers/opencode-zen-rate-limit";
105
- import { planReasoningEffortDowngrade } from "../../providers/reasoning-metadata";
106
105
  import { formatAdapterUpstreamFailure } from "./adapter-failure-message";
107
106
  import { consumeComboFailure } from "./core-combo-failure";
108
107
  import { streamingContextOverflowResponse, jsonContextOverflowResponse, lateAttributionLimitResponse } from "./context-overflow";
@@ -613,9 +612,8 @@ export async function prepareAdapterExchange(
613
612
  const consoleGoUploadRetryGuard: { attempted: boolean } = { attempted: false };
614
613
  let oauth401ReplayAttempted = transportState.oauth401ReplayAttempted;
615
614
  let antigravityAuthRotationAttempted = false;
616
- // At most one reasoning-effort downgrade per request. This sits outside the recovery loop
617
- // below for the same reason the two guards above do: a guard declared inside it is reset by
618
- // every `continue recovery`, which would let one turn walk the whole ladder down.
615
+ // Direct requests get one reasoning-effort downgrade. Combo candidates may walk down the
616
+ // published ladder one refused rung at a time; the request send budget bounds those retries.
619
617
  const reasoningEffortDowngradeGuard: { attempted: boolean } = { attempted: false };
620
618
  // At most one Anthropic fast-mode downgrade per request, for the same reason.
621
619
  const anthropicFastDowngradeGuard: { attempted: boolean } = { attempted: false };
@@ -663,20 +661,19 @@ export async function prepareAdapterExchange(
663
661
  const authRefusal = options.abortSignal?.aborted ? undefined : codexAdapterBuildRefusal(err, admissionState.authCtx, route.codexAccountNamespace, () => { cleanupUpstreamAbort(); upstream.abort(); });
664
662
  if (authRefusal) return { failed: authRefusal };
665
663
  // A rotated credential that cannot be shaped keeps the refusal it was meant to
666
- // replace. The image-tier rebuild is different: the request itself failed to shape,
667
- // and its established 413/400 build-error contract stays authoritative.
668
- if (preserveFailureResponse && recovery !== "image-413" && !options.abortSignal?.aborted) {
664
+ // replace. The image-tier and reasoning-effort rebuilds are different: the request itself
665
+ // failed to shape, and their established build-error contracts stay authoritative.
666
+ if (preserveFailureResponse && recovery !== "image-413" && recovery !== "reasoning-effort-downgrade" && !options.abortSignal?.aborted) {
669
667
  return { failed: preserveFailureResponse };
670
668
  }
671
669
  // A rotated/rebuilt adapter build failure is a request-shaping error, not an
672
- // upstream connect failure: tear the abort link down and map it as 400. A
673
- // translator-budget refusal keeps its established 413 here as well — adapters
674
- // can throw it while sizing generated content (e.g. Ollama late-tool
675
- // attribution), not only parseRequest/buildToolBridgeMaps.
670
+ // upstream connect failure: tear the abort link down and map it as 400.
676
671
  cleanupUpstreamAbort();
677
672
  upstream.abort();
678
673
  if (options.abortSignal?.aborted) return { failed: clientCancelledResponse() };
679
- if (err instanceof OllamaLateAttributionBudgetError) return { failed: lateAttributionLimitResponse() };
674
+ if (err instanceof OllamaLateAttributionBudgetError) {
675
+ return { failed: lateAttributionLimitResponse() };
676
+ }
680
677
  if (isTranslatorBudgetExceededError(err)) {
681
678
  return { failed: formatErrorResponse(413, "request_too_large", "request translation buffer exceeded the safe limit", {
682
679
  code: "translation_buffer_limit",
@@ -847,7 +844,7 @@ export async function prepareAdapterExchange(
847
844
  releaseCodexAuthContextProbeLease(admissionState.authCtx);
848
845
  return { failed: codexRefusal };
849
846
  }
850
- if (preserveFailureResponse && !replacementAdmitted && !options.abortSignal?.aborted)
847
+ if (preserveFailureResponse && (recovery !== "reasoning-effort-downgrade" || err instanceof SendBudgetExhaustedError) && !replacementAdmitted && !options.abortSignal?.aborted)
851
848
  return { failed: preserveFailureResponse };
852
849
  cleanupUpstreamAbort();
853
850
  upstream.abort();
@@ -1826,33 +1823,26 @@ export async function prepareAdapterExchange(
1826
1823
  continue recovery;
1827
1824
  }
1828
1825
  }
1829
- // Reasoning-effort downgrade, mirroring the passthroughRecovery loop above: learn the
1830
- // refused rung, then replay once at the next published one.
1831
- if (!reasoningEffortDowngradeGuard.attempted) {
1832
- const rejectionText = await reasoningEffortRejectionText(
1833
- upstreamResponse,
1834
- reasoningEffortDowngradeGuard.attempted,
1835
- upstream.signal,
1836
- );
1837
- const downgrade = rejectionText === undefined
1838
- ? undefined
1839
- : planReasoningEffortDowngrade({
1840
- provider: route.provider,
1841
- modelId: parsed.modelId,
1842
- requested: parsed.options.reasoning,
1843
- rejectionText,
1844
- });
1845
- if (downgrade) {
1846
- reasoningEffortDowngradeGuard.attempted = true;
1847
- parsed.options.reasoning = downgrade.effort;
1848
- // The same-target cache keys on parsed identity, so a mutated effort needs a token bump.
1849
- invalidateSameTargetRequest();
1850
- try { void upstreamResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ }
1851
- const result = await rebuildAndRefetch("reasoning-effort-downgrade");
1852
- if ("failed" in result) return result.failed;
1853
- upstreamResponse = result;
1854
- continue recovery;
1826
+ // Learn a refused rung and retry at the next published one. Direct requests are limited
1827
+ // to one repair; combo candidates may continue down the finite ladder within the send budget.
1828
+ const downgrade = await refusedReasoningEffortDowngrade(upstreamResponse, upstream.signal, reasoningEffortDowngradeGuard,
1829
+ options.comboAttempt, { provider: route.provider, modelId: parsed.modelId, requested: parsed.options.reasoning });
1830
+ if (downgrade) {
1831
+ reasoningEffortDowngradeGuard.attempted = true;
1832
+ parsed.options.reasoning = downgrade.effort;
1833
+ // The same-target cache keys on parsed identity, so a mutated effort needs a token bump.
1834
+ invalidateSameTargetRequest();
1835
+ // A combo keeps the refusal, so an unfunded rung still reaches combo failover as the original 400.
1836
+ const refusal = options.comboAttempt ? await retainFailureResponse() : undefined;
1837
+ if (!refusal) try { void upstreamResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ }
1838
+ const result = await rebuildAndRefetch("reasoning-effort-downgrade", undefined, refusal);
1839
+ if ("failed" in result) {
1840
+ if (result.failed !== refusal) return result.failed;
1841
+ break recovery;
1855
1842
  }
1843
+ if (refusal) try { void refusal.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ }
1844
+ upstreamResponse = result;
1845
+ continue recovery;
1856
1846
  }
1857
1847
  break;
1858
1848
  }
@@ -1864,7 +1854,7 @@ export async function prepareAdapterExchange(
1864
1854
  // `response.body` itself with the abort signal threaded through, and the combo
1865
1855
  // contract is that this body's getter is touched exactly once. A guard here would be
1866
1856
  // a second `.body` access for no gain, since the bounded reader owns settlement.
1867
- const failure = await consumeComboFailure(upstreamResponse, options.abortSignal, Date.now(), logCtx)
1857
+ const failure = await consumeComboFailure(upstreamResponse, options.abortSignal, Date.now(), logCtx, !isProxyError(upstreamResponse))
1868
1858
  .finally(cleanupUpstreamAbort);
1869
1859
  options.onConsumedComboFailure?.(failure);
1870
1860
  return failure.response;
@@ -1879,7 +1869,8 @@ export async function prepareAdapterExchange(
1879
1869
  } finally {
1880
1870
  cleanupUpstreamAbort();
1881
1871
  }
1882
- recordUpstreamValidationDetail(logCtx, upstreamResponse.status, errorText);
1872
+ // The provider's own body (not a proxy-normalized one) may name its closed error class (#8446).
1873
+ if (!isProxyError(upstreamResponse)) recordUpstreamProviderErrorDetail(logCtx, upstreamResponse.status, errorText, upstreamResponse);
1883
1874
  if (upstreamResponse.status === 413) {
1884
1875
  if (options.clientModelLabel) projectLocalModelRefusalLog(logCtx, options.clientModelLabel);
1885
1876
  return clientRequestedStream
@@ -1,4 +1,14 @@
1
- import { codexAccountModelRefusal, codexAccountModelRefusalPayload, hasConflictingCodexModelRefusalEnvelopes, type CodexAccountModelRefusal } from "../../combos/failover";
1
+ import {
2
+ codexAccountModelRefusal,
3
+ codexAccountModelRefusalPayload,
4
+ envelopeErrorRecord,
5
+ envelopeRecordCode,
6
+ hasConflictingCodexModelRefusalEnvelopes,
7
+ isMalformedResponseFormatRecord,
8
+ isOpenRouterOpaque400EnvelopeRoot,
9
+ isOpenRouterOpaque400Record,
10
+ type CodexAccountModelRefusal,
11
+ } from "../../combos/failover";
2
12
  import type { ResponsesTerminalStatus } from "../../bridge";
3
13
  import { comboFailureDecision } from "../../combos";
4
14
  import { httpStatusFromTerminalError } from "../../lib/errors";
@@ -9,6 +19,7 @@ import { carryResponseToolOwnership } from "./response-tool-ownership";
9
19
  import { createSseInspector } from "../relay";
10
20
  import { MAX_CLIENT_SSE_FRAME_BYTES } from "../sse-frame-buffer";
11
21
  import { REQUIRED_TOOL_CONTRACT_CODE } from "../../lib/errors";
22
+ import { isPausedTurn } from "../../lib/client-error-body";
12
23
  import { requiredToolReasoningPrelude } from "./combo-required-tool-stream";
13
24
 
14
25
  const COMBO_STREAM_PREFLIGHT_MAX_BYTES = MAX_CLIENT_SSE_FRAME_BYTES;
@@ -76,10 +87,26 @@ function bareErrorStatus(payload: unknown): number | undefined {
76
87
  ? Number(value)
77
88
  : undefined)
78
89
  .find(value => value !== undefined && value >= 400 && value <= 599);
79
- const code = typeof error.code === "string"
80
- ? error.code
81
- : typeof event.code === "string" ? event.code : null;
90
+ const rawCode = error.code ?? event.code;
91
+ const code = typeof rawCode === "string"
92
+ ? rawCode
93
+ : typeof rawCode === "number" && Number.isFinite(rawCode)
94
+ ? String(rawCode)
95
+ : null;
82
96
  if (explicitStatus === undefined && code === "invalid_request_error") return 400;
97
+ // Status is the record's own evidence; whether that record speaks for the envelope is the
98
+ // decision's question, so a root hard stop still reports 400 instead of inventing a 5xx.
99
+ if (explicitStatus === undefined && isOpenRouterOpaque400Record(envelopeErrorRecord(event))) {
100
+ return 400;
101
+ }
102
+ // OpenRouter-style envelopes carry the HTTP status as a bare numeric `code` (e.g. `code: 400`)
103
+ // with no separate status field. `httpStatusFromTerminalError` only understands symbolic codes,
104
+ // so without this the opaque 400 stringifies to "400", reads as unknown, and falls back to 502 —
105
+ // which cools the target on the generic 5xx path instead of taking the intended no-cool hop.
106
+ if (explicitStatus === undefined
107
+ && typeof rawCode === "number" && Number.isInteger(rawCode) && rawCode >= 400 && rawCode <= 599) {
108
+ return rawCode;
109
+ }
83
110
  return explicitStatus ?? httpStatusFromTerminalError({
84
111
  type: typeof error.type === "string" && error.type !== "error" ? error.type : undefined,
85
112
  code,
@@ -115,38 +142,98 @@ function bareErrorIsRetryable(payload: unknown): boolean {
115
142
  return false;
116
143
  }
117
144
  const event = payload as Record<string, unknown>;
118
- const nested = event.error;
119
- const error = nested && typeof nested === "object" && !Array.isArray(nested)
120
- ? nested as Record<string, unknown>
121
- : event;
122
- const code = typeof error.code === "string"
123
- ? error.code
124
- : typeof event.code === "string" ? event.code : null;
145
+ // The record selection, the opaque verdict and the code conflict rule are shared with the HTTP
146
+ // consumer; only the carrier (one parsed frame here, one body there) differs.
147
+ const record = envelopeErrorRecord(event);
148
+ const error = record ?? event;
149
+ const rootCode = envelopeRecordCode(event);
150
+ const recordCode = envelopeRecordCode(record);
125
151
  const message = typeof error.message === "string"
126
152
  ? error.message
127
153
  : typeof event.message === "string" ? event.message : "";
154
+ const rawRecord = {
155
+ ...(error as Record<string, unknown>),
156
+ ...(typeof event.detail === "string" ? { detail: event.detail } : {}),
157
+ };
158
+ const malformedResponseFormat = status === 400 ? isMalformedResponseFormatRecord(rawRecord, message) : undefined;
159
+ const openRouterOpaque400 = status === 400 ? isOpenRouterOpaque400EnvelopeRoot(event) : undefined;
160
+ // A conflicting root and record code hop only when each would hop on its own, so a root hard
161
+ // stop is never hidden behind a retryable record code (and a retryable pair keeps dev's hop).
128
162
  return comboFailureDecision(status, message, {
129
- code, codexModelRefusal: terminalModelRefusal(status, event),
163
+ code: recordCode ?? rootCode, rootCode,
164
+ codexModelRefusal: terminalModelRefusal(status, event),
165
+ malformedResponseFormat, openRouterOpaque400,
130
166
  }) === "hop";
131
167
  }
132
168
 
133
- function retryableZeroOutputTerminal(payload: unknown): boolean {
169
+ /**
170
+ * Only text and reasoning items, which the required-tool guard holds back until it decides. Both the
171
+ * snapshot's and the event's own `output` are read; an absent or empty one contributes nothing.
172
+ */
173
+ function heldOnlyOutput(...outputs: unknown[]): boolean {
174
+ const items = outputs.flatMap(output => Array.isArray(output) ? output : []);
175
+ if (outputs.some(output => output !== undefined && !Array.isArray(output))) return false;
176
+ return items.length > 0 && items.every(item => item !== null && typeof item === "object"
177
+ && !Array.isArray(item) && ["message", "reasoning"].includes((item as { type?: unknown }).type as string));
178
+ }
179
+
180
+ function retryableZeroOutputTerminal(payload: unknown, context?: object): boolean {
134
181
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false;
135
182
  const event = payload as {
136
183
  type?: unknown;
137
- response?: { incomplete_details?: { reason?: unknown }; output?: unknown };
184
+ status?: unknown;
185
+ end_turn?: unknown;
186
+ incomplete_details?: { reason?: unknown; retryable?: unknown };
187
+ output?: unknown;
188
+ error?: { code?: unknown; retryable?: unknown };
189
+ response?: {
190
+ status?: unknown;
191
+ end_turn?: unknown;
192
+ incomplete_details?: { reason?: unknown; retryable?: unknown };
193
+ output?: unknown;
194
+ error?: { code?: unknown; retryable?: unknown };
195
+ };
138
196
  };
139
197
  if (bareErrorIsRetryable(event)) return true;
140
- if (event.type === "response.failed") {
141
- const error = (event.response as { error?: { code?: unknown; retryable?: unknown } } | undefined)?.error;
198
+ const target = (event.response && typeof event.response === "object" && !Array.isArray(event.response))
199
+ ? event.response as Record<string, unknown>
200
+ : event as Record<string, unknown>;
201
+ const emptyOutput = (!Array.isArray(event.output) || event.output.length === 0)
202
+ && (!Array.isArray(target.output) || target.output.length === 0);
203
+
204
+ if (event.type === "response.failed" || event.status === "failed") {
205
+ const error = (event.response as { error?: { code?: unknown; retryable?: unknown } } | undefined)?.error
206
+ ?? event.error;
142
207
  const code = error?.code;
143
- if (code === REQUIRED_TOOL_CONTRACT_CODE && error?.retryable === false) return false;
208
+ // The required-tool guard synthesizes this terminal over output it held back from the client,
209
+ // so held text and reasoning are not evidence of anything sent; it keeps the retryability it
210
+ // carries. Any other output item (a tool call, an action) still commits it.
211
+ if (code === REQUIRED_TOOL_CONTRACT_CODE) {
212
+ return error?.retryable !== false && (emptyOutput || heldOnlyOutput(target.output, event.output));
213
+ }
214
+ if (!emptyOutput) return false;
144
215
  return !(typeof code === "string" && NON_REPLAYABLE_FAILED_CODES.has(code));
145
216
  }
146
- if (event.type !== "response.incomplete") return false;
147
- const reason = event.response?.incomplete_details?.reason;
148
- // A terminal-only upstream can carry output without preceding delta/item events.
149
- if (reason === undefined) return !Array.isArray(event.response?.output) || event.response.output.length === 0;
217
+ const isIncomplete = event.type === "response.incomplete" || event.status === "incomplete";
218
+ if (!isIncomplete) return false;
219
+ if (!emptyOutput) return false;
220
+ const details = (target.incomplete_details && typeof target.incomplete_details === "object" && !Array.isArray(target.incomplete_details))
221
+ ? target.incomplete_details as { reason?: unknown; retryable?: unknown }
222
+ : undefined;
223
+ const reason = details?.reason;
224
+ if (reason === undefined) return true;
225
+ if (reason === "max_output_tokens") {
226
+ // Same evidence the run-turn classifier requires before it treats an output limit as a
227
+ // replayable zero-output terminal: an explicitly unfinished turn or an explicitly
228
+ // non-retryable limit is an answer, not a target failure. A normalized Anthropic
229
+ // `pause_turn` also reads as max_output_tokens on the wire, so the request-scoped marker
230
+ // keeps a paused turn the client must continue from hopping to another provider.
231
+ if (isPausedTurn(context)) return false;
232
+ const endTurn = target.end_turn ?? event.end_turn;
233
+ if (endTurn === false) return false;
234
+ if (details?.retryable === false) return false;
235
+ return true;
236
+ }
150
237
  return typeof reason === "string" && RETRYABLE_ZERO_OUTPUT_INCOMPLETE_REASONS.has(reason);
151
238
  }
152
239
 
@@ -170,6 +257,10 @@ export function comboStreamPayloadCommitsOutput(payload: unknown): boolean {
170
257
  if (Array.isArray(output) && output.length > 0) return true;
171
258
  }
172
259
  }
260
+ if (type === "response.output_text.delta") {
261
+ const delta = (payload as { delta?: unknown }).delta;
262
+ if (delta === undefined || (typeof delta === "string" && delta.length === 0)) return false;
263
+ }
173
264
  return !PRE_OUTPUT_CONTROL_EVENTS.has(type) && !CODEX_METADATA_CONTROL_EVENTS.has(type)
174
265
  && !TERMINAL_EVENTS.has(type);
175
266
  }
@@ -244,13 +335,19 @@ function failedTerminalResponse(
244
335
  const nested = terminalPayload.response;
245
336
  const terminalResponse = nested && typeof nested === "object" && !Array.isArray(nested)
246
337
  ? nested as Record<string, unknown>
247
- : {};
248
- const nestedError = terminalResponse.error;
338
+ : terminalPayload;
339
+ const nestedError = (nested as Record<string, unknown> | undefined)?.error;
249
340
  const topLevelError = terminalPayload.error;
250
341
  const error = nestedError && typeof nestedError === "object" && !Array.isArray(nestedError)
251
342
  ? nestedError as Record<string, unknown>
252
343
  : topLevelError && typeof topLevelError === "object" && !Array.isArray(topLevelError)
253
344
  ? topLevelError as Record<string, unknown>
345
+ : isOpenRouterOpaque400Record(terminalPayload)
346
+ ? {
347
+ message: terminalPayload.message,
348
+ code: terminalPayload.code,
349
+ metadata: terminalPayload.metadata,
350
+ }
254
351
  : {
255
352
  // A caller-validated flat error can carry its identity beside type:error.
256
353
  // Retain it when that caller established a 400, rather than discarding the
@@ -258,10 +355,20 @@ function failedTerminalResponse(
258
355
  type: terminalPayload.type === "error" && logCtx.terminalHttpStatus === 400
259
356
  ? "invalid_request_error" : "upstream_error",
260
357
  code: terminalPayload.type === "error" && logCtx.terminalHttpStatus === 400
261
- ? (typeof terminalPayload.code === "string" ? terminalPayload.code : null) : "upstream_server_error",
358
+ ? (typeof terminalPayload.code === "string"
359
+ ? terminalPayload.code
360
+ : typeof terminalPayload.code === "number" && Number.isFinite(terminalPayload.code)
361
+ ? String(terminalPayload.code)
362
+ : null)
363
+ : ((terminalPayload.type === "response.incomplete" || terminalPayload.status === "incomplete")
364
+ && (terminalResponse.incomplete_details as { reason?: unknown } | undefined)?.reason === "max_output_tokens"
365
+ ? "zero_output_token_limit" : "upstream_server_error"),
262
366
  message: typeof terminalPayload.message === "string"
263
367
  ? terminalPayload.message
264
- : logCtx.upstreamError ?? "Provider stream failed before producing output",
368
+ : ((terminalPayload.type === "response.incomplete" || terminalPayload.status === "incomplete")
369
+ && (terminalResponse.incomplete_details as { reason?: unknown } | undefined)?.reason === "max_output_tokens"
370
+ ? "Provider reached its output token limit before producing output"
371
+ : logCtx.upstreamError ?? "Provider stream failed before producing output"),
265
372
  };
266
373
  const headers = new Headers(response.headers);
267
374
  headers.set("content-type", "application/json");
@@ -270,6 +377,7 @@ function failedTerminalResponse(
270
377
  const usage = terminalResponse.usage;
271
378
  return new Response(JSON.stringify({
272
379
  error,
380
+ ...(typeof terminalPayload.detail === "string" ? { detail: terminalPayload.detail } : {}),
273
381
  // The combo classifier needs only the error and optional usage. Do not carry
274
382
  // response ids, provider metadata, or future terminal fields into the client
275
383
  // error envelope merely because they shared the terminal snapshot.
@@ -305,13 +413,22 @@ export type ComboStreamPreflightResult =
305
413
  export async function preflightComboStreamResponse(
306
414
  response: Response,
307
415
  logCtx: RequestLogContext,
308
- retryableTerminal: (payload: unknown) => boolean = retryableZeroOutputTerminal,
309
- options?: { allowMissingContentType?: boolean; replayReadErrors?: boolean; requiredToolPrelude?: boolean; signal?: AbortSignal },
416
+ retryableTerminal?: (payload: unknown) => boolean,
417
+ options?: {
418
+ allowMissingContentType?: boolean;
419
+ replayReadErrors?: boolean;
420
+ requiredToolPrelude?: boolean;
421
+ signal?: AbortSignal;
422
+ },
310
423
  ): Promise<ComboStreamPreflightResult> {
424
+ const retryableTerminalFor = retryableTerminal ?? ((payload: unknown) => retryableZeroOutputTerminal(payload, logCtx));
311
425
  const contentType = response.headers.get("content-type");
312
426
  const isEventStream = hasResponseMediaType(response.headers, "text/event-stream")
313
427
  || (!contentType && options?.allowMissingContentType === true);
314
- if (!response.ok || !response.body || !isEventStream) {
428
+ if (!response.ok || !response.body) {
429
+ return { kind: "accepted", response };
430
+ }
431
+ if (!isEventStream) {
315
432
  return { kind: "accepted", response };
316
433
  }
317
434
 
@@ -336,7 +453,7 @@ export async function preflightComboStreamResponse(
336
453
  if (terminalStatus !== undefined || outputCommitted || retryableTerminalPayload) return;
337
454
  if (payload !== null && typeof payload === "object" && !Array.isArray(payload)
338
455
  && (payload as { type?: unknown }).type === "response.created") responseCreated = true;
339
- const retryable = retryableTerminal(payload);
456
+ const retryable = retryableTerminalFor(payload);
340
457
  const matchedBareError = retryable && payload !== null && typeof payload === "object"
341
458
  && !Array.isArray(payload) && (payload as { type?: unknown }).type === "error";
342
459
  // A zero-output bare error is terminal evidence. Explicit client errors stay
@@ -181,6 +181,7 @@ import { resolveAdapter, resolveWireProtocolOverride } from "../adapter-resolve"
181
181
  import { hasKeyPoolFailover, rotateProviderTransportOn429, selectProactiveApiKeyTransport, transientRetryPolicyFor } from "../../providers/key-failover";
182
182
  import { transientSendCapFor } from "./request-send-budget";
183
183
  import { distributedKeyPhysicalFetch, recordDistributedResponseFailure } from "../../providers/api-key-response-ownership";
184
+ import { isProviderApiKeyPaused, ProviderApiKeyPausedError } from "../../providers/api-key-pause";
184
185
  import { providerApiKeySelectionIsCurrent, resolveCurrentProviderApiKeyTransport } from "../../providers/api-key-selection";
185
186
  import { stampApiKeyAccountLabel } from "../../providers/label";
186
187
  import { shouldAttemptImageTierRetry } from "../image-retry";
@@ -957,7 +958,7 @@ export async function handleResponsesCompact(
957
958
  const base = isCanonicalOpenAiForwardProvider(compactProvider)
958
959
  ? CODEX_FORWARD_BASE_URL
959
960
  : (compactProvider.baseUrl ?? "").replace(/\/+$/, "");
960
- if (compactProvider.authMode !== "forward" && compactProvider.apiKey) {
961
+ if (compactProvider.authMode !== "forward" && (compactProvider.apiKey || compactProvider.apiKeyPool?.length)) {
961
962
  // Native compact never enters handleResponses, so it needs its own pre-dispatch key
962
963
  // pick. Kept inside this branch on purpose: the overlay above owns the forward and
963
964
  // codexAccountMode cases, and the picker returns null for them anyway.
@@ -968,11 +969,19 @@ export async function handleResponsesCompact(
968
969
  catch (error) {
969
970
  const refusal = requestPacingOverloadResponse(error);
970
971
  if (refusal) return refusal;
972
+ if (error instanceof ProviderApiKeyPausedError) {
973
+ return formatErrorResponse(403, "permission_error", error.message);
974
+ }
971
975
  throw error;
972
976
  }
973
977
  if (warmKeyProvider?.apiKey) compactProvider = warmKeyProvider;
974
- headers.set("authorization", `Bearer ${resolveProviderApiKey(compactProvider.apiKey)}`);
975
- stampApiKeyAccountLabel(logCtx, route.providerName, compactProvider);
978
+ if (compactProvider.apiKey) {
979
+ headers.set("authorization", `Bearer ${resolveProviderApiKey(compactProvider.apiKey)}`);
980
+ stampApiKeyAccountLabel(logCtx, route.providerName, compactProvider);
981
+ }
982
+ }
983
+ if (compactProvider.authMode !== "forward" && isProviderApiKeyPaused(compactProvider)) {
984
+ return formatErrorResponse(403, "permission_error", new ProviderApiKeyPausedError().message);
976
985
  }
977
986
  const { reasoning: _reasoning, ...compactBodyRaw } = raw as typeof raw & { reasoning?: unknown };
978
987
  const requireCompactPlaintextReasoning = !isOpenAiOperatedResponsesDestination(compactProvider)
@@ -1252,6 +1261,7 @@ export async function handleResponsesCompact(
1252
1261
  if (fresh) current = selectProactiveApiKeyTransport(config, route.providerName, fresh) ?? fresh;
1253
1262
  }
1254
1263
  if (!current?.apiKey || !supportsNativeResponsesCompactEndpoint(route.providerName, current)) {
1264
+ if (!current?.apiKey && isProviderApiKeyPaused(config.providers[route.providerName])) throw new ProviderApiKeyPausedError();
1255
1265
  throw new Error("Provider key selection is no longer available for compact");
1256
1266
  }
1257
1267
  const rebuilt = new Headers(sendHeaders);
@@ -1315,9 +1325,10 @@ export async function handleResponsesCompact(
1315
1325
  let outcomeCtx = authCtx;
1316
1326
  const localDispatchRefusal = (error: unknown): Response | undefined => {
1317
1327
  const cause = unwrapUpstreamRetryEvidenceError(error);
1318
- const response = cause instanceof InvalidRetainedCompactionEnvelopeError
1328
+ const response = (cause instanceof InvalidRetainedCompactionEnvelopeError
1319
1329
  ? formatErrorResponse(400, "invalid_request_error", cause.message)
1320
- : requestPacingOverloadResponse(cause) ?? spendLedgerStorageErrorResponse(error, logCtx) ?? (cause instanceof SendBudgetExhaustedError
1330
+ : cause instanceof ProviderApiKeyPausedError ? formatErrorResponse(403, "permission_error", cause.message) : undefined)
1331
+ ?? requestPacingOverloadResponse(cause) ?? spendLedgerStorageErrorResponse(error, logCtx) ?? (cause instanceof SendBudgetExhaustedError
1321
1332
  ? unboundPoolSpendRefusalResponse(logCtx) ?? formatErrorResponse(429, "request_send_budget_exhausted", cause.message)
1322
1333
  : mapCodexAuthContextErrorToResponse(cause, {
1323
1334
  now: Date.now(), accountSelector: route.codexAccountNamespace,
@@ -1,10 +1,10 @@
1
- import { bridgeToResponsesSSE, formatErrorResponse } from "../../bridge";
1
+ import { bridgeToResponsesSSE, buildResponseJSON, formatErrorResponse } from "../../bridge";
2
2
  import { OLLAMA_LATE_ATTRIBUTION_LIMIT_MESSAGE } from "../../adapters/ollama-native";
3
3
  import { isThroughputLimitText } from "../../claude/outbound";
4
4
  import { isDefiniteContextOverflow } from "../../combos/failover";
5
5
  import { classifyError, MODEL_NOT_IN_PLAN_STREAM_CODE } from "../../lib/errors";
6
6
  import type { TranslatorBudget } from "../../lib/translator-budget";
7
- import type { AdapterEvent } from "../../types";
7
+ import type { AdapterEvent, OcxUsage } from "../../types";
8
8
 
9
9
  /**
10
10
  * The Ollama late-attribution refusal as a client response: the existing translator-budget
@@ -221,3 +221,59 @@ export function streamingContextOverflowResponse(
221
221
  },
222
222
  });
223
223
  }
224
+
225
+ /**
226
+ * Return an incomplete JSON response with the target's usage and reason when combo candidates
227
+ * exhaust on zero-output token limits.
228
+ */
229
+ export function jsonIncompleteResponse(
230
+ modelId: string,
231
+ usage?: OcxUsage,
232
+ reason = "max_output_tokens",
233
+ ): Response {
234
+ const json = buildResponseJSON([
235
+ {
236
+ type: "incomplete",
237
+ reason,
238
+ ...(usage ? { usage } : {}),
239
+ },
240
+ ], modelId);
241
+ return Response.json(json, { status: 200, headers: { "Cache-Control": "no-store" } });
242
+ }
243
+
244
+ /**
245
+ * Return an incomplete SSE stream with the target's usage and reason when combo candidates
246
+ * exhaust on zero-output token limits.
247
+ */
248
+ export function streamingIncompleteResponse(
249
+ modelId: string,
250
+ usage?: OcxUsage,
251
+ reason = "max_output_tokens",
252
+ translatorBudget?: TranslatorBudget,
253
+ ): Response {
254
+ async function* incompleteEvents(): AsyncGenerator<AdapterEvent> {
255
+ yield {
256
+ type: "incomplete",
257
+ reason,
258
+ ...(usage ? { usage } : {}),
259
+ };
260
+ }
261
+ return new Response(bridgeToResponsesSSE(
262
+ incompleteEvents(),
263
+ modelId,
264
+ undefined,
265
+ undefined,
266
+ undefined,
267
+ undefined,
268
+ 2_000,
269
+ translatorBudget ? { translatorBudget } : undefined,
270
+ ), {
271
+ headers: {
272
+ "Content-Type": "text/event-stream",
273
+ "Cache-Control": "no-cache",
274
+ Connection: "keep-alive",
275
+ "X-Accel-Buffering": "no",
276
+ },
277
+ });
278
+ }
279
+
@@ -1,9 +1,16 @@
1
- import { recordUpstreamValidationDetail, type FailureDetail } from "../request-log-failure-detail";
1
+ import { recordUpstreamProviderErrorDetail, recordUpstreamValidationDetail, type FailureDetail } from "../request-log-failure-detail";
2
2
  import { carryProxyErrorPresentation } from "../../lib/client-error-body";
3
3
  import { carryPolicyCandidateRefusal } from "./policy-request-scope";
4
4
  import { comboFailureEvidence, carryProxyError } from "../../lib/client-error-body";
5
5
  import { carryWorkflowRefusal } from "../workflow-refusal";
6
- import { codexAccountModelRefusal, codexAccountModelRefusalHardStopCode, type CodexAccountModelRefusal } from "../../combos/failover";
6
+ import {
7
+ codexAccountModelRefusal,
8
+ codexAccountModelRefusalHardStopCode,
9
+ isMalformedResponseFormatRequest,
10
+ isOpenRouterOpaque400Envelope,
11
+ upstreamEnvelopeRootCode,
12
+ type CodexAccountModelRefusal,
13
+ } from "../../combos/failover";
7
14
  import { parseRetryAfterMs } from "../../combos";
8
15
  import type { ConsumedComboFailure, HandleResponsesOptions } from "./core-options";
9
16
  import type { OcxUsage } from "../../types";
@@ -47,6 +54,8 @@ export async function consumeComboFailure(
47
54
  signal?: AbortSignal,
48
55
  now = Date.now(),
49
56
  logCtx?: { failureDetail?: FailureDetail; causeHint?: RequestFailureCause },
57
+ /** True only when `response` is the provider's own HTTP answer, so its closed error class is evidence. */
58
+ rawUpstream = false,
50
59
  ): Promise<ConsumedComboFailure> {
51
60
  // Read before the body: the marker lives on this Response object, and the failure below is
52
61
  // rebuilt as a new one that would otherwise lose it.
@@ -55,8 +64,11 @@ export async function consumeComboFailure(
55
64
  const fallback = `Provider error ${response.status}`;
56
65
  let classificationText = fallback;
57
66
  let codexModelRefusal: CodexAccountModelRefusal | undefined;
67
+ let malformedResponseFormat: boolean | undefined;
68
+ let openRouterOpaque400: boolean | undefined;
58
69
  let usage: OcxUsage | undefined;
59
70
  let upstreamCode: string | undefined;
71
+ let upstreamRootCode: string | undefined;
60
72
  let upstreamMessage: string | undefined;
61
73
  let upstreamType: string | undefined;
62
74
  // Whether the body itself confirms a quota/rate-limit refusal, computed on the SAME read as
@@ -85,11 +97,19 @@ export async function consumeComboFailure(
85
97
  && isRateLimitOrQuotaFailureMessage(quotaMessage);
86
98
  }
87
99
  if (body.displaySafe && !body.truncated) {
88
- if (logCtx) recordUpstreamValidationDetail(logCtx, response.status, body.text);
100
+ if (logCtx && rawUpstream) recordUpstreamProviderErrorDetail(logCtx, response.status, body.text, response);
101
+ else if (logCtx) recordUpstreamValidationDetail(logCtx, response.status, body.text);
89
102
  // A combo child's row is attributed from the same evidence the parent uses: Meta's Muse
90
103
  // Code refusal is a plan restriction, not a rejected credential (#8352).
91
104
  if (logCtx) stampMetaMusePlanRefusal(logCtx, response.status, body.text);
92
- if (response.status === 400) codexModelRefusal = codexAccountModelRefusal(response.status, body.text);
105
+ if (response.status === 400) {
106
+ codexModelRefusal = codexAccountModelRefusal(response.status, body.text);
107
+ malformedResponseFormat = isMalformedResponseFormatRequest(response.status, body.text);
108
+ openRouterOpaque400 = isOpenRouterOpaque400Envelope(body.text);
109
+ }
110
+ // Status-independent: the nested record is what normalization selects, so a root verdict
111
+ // beside it has to be captured here or the conflict rule never sees it.
112
+ upstreamRootCode = upstreamEnvelopeRootCode(body.text);
93
113
  const normalized = normalizeUpstreamErrorText(body.text, fallback);
94
114
  if (utf8Trusted || isCyberPolicyCode(normalized.code) || isCyberPolicyMessage(normalized.safeText)) {
95
115
  classificationText = normalized.safeText;
@@ -167,7 +187,12 @@ export async function consumeComboFailure(
167
187
  ...(verifiedPlanRefusal ? { verifiedPlanRefusal: true } : {}),
168
188
  classificationText,
169
189
  ...(codexModelRefusal !== undefined ? { codexModelRefusal } : {}),
190
+ ...(malformedResponseFormat !== undefined ? { malformedResponseFormat } : {}),
191
+ ...(openRouterOpaque400 !== undefined ? { openRouterOpaque400 } : {}),
170
192
  ...(normalizedUpstreamCode !== undefined ? { upstreamCode: normalizedUpstreamCode } : {}),
193
+ // A rewritten identity (policy, replay refusal) is the whole verdict; the root's own code
194
+ // would only re-open a decision that rewrite already settled.
195
+ ...(!cyberFailure && !replayRefusal && upstreamRootCode !== undefined ? { upstreamRootCode } : {}),
171
196
  ...(upstreamMessage !== undefined ? { upstreamMessage } : {}),
172
197
  ...(upstreamType !== undefined ? { upstreamType } : {}),
173
198
  ...(!cyberFailure && cooldownRetryAfter !== undefined ? { retryAfter: cooldownRetryAfter } : {}),
@@ -197,8 +197,10 @@ export function createComboProtocolLanes(input: {
197
197
  if (inbound === "messages") {
198
198
  const combo = getCombo(config, comboId);
199
199
  // ponytail: exact replay supports no combo effort rewrite; the existing bridge owns those policies.
200
+ const domain = credentialDomainFor(route.provider);
200
201
  if (!combo || combo.strategy !== "failover" || comboDefaultEffort(config, comboId)
201
- || combo.reasoningEffortMode !== "strict" || !credentialDomainFor(route.provider)?.firstPartyAnthropic
202
+ || combo.reasoningEffortMode !== "strict" || !domain
203
+ || (route.provider.authMode === "oauth" && !domain.firstPartyAnthropic)
202
204
  || supportedLadderFor({ provider: route.provider, modelId: route.modelId })?.length === 0) return false;
203
205
  }
204
206
  // The concrete selector, as the bridge child's body carries it; the wire model comes from