@bitkyc08/opencodex 2.100.0 → 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 (178) 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-DU-0Vdkr.js +1 -0
  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-CcxZBnxv.js → segment-thumb-features-e9A_FogJ.js} +1 -1
  7. package/gui/dist/classic/assets/{App-aYgIQMxI.js → App-BrIlUiLc.js} +18 -18
  8. package/gui/dist/classic/assets/{Tray-D8jfUXpQ.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/anthropic-image-normalize.ts +1 -1
  15. package/src/adapters/client-fingerprint.ts +6 -4
  16. package/src/adapters/cursor/native-exec.ts +3 -2
  17. package/src/adapters/cursor/tool-guidance.ts +3 -3
  18. package/src/adapters/cursor/tool-wording.ts +10 -1
  19. package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
  20. package/src/adapters/google-antigravity-wire.ts +13 -6
  21. package/src/adapters/google-truncation.ts +4 -2
  22. package/src/adapters/google.ts +8 -2
  23. package/src/adapters/openai-chat/mistral-image-limit.ts +28 -15
  24. package/src/adapters/openai-chat/tool-schema.ts +9 -0
  25. package/src/adapters/openai-chat-images.ts +100 -0
  26. package/src/adapters/openai-chat.ts +6 -9
  27. package/src/adapters/openai-responses/tool-schema.ts +18 -4
  28. package/src/adapters/run-turn-queue.ts +139 -5
  29. package/src/adapters/upstream-http-error.ts +4 -2
  30. package/src/bridge/sse.ts +8 -1
  31. package/src/claude/chat-tool-dispatch.ts +233 -0
  32. package/src/claude/inbound-tool-loading.ts +42 -17
  33. package/src/cli/account-api.ts +6 -0
  34. package/src/cli/account-extended.ts +60 -6
  35. package/src/cli/account-key-quota.ts +22 -2
  36. package/src/cli/account.ts +1 -1
  37. package/src/cli/capabilities-access-remote.ts +10 -0
  38. package/src/cli/capabilities-agents-routing.ts +2 -2
  39. package/src/cli/capabilities-base.ts +2 -2
  40. package/src/cli/claude.ts +19 -14
  41. package/src/cli/config-command.ts +24 -1
  42. package/src/cli/connect.ts +36 -3
  43. package/src/cli/gui-pair-client.ts +23 -2
  44. package/src/cli/help.ts +1 -1
  45. package/src/cli/hub.ts +18 -1
  46. package/src/cli/link-child-ops.ts +136 -0
  47. package/src/cli/link-status-child.ts +94 -0
  48. package/src/cli/link.ts +22 -9
  49. package/src/cli/registry.ts +3 -2
  50. package/src/cli/sync-command.ts +3 -1
  51. package/src/cli/sync-fanout.ts +8 -81
  52. package/src/client/link-readiness.ts +16 -6
  53. package/src/client/link-tunnel-status.ts +76 -0
  54. package/src/clients/config-export.ts +14 -1
  55. package/src/codex/account-resume-health.ts +41 -0
  56. package/src/codex/auth-api/login-flow.ts +6 -0
  57. package/src/codex/auth-api/routes.ts +35 -2
  58. package/src/codex/catalog/gather-capture.ts +2 -0
  59. package/src/codex/catalog/provider-models.ts +13 -8
  60. package/src/codex/convergence-types.ts +2 -0
  61. package/src/codex/quota.ts +111 -6
  62. package/src/combos/cooldown-store.ts +208 -0
  63. package/src/combos/failover.ts +432 -35
  64. package/src/config/salvage.ts +1 -0
  65. package/src/config/schema/config-schema.ts +6 -3
  66. package/src/config/schema/leaf-validators.ts +34 -12
  67. package/src/generated/compatibility-version.json +227 -135
  68. package/src/lib/catalog-etag.ts +10 -0
  69. package/src/lib/client-error-body.ts +15 -0
  70. package/src/lib/config-ownership.ts +9 -2
  71. package/src/lib/context-overflow-verdict.ts +266 -9
  72. package/src/lib/failure-detail.ts +72 -3
  73. package/src/lib/hard-refusal.ts +259 -0
  74. package/src/link/child-activity.ts +57 -0
  75. package/src/link/child-catalog-freshness.ts +149 -0
  76. package/src/link/child-gated-ocx.ts +117 -0
  77. package/src/link/child-observations.ts +205 -0
  78. package/src/link/child-observe.ts +121 -0
  79. package/src/link/child-ops-engine.ts +162 -0
  80. package/src/link/child-update-contract.ts +165 -0
  81. package/src/link/paths.ts +5 -0
  82. package/src/link/remote-windows.ts +42 -6
  83. package/src/link/ssh-argv.ts +126 -32
  84. package/src/link/status-projection.ts +73 -0
  85. package/src/link/sync-fanout-classify.ts +98 -0
  86. package/src/link/tunnel-state.ts +10 -4
  87. package/src/messaging/mcp-queue-rpc.ts +2 -1
  88. package/src/messaging/mcp-queue-server.ts +5 -0
  89. package/src/messaging/mcp-reply-tools.ts +24 -9
  90. package/src/messaging/mcp-reply-wait.ts +70 -0
  91. package/src/oauth/account-resume-health.ts +60 -0
  92. package/src/oauth/anthropic-model-quota.ts +12 -0
  93. package/src/oauth/anthropic-routing.ts +11 -4
  94. package/src/oauth/index.ts +1 -0
  95. package/src/oauth/kiro-iam-identity-center.ts +4 -1
  96. package/src/oauth/store.ts +44 -1
  97. package/src/providers/api-key-pause-state.ts +23 -0
  98. package/src/providers/api-key-pause.ts +68 -10
  99. package/src/providers/api-key-selection-capture.ts +3 -1
  100. package/src/providers/api-key-selection.ts +3 -2
  101. package/src/providers/api-keys.ts +18 -5
  102. package/src/providers/claude-cli-identity.ts +9 -3
  103. package/src/providers/claude-cli-usage-state.ts +11 -6
  104. package/src/providers/claude-cli-usage.ts +27 -8
  105. package/src/providers/codex-capacity.ts +11 -2
  106. package/src/providers/key-failover.ts +13 -6
  107. package/src/providers/model-discovery-config.ts +31 -0
  108. package/src/providers/model-discovery-diagnostic.ts +34 -3
  109. package/src/providers/model-discovery.ts +43 -7
  110. package/src/providers/model-rename-fields.ts +2 -0
  111. package/src/providers/openai-sidecar.ts +15 -2
  112. package/src/providers/provider-id-rewrite.ts +3 -0
  113. package/src/providers/quota/account-cache.ts +52 -34
  114. package/src/providers/quota/anthropic-family-headers.ts +8 -1
  115. package/src/providers/quota/anthropic-usage-windows.ts +66 -9
  116. package/src/providers/quota/report-cache.ts +53 -5
  117. package/src/providers/quota/vendor-probes-key.ts +73 -0
  118. package/src/providers/quota/vendor-probes-oauth.ts +57 -3
  119. package/src/providers/quota-key-accounts.ts +12 -5
  120. package/src/providers/quota-mistral-budget.ts +18 -0
  121. package/src/providers/quota-types.ts +32 -0
  122. package/src/providers/quota.ts +22 -22
  123. package/src/providers/reasoning-metadata.ts +1051 -12
  124. package/src/providers/registry/entries-extended.ts +3 -1
  125. package/src/providers/registry/model-ids.ts +1 -0
  126. package/src/providers/registry/types.ts +6 -0
  127. package/src/quota/reset-observer.ts +4 -2
  128. package/src/quota/reset-seen-store.ts +9 -0
  129. package/src/quota/window-mapping.ts +1 -0
  130. package/src/quota-pool/assemble.ts +4 -1
  131. package/src/responses/hosted-tool-policy.ts +56 -12
  132. package/src/responses/retained-compaction.ts +31 -5
  133. package/src/router.ts +2 -0
  134. package/src/server/auth-cors.ts +11 -8
  135. package/src/server/catalog-download.ts +3 -5
  136. package/src/server/chat-native.ts +11 -2
  137. package/src/server/claude-messages.ts +2 -1
  138. package/src/server/images.ts +41 -13
  139. package/src/server/index/link-listener.ts +16 -2
  140. package/src/server/index/link-relay-sessions.ts +43 -2
  141. package/src/server/index/optional-listeners.ts +18 -0
  142. package/src/server/management/config-routes.ts +7 -1
  143. package/src/server/management/context.ts +1 -1
  144. package/src/server/management/link-child-ops-routes.ts +116 -0
  145. package/src/server/management/link-route-state.ts +10 -0
  146. package/src/server/management/link-routes.ts +10 -0
  147. package/src/server/management/oauth-account-routes.ts +33 -4
  148. package/src/server/management/provider-overwrite-carry.ts +28 -3
  149. package/src/server/management/provider-routes.ts +16 -11
  150. package/src/server/management/route-registry.ts +3 -0
  151. package/src/server/messages-native.ts +5 -0
  152. package/src/server/request-log-failure-detail.ts +59 -1
  153. package/src/server/responses/adapter-dispatch.ts +35 -44
  154. package/src/server/responses/combo-stream-preflight.ts +146 -29
  155. package/src/server/responses/compact.ts +27 -4
  156. package/src/server/responses/context-overflow.ts +58 -2
  157. package/src/server/responses/core-combo-failure.ts +29 -4
  158. package/src/server/responses/core-combo-native.ts +3 -1
  159. package/src/server/responses/core-combo.ts +30 -3
  160. package/src/server/responses/core-errors.ts +3 -1
  161. package/src/server/responses/core-opaque-recovery.ts +45 -2
  162. package/src/server/responses/core-options.ts +12 -0
  163. package/src/server/responses/passthrough-dispatch.ts +30 -38
  164. package/src/server/responses/request-transport.ts +43 -14
  165. package/src/server/responses/reset-replay.ts +58 -2
  166. package/src/server/responses/run-turn-execution.ts +56 -30
  167. package/src/types/claude-tool-loading.ts +48 -0
  168. package/src/types/config.ts +5 -35
  169. package/src/types/provider.ts +21 -0
  170. package/src/types.ts +1 -0
  171. package/src/web-search/parse.ts +44 -4
  172. package/gui/dist/assets/App-CitvEefy.js +0 -59
  173. package/gui/dist/assets/Tray-CeKVWQyB.js +0 -1
  174. package/gui/dist/assets/brand-mark-M92UnxX2.js +0 -1
  175. package/gui/dist/assets/index-BP47do6-.js +0 -94
  176. package/gui/dist/assets/index-DmDooSAG.css +0 -2
  177. package/gui/dist/classic/assets/index-CfGqHooN.js +0 -94
  178. package/gui/dist/classic/assets/quota-summary-R-ih7OlS.js +0 -1
@@ -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
@@ -30,7 +30,7 @@ import type {
30
30
  RequestExecutionBudgetPolicy,
31
31
  RequestExecutionBudget,
32
32
  } from "../../lib/request-execution-budget";
33
- import type { OcxComboDefaultEffort, OcxConfig } from "../../types";
33
+ import type { OcxComboDefaultEffort, OcxConfig, OcxUsage } from "../../types";
34
34
  import type { RequestLogContext } from "../request-log";
35
35
  import type { HandleResponsesOptions, ResponsesDispatchers, ConsumedComboFailure } from "./core-options";
36
36
  import type { TranslatorBudget } from "../../lib/translator-budget";
@@ -126,7 +126,13 @@ import {
126
126
  } from "../relay";
127
127
  import { preflightComboStreamResponse } from "./combo-stream-preflight";
128
128
  import { requiredToolContractOf } from "./combo-required-tool-contract";
129
- import { streamingContextOverflowResponse, jsonContextOverflowResponse, lateAttributionLimitResponse } from "./context-overflow";
129
+ import {
130
+ streamingContextOverflowResponse,
131
+ jsonContextOverflowResponse,
132
+ lateAttributionLimitResponse,
133
+ jsonIncompleteResponse,
134
+ streamingIncompleteResponse,
135
+ } from "./context-overflow";
130
136
  import { mandatoryResponsesReasoningReplayUnavailable } from "./core-replay";
131
137
  import { isReplayRefusalResponse, settleOperatorReplacement, UPSTREAM_RESET_REPLAY_REFUSED_CODE } from "../../lib/upstream-retry";
132
138
  import { attributeFinalRequest } from "../request-log-failure-attribution";
@@ -909,6 +915,9 @@ export async function executeComboResponses(
909
915
  // is gone, so carry the loop's own classification decision instead of re-deriving a
910
916
  // weaker one from the status alone (#4149).
911
917
  let lastFailureClassifiesOverflow = false;
918
+ let zeroOutputLimitFailure: { childLog: RequestLogContext; usage?: OcxUsage } | undefined;
919
+ let lastFailureUpstreamCode: string | undefined;
920
+ const wantsStream = (rawBody as { stream?: unknown } | null)?.stream === true || (body as { stream?: unknown } | null)?.stream === true;
912
921
  // Local input admission refusals (#1524), while every failed target so far was one: such a
913
922
  // target sent nothing, so an exhausted ladder must not be reported as a provider rejection.
914
923
  let localAdmissionRefusals: string[] | undefined = [];
@@ -928,6 +937,12 @@ export async function executeComboResponses(
928
937
  adoptFailedChildLog(contextFailure.childLog);
929
938
  return contextFailure.response;
930
939
  }
940
+ if (lastFailure && lastFailureUpstreamCode === "zero_output_token_limit" && zeroOutputLimitFailure) {
941
+ adoptFailedChildLog(zeroOutputLimitFailure.childLog);
942
+ return wantsStream
943
+ ? streamingIncompleteResponse(responseModel, zeroOutputLimitFailure.usage, "max_output_tokens", options.translatorBudget)
944
+ : jsonIncompleteResponse(responseModel, zeroOutputLimitFailure.usage, "max_output_tokens");
945
+ }
931
946
  const returnsQuota = lastFailure && [400, 401, 403].includes(lastFailure.status) && quotaFailure;
932
947
  const failedChildLog = returnsQuota ? quotaFailedChildLog : lastFailedChildLog;
933
948
  if (failedChildLog) adoptFailedChildLog(failedChildLog);
@@ -1371,7 +1386,7 @@ export async function executeComboResponses(
1371
1386
  attempt,
1372
1387
  failure.response.status,
1373
1388
  Date.now() - started,
1374
- failure.usage,
1389
+ failure.usage ?? childLog.usage,
1375
1390
  );
1376
1391
  if (isReplayRefusalResponse(failure.response)) {
1377
1392
  // Numeric 429 is a client replay policy here, not an upstream quota observation.
@@ -1387,6 +1402,7 @@ export async function executeComboResponses(
1387
1402
  }
1388
1403
  attemptRetained = true;
1389
1404
  lastFailure = failure.response;
1405
+ lastFailureUpstreamCode = failure.upstreamCode;
1390
1406
  toolChoiceRefusalsOnly = (toolChoiceRefusalsOnly ?? true) && isMandatoryToolChoiceRefusal(failure.response);
1391
1407
  // A real target failure ends the session pin; the next turn is decided afresh (#7525).
1392
1408
  jevPin?.forget();
@@ -1416,8 +1432,11 @@ export async function executeComboResponses(
1416
1432
  : isPolicyCandidateRefusal(failure.response) ? "hop"
1417
1433
  : comboFailureDecision(failure.response.status, failure.classificationText, {
1418
1434
  code: failure.upstreamCode,
1435
+ rootCode: failure.upstreamRootCode,
1419
1436
  codexModelRefusal: failure.codexModelRefusal,
1420
1437
  verifiedPlanRefusal: failure.verifiedPlanRefusal,
1438
+ malformedResponseFormat: failure.malformedResponseFormat,
1439
+ openRouterOpaque400: failure.openRouterOpaque400,
1421
1440
  // The adapter the failed leg actually resolved: a configured `kiro` provider can route a
1422
1441
  // model through another wire via `modelAdapters`, and an unresolved leg grants no hop.
1423
1442
  failedAdapter: childLog.providerAdapter,
@@ -1475,6 +1494,12 @@ export async function executeComboResponses(
1475
1494
  contextFailure = { childLog, response: formatErrorResponse(400, "invalid_request_error",
1476
1495
  failure.upstreamMessage ?? failure.classificationText, { code: "context_length_exceeded", classified: true }) };
1477
1496
  }
1497
+ if (failure.upstreamCode === "zero_output_token_limit") {
1498
+ zeroOutputLimitFailure = {
1499
+ childLog,
1500
+ usage: failure.usage ?? childLog.usage,
1501
+ };
1502
+ }
1478
1503
  // A bare status made a revoked credential read as a provider outage. Log the classified
1479
1504
  // condition (a closed member), never upstream-authored code or message text.
1480
1505
  const failureReason = classifyUpstreamCondition({
@@ -1488,6 +1513,8 @@ export async function executeComboResponses(
1488
1513
  const attemptedTargets = pick.attempted;
1489
1514
  const failureCooldownScope = isPolicyCandidateRefusal(failure.response) ? "none" : comboFailureCooldownScope(failure.response.status, failure.classificationText, {
1490
1515
  code: failure.upstreamCode,
1516
+ malformedResponseFormat: failure.malformedResponseFormat,
1517
+ openRouterOpaque400: failure.openRouterOpaque400,
1491
1518
  });
1492
1519
  const failedTargetKey = targetKey(pick.target);
1493
1520
  let failedTargetCooldownRecorded = false;
@@ -70,7 +70,9 @@ export function normalizeUpstreamErrorText(text: string, fallback: string): Norm
70
70
  message = redactSecretString(source.message.trim()).slice(0, 500);
71
71
  }
72
72
  if (typeof source.type === "string" && source.type.trim()) type = source.type.trim();
73
- if (typeof source.code === "string" && source.code.trim()) code = source.code.trim();
73
+ if (typeof source.code === "string" && source.code.trim()) {
74
+ code = source.code.trim();
75
+ }
74
76
  } catch {
75
77
  /* non-JSON upstream body — retain the bounded display-safe text */
76
78
  }
@@ -1,6 +1,12 @@
1
1
  import { ENCRYPTED_FUNCTION_OUTPUT_REJECTION, upstreamErrorMessageFromPayload } from "../../lib/errors";
2
2
  import { readBoundedResponseBody } from "../../lib/bounded-body";
3
- import { isReasoningEffortRejection } from "../../providers/reasoning-metadata";
3
+ import { isHardPolicyOrOriginRefusal } from "../../lib/hard-refusal";
4
+ import { isPlainObject } from "../../lib/plain-data";
5
+ import {
6
+ hasConflictingReasoningEffortCode,
7
+ isReasoningEffortRejection,
8
+ planReasoningEffortDowngrade,
9
+ } from "../../providers/reasoning-metadata";
4
10
  import { isAnthropicFastRefusal } from "../../providers/anthropic-fast";
5
11
  import type { AdapterRequest } from "../../adapters/base";
6
12
  import { isNonReplayableResponse } from "../../lib/upstream-retry";
@@ -64,6 +70,43 @@ export function outboundResponsesInput(bodyText: string | undefined): unknown[]
64
70
  }
65
71
  }
66
72
 
73
+ /**
74
+ * The next published rung after an upstream reasoning-effort refusal, or undefined when no replay
75
+ * applies. A direct request repairs once. A combo candidate may walk the finite ladder one refused
76
+ * rung at a time: each refusal is learned, so a rung is never offered twice, and the request send
77
+ * budget bounds the walk (#8173). The caller sets `guard.attempted` when it actually replays.
78
+ */
79
+ export async function refusedReasoningEffortDowngrade(
80
+ response: Response,
81
+ signal: AbortSignal,
82
+ guard: { attempted: boolean },
83
+ comboAttempt: boolean | undefined,
84
+ plan: Omit<Parameters<typeof planReasoningEffortDowngrade>[0], "rejectionText">,
85
+ ): Promise<ReturnType<typeof planReasoningEffortDowngrade>> {
86
+ if (guard.attempted && !comboAttempt) return undefined;
87
+ const rejectionText = await reasoningEffortRejectionText(response, false, signal);
88
+ return rejectionText === undefined
89
+ ? undefined
90
+ : planReasoningEffortDowngrade({ ...plan, rejectionText });
91
+ }
92
+
93
+ /**
94
+ * The passthrough rebuild serializes `_rawBody`, so a downgraded rung has to be written there as
95
+ * well or the replay resends the refused effort.
96
+ *
97
+ * Only shapes that already carry the control are rewritten. An absent `reasoning`, or one the
98
+ * caller sent as a string or `null`, is left exactly as it was: inventing `{ effort }` here would
99
+ * add a reasoning control to a body that never asked for one, and overriding a string would
100
+ * replace whatever that wire meant by it. `reasoning_effort` is kept in step only when present.
101
+ */
102
+ export function withRawBodyReasoningEffort(rawBody: unknown, effort: string): unknown {
103
+ if (!isPlainObject(rawBody)) return rawBody;
104
+ const next: Record<string, unknown> = { ...rawBody };
105
+ if (isPlainObject(rawBody.reasoning)) next.reasoning = { ...rawBody.reasoning, effort };
106
+ if ("reasoning_effort" in rawBody) next.reasoning_effort = effort;
107
+ return next;
108
+ }
109
+
67
110
 
68
111
  export function outboundResponsesBodyCarriesEncryptedFunctionOutput(bodyText: string | undefined): boolean {
69
112
  const input = outboundResponsesInput(bodyText);
@@ -365,7 +408,7 @@ export async function reasoningEffortRejectionText(
365
408
  if (response.status !== 400 && response.status !== 403) return undefined;
366
409
  try {
367
410
  const body = await readBoundedResponseBody(response.clone(), { signal });
368
- if (!body.displaySafe || body.truncated) return undefined;
411
+ if (!body.displaySafe || body.truncated || isHardPolicyOrOriginRefusal(body.text) || hasConflictingReasoningEffortCode(body.text)) return undefined;
369
412
  return isReasoningEffortRejection(body.text) ? body.text : undefined;
370
413
  } catch {
371
414
  return undefined;
@@ -33,8 +33,20 @@ export interface ConsumedComboFailure {
33
33
  classificationText: string;
34
34
  /** Complete bounded-envelope evidence captured before display truncation; never serialized. */
35
35
  codexModelRefusal?: CodexAccountModelRefusal;
36
+ /** Complete bounded-envelope malformed response_format diagnostic verdict captured before display truncation. */
37
+ malformedResponseFormat?: boolean;
38
+ /** Complete bounded-envelope OpenRouter opaque-400 verdict captured before display truncation. */
39
+ openRouterOpaque400?: boolean;
36
40
  /** Structured upstream `error.code` when present in the failure body. */
37
41
  upstreamCode?: string;
42
+ /**
43
+ * The envelope root's own structured code when it differs from {@link upstreamCode}.
44
+ *
45
+ * `normalizeUpstreamErrorText` selects the nested record first, so a root verdict would
46
+ * otherwise never reach the combo decision. Both transports pass it, and the decision hops
47
+ * only when the root and the record each would.
48
+ */
49
+ upstreamRootCode?: string;
38
50
  /** Sanitized structured `error.message`; compared only against proxy-owned constants, never emitted. */
39
51
  upstreamMessage?: string;
40
52
  /** Complete structured provider type, retained for conservative recovery classification. */
@@ -165,15 +165,13 @@ import {
165
165
  resetStreamedOpaqueBlobLogContext,
166
166
  consoleGoUploadRejectionBody,
167
167
  CONSOLE_GO_UPLOAD_RETRY_DELAY_MS,
168
- reasoningEffortRejectionText,
168
+ refusedReasoningEffortDowngrade, withRawBodyReasoningEffort,
169
169
  } from "./core-opaque-recovery";
170
170
  import type { RequestLogContext } from "../request-log";
171
171
  import { deferProtocolSafeResetRecovery, preflightComboStreamResponse } from "./combo-stream-preflight";
172
- import { authorizeResendForRecovery } from "../../lib/request-resend-gate";
173
- import { ambiguousResendAllowanceFor, selfContainedResponsesBody } from "./reset-replay";
172
+ import { ambiguousResendAllowanceFor, ambiguousResendAuthorizer, nativePassthroughReplayJudgmentBody, selfContainedResponsesBody } from "./reset-replay";
174
173
  import { upstreamErrorMessageFromPayload, ENCRYPTED_FUNCTION_OUTPUT_REJECTION } from "../../lib/errors";
175
174
  import { isTransientConsoleGoUploadRejection } from "../../providers/opencode-zen-rate-limit";
176
- import { planReasoningEffortDowngrade } from "../../providers/reasoning-metadata";
177
175
  import { unboundPoolSpendRefusalResponse } from "../workflow-refusal";
178
176
  import { createNativeContinuationDispatch } from "./native-continuation-send";
179
177
  import { guardPassthroughCompletion, parseOutboundRequestBody } from "./passthrough-completion";
@@ -774,7 +772,7 @@ export async function preparePassthroughExchange(
774
772
  */
775
773
  let selfContainedJudgment: boolean | undefined;
776
774
  const requestIsSelfContained = (): boolean =>
777
- selfContainedJudgment ??= selfContainedResponsesBody(parsed._rawBody);
775
+ selfContainedJudgment ??= selfContainedResponsesBody(nativePassthroughReplayJudgmentBody(parsed));
778
776
  /**
779
777
  * The operator's replacement grant for THIS logical request.
780
778
  *
@@ -785,6 +783,7 @@ export async function preparePassthroughExchange(
785
783
  */
786
784
  const ambiguousResend = () =>
787
785
  ambiguousResendAllowanceFor(route.provider, requestIsSelfContained, claimAmbiguousResend);
786
+ const authorizeAmbiguousResend = ambiguousResendAuthorizer(ambiguousResend, () => safeHostLabel(request.url));
788
787
  /**
789
788
  * The pre-header row of the stage table, asked through the one gate.
790
789
  *
@@ -792,8 +791,7 @@ export async function preparePassthroughExchange(
792
791
  * the server tree; routing the answer through `authorizeResendForRecovery` here is what
793
792
  * keeps the decision derived from the table rather than restated as a boolean.
794
793
  */
795
- const claimPreHeaderResend = (): boolean =>
796
- authorizeResendForRecovery("pre-header", "connection-reset", ambiguousResend()).allowed;
794
+ const claimPreHeaderResend = (): boolean => authorizeAmbiguousResend("pre-header");
797
795
  /**
798
796
  * The one replacement send the ambiguous rows at the end of the recovery loop may buy: an SSE
799
797
  * body that died before any output, and a Codex WebSocket that died under its create frame
@@ -1063,7 +1061,8 @@ export async function preparePassthroughExchange(
1063
1061
  }
1064
1062
 
1065
1063
  const opaqueBlobRecoveryGuard: OpaqueBlobRecoveryGuard = { attempted: false };
1066
- // At most one reasoning-effort downgrade per request.
1064
+ // Direct requests get one reasoning-effort downgrade. Combo candidates may walk down the
1065
+ // published ladder one refused rung at a time; the request send budget bounds those retries.
1067
1066
  const reasoningEffortDowngradeGuard: { attempted: boolean } = { attempted: false };
1068
1067
  /** Rebind the refreshed wire before transferring this request to the Chat pipeline. */
1069
1068
  function bindRefreshedAdapter(refreshedAdapter: typeof transportState.adapter) {
@@ -1097,6 +1096,7 @@ export async function preparePassthroughExchange(
1097
1096
  let rateLimitRetries = 0;
1098
1097
  const rebuildAndRefetch = async (
1099
1098
  recovery: AttemptRecoveryKind,
1099
+ preserveFailureResponse?: Response,
1100
1100
  ): Promise<Response | { failed: Response | PassthroughAdapterHandoff }> => {
1101
1101
  const retryAdapter = resolveSelectionAdapter(
1102
1102
  resolveWireProtocolOverride(route.providerName, route.modelId, route.provider, inboundWire, route.staticPolicy),
@@ -1147,6 +1147,8 @@ export async function preparePassthroughExchange(
1147
1147
  { allowFinalRecoveryReserve: transientSendPolicy() === null },
1148
1148
  );
1149
1149
  if (recovery === "empty-completion") allowance.attempts = Math.min(1, allowance.attempts);
1150
+ // An unfunded combo rung keeps the upstream refusal for combo failover instead of a budget 429.
1151
+ if (preserveFailureResponse && allowance.attempts < 1) { request.releaseBodyObservation?.(); return { failed: preserveFailureResponse }; }
1150
1152
  const recoveryAccounting = copilotSendAccounting(allowance.permit);
1151
1153
  try {
1152
1154
  return await fetchWithTransientRetry(
@@ -1827,34 +1829,24 @@ export async function preparePassthroughExchange(
1827
1829
  continue passthroughRecovery;
1828
1830
  }
1829
1831
  }
1830
- // Reasoning-effort downgrade: a rung the catalog still advertises can be refused upstream --
1831
- // the metadata records the model's ladder, not this account's entitlement (a Muse Code
1832
- // subscription gates max on muse-spark-1.3-contributor, for example). Learn the refusal so
1833
- // later turns clamp before dispatch, then replay once at the next lower published rung
1834
- // instead of failing the turn; requestedEffort/effectiveEffort keep both values in usage.
1835
- if (!reasoningEffortDowngradeGuard.attempted) {
1836
- const rejectionText = await reasoningEffortRejectionText(
1837
- upstreamResponse,
1838
- reasoningEffortDowngradeGuard.attempted,
1839
- upstream.signal,
1840
- );
1841
- const downgrade = rejectionText === undefined
1842
- ? undefined
1843
- : planReasoningEffortDowngrade({
1844
- provider: route.provider,
1845
- modelId: parsed.modelId,
1846
- requested: parsed.options.reasoning,
1847
- rejectionText,
1848
- });
1849
- if (downgrade && !configuredTransientSendBudgetExhausted()) {
1850
- reasoningEffortDowngradeGuard.attempted = true;
1851
- parsed.options.reasoning = downgrade.effort;
1852
- try { void upstreamResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ }
1853
- const result = await rebuildAndRefetch("reasoning-effort-downgrade");
1854
- if ("failed" in result) return result.failed;
1855
- upstreamResponse = result;
1856
- continue passthroughRecovery;
1857
- }
1832
+ // A rung the catalog advertises can still be refused upstream -- metadata describes the
1833
+ // model's ladder, not this account's entitlement. Learn each refusal so later turns clamp
1834
+ // before dispatch. Direct requests repair once; combo candidates may retry the next lower
1835
+ // published rung until it works, the ladder ends, or the send budget is spent.
1836
+ const downgrade = await refusedReasoningEffortDowngrade(upstreamResponse, upstream.signal, reasoningEffortDowngradeGuard,
1837
+ options.comboAttempt, { provider: route.provider, modelId: parsed.modelId, requested: parsed.options.reasoning });
1838
+ if (downgrade && !configuredTransientSendBudgetExhausted()) {
1839
+ reasoningEffortDowngradeGuard.attempted = true;
1840
+ parsed.options.reasoning = downgrade.effort;
1841
+ parsed._rawBody = withRawBodyReasoningEffort(parsed._rawBody, downgrade.effort);
1842
+ // A combo keeps the refusal, so an unfunded rung still reaches combo failover as the original 400.
1843
+ const refusal = options.comboAttempt ? upstreamResponse : undefined;
1844
+ if (!refusal) try { void upstreamResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ }
1845
+ const result = await rebuildAndRefetch("reasoning-effort-downgrade", refusal);
1846
+ if ("failed" in result) return result.failed;
1847
+ if (refusal) try { void refusal.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ }
1848
+ upstreamResponse = result;
1849
+ continue passthroughRecovery;
1858
1850
  }
1859
1851
 
1860
1852
  // The WebSocket row of the same table (#4191). A Codex socket that closed or failed under its
@@ -1870,7 +1862,7 @@ export async function preparePassthroughExchange(
1870
1862
  // Asked before the gate, which claims last: a replacement the budget cannot fund must not
1871
1863
  // spend the request's one grant.
1872
1864
  && remainingTransientSendBudget(transientSendAttempts()) > 0
1873
- && authorizeResendForRecovery(socketDeathStage, "connection-reset", ambiguousResend()).allowed
1865
+ && authorizeAmbiguousResend(socketDeathStage)
1874
1866
  ) {
1875
1867
  try { void upstreamResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ }
1876
1868
  console.warn(`[upstream-retry] codex websocket died before any Responses event (${safeHostLabel(request.url)}); `
@@ -1931,7 +1923,7 @@ export async function preparePassthroughExchange(
1931
1923
  // pre-header helper shares. A committed stage refuses here without touching the
1932
1924
  // allowance, which is what keeps a turn that already emitted output from draining
1933
1925
  // the replacement a later ambiguous reset would have been entitled to.
1934
- authorize: () => authorizeResendForRecovery(stage, "connection-reset", ambiguousResend()).allowed,
1926
+ authorize: () => authorizeAmbiguousResend(stage),
1935
1927
  acceptResponse: candidate => {
1936
1928
  const type = candidate.headers.get("content-type")?.toLowerCase() ?? "";
1937
1929
  return type.includes("text/event-stream") || (!type && upstreamRequestsStream);
@@ -1,9 +1,10 @@
1
1
  import { publicOAuthErrorPresentation } from "../../oauth";
2
- import { projectLocalModelRefusalLog } from "../request-log-failure-detail";
2
+ import { observeProviderFailureEvent, projectLocalModelRefusalLog } from "../request-log-failure-detail";
3
3
  import { markProxyError } from "../../lib/client-error-body";
4
4
  import { formatClientRetryAfter } from "../../lib/client-retry-after";
5
5
  import { SendBudgetExhaustedError, errorDestinationText, providerErrorDestinationLabel } from "../../lib/upstream-retry";
6
- import { appendLoadedToolDefinitions, appendOnlyToolLoadingMatches } from "../../claude/inbound-tool-loading";
6
+ import { appendLoadedToolDefinitions, toolLoadingModelMatches } from "../../claude/inbound-tool-loading";
7
+ import { applyChatToolDispatch } from "../../claude/chat-tool-dispatch";
7
8
  import { isRec } from "../../claude/inbound-records";
8
9
  import { isOpenCodeGoResponsesUrl } from "../../adapters/opencode-go-additional-tools";
9
10
  import { buildResponsesTransport } from "../../adapters/openai-responses/transport";
@@ -84,6 +85,7 @@ import {
84
85
  providerApiKeySelectionIsCurrent,
85
86
  resolveCurrentProviderApiKeyTransport,
86
87
  } from "../../providers/api-key-selection";
88
+ import { isProviderApiKeyPaused, ProviderApiKeyPausedError } from "../../providers/api-key-pause";
87
89
  import { resolveAdapter, resolveWireProtocolOverride } from "../adapter-resolve";
88
90
  import { codexWsExecutorBinding, fetchWithHeaderTimeout, physicalSendGuardInit, physicalSendObserverInit, providerFetch, sendWithConnectionPolicy } from "./fetch-helpers";
89
91
  import { resolveConnectTimeoutMs } from "../../stall-timeout";
@@ -596,6 +598,7 @@ export async function prepareResponsesTransport(
596
598
  const bindKeyUsageFromBridge = (usage: OcxUsage | undefined): void => {
597
599
  logCtx.usageFromBridge = true;
598
600
  if (usesApiKeyAccount(route.provider)) {
601
+ if (!logCtx.activeAttempt?.usage && usage) recordKeyAttemptUsage(logCtx, usage);
599
602
  logCtx.usage = logCtx.activeAttempt?.usage;
600
603
  } else if (usage) {
601
604
  logCtx.usage = usage;
@@ -629,11 +632,19 @@ export async function prepareResponsesTransport(
629
632
  // Capture this physical adapter's destination. A retry/rebind gets a fresh decision, and
630
633
  // each build projects a copy so unselected fallbacks retain the original tool catalog.
631
634
  const discovery = options.anthropicToolLoadingSource;
632
- const appendOnly = inboundWire === "anthropic" && discovery && provider.adapter === "openai-responses"
635
+ // Shared by both direct-route opt-ins: combo attempts and policy-owned requests keep the
636
+ // original catalog.
637
+ const directToolLoadingRoute = inboundWire === "anthropic"
633
638
  && !options.comboAttempt && !route.combo && route.routeKind !== "combo" && route.routeKind !== "policy"
634
- && !options.policyFallbackCandidate && !options.policyRequestScope?.eligibility
635
- && appendOnlyToolLoadingMatches(config.claudeCode?.appendOnlyToolLoadingModels,
636
- `${route.providerName}/${parsed._wireModelOverride ?? route.modelId}`);
639
+ && !options.policyFallbackCandidate && !options.policyRequestScope?.eligibility;
640
+ const wireModel = `${route.providerName}/${parsed._wireModelOverride ?? route.modelId}`;
641
+ const appendOnly = discovery && directToolLoadingRoute && provider.adapter === "openai-responses"
642
+ && toolLoadingModelMatches(config.claudeCode?.appendOnlyToolLoadingModels, wireModel);
643
+ // The Chat wire has no additional_tools; its own opt-in keeps the catalog stable through a
644
+ // dispatcher instead, projected and un-projected at this one physical adapter (#7452).
645
+ const chatDispatch = discovery && directToolLoadingRoute && provider.adapter === "openai-chat"
646
+ && toolLoadingModelMatches(config.claudeCode?.chatToolDispatchModels, wireModel);
647
+ if (chatDispatch) applyChatToolDispatch(resolved, discovery);
637
648
  if (appendOnly) {
638
649
  const buildWithOriginalCatalog = resolved.buildRequest.bind(resolved);
639
650
  resolved.buildRequest = (requestParsed, incoming) => {
@@ -674,6 +685,7 @@ export async function prepareResponsesTransport(
674
685
  const observeEvent = (event: AdapterEvent, response: object): void => {
675
686
  delivery.noteAdapterEvent();
676
687
  observeUsage(event, response);
688
+ observeProviderFailureEvent(logCtx, event);
677
689
  };
678
690
  const parseStream = resolved.parseStream.bind(resolved);
679
691
  resolved.parseStream = async function* (...args) {
@@ -793,7 +805,12 @@ export async function prepareResponsesTransport(
793
805
  const fresh = resolveCurrentProviderApiKeyTransport(config, route.providerName, { ...route.provider, _apiKeyAttempt: undefined });
794
806
  if (fresh) current = selectProactiveApiKeyTransport(config, route.providerName, fresh) ?? fresh;
795
807
  }
796
- if (!current) throw new Error("API key selection is unavailable before dispatch");
808
+ if (!current) {
809
+ // Rethrown through oauthDispatch so adapter-dispatch / passthrough-dispatch map it
810
+ // as a local 403 admission refusal without charging an upstream send.
811
+ if (isProviderApiKeyPaused(config.providers[route.providerName])) throw new ProviderApiKeyPausedError();
812
+ throw new Error("API key selection is unavailable before dispatch");
813
+ }
797
814
  if (route.provider.googleMode === "vertex" || current.googleMode === "vertex") {
798
815
  const freshPolicy = captureRouteStaticPolicy(route.providerName, route.modelId, current, route.staticPolicy.effectiveAlias, inboundWire);
799
816
  if (freshPolicy.model.adapter !== route.staticPolicy.model.adapter) throw new Error("Vertex model wire changed before dispatch");
@@ -810,7 +827,7 @@ export async function prepareResponsesTransport(
810
827
  if (route.provider.authMode === "forward") return false;
811
828
  const available = route.provider.authMode === "oauth"
812
829
  ? getAccountSet(route.providerName)?.accounts.some(row => !row.paused && !row.needsReauth)
813
- : !!config.providers[route.providerName]?.apiKey;
830
+ : !isProviderApiKeyPaused(config.providers[route.providerName]) && !!config.providers[route.providerName]?.apiKey;
814
831
  if (!available) return false;
815
832
  await refreshDispatchAdapter(requestParsed);
816
833
  // Bind before the recovery caller rebuilds. A terminal retry can be a clone;
@@ -1278,13 +1295,25 @@ export async function prepareResponsesTransport(
1278
1295
  // The Transport variant, not the bare picker: the picker answers with the PERSISTED row, and
1279
1296
  // a built-in provider stored in its valid minimal form would lose the adapter id, base URL
1280
1297
  // and static headers registry backfill supplies, throwing `Unknown adapter: undefined`.
1281
- const proactiveKeyProvider = selectProactiveApiKeyTransport(
1282
- config,
1283
- route.providerName,
1284
- route.provider,
1285
- parsed.options.promptCacheKey,
1286
- );
1298
+ let proactiveKeyProvider: OcxProviderConfig | null;
1299
+ try {
1300
+ proactiveKeyProvider = selectProactiveApiKeyTransport(
1301
+ config,
1302
+ route.providerName,
1303
+ route.provider,
1304
+ parsed.options.promptCacheKey,
1305
+ );
1306
+ } catch (err) {
1307
+ if (err instanceof OAuthAccountPausedError) {
1308
+ return markProxyError(formatErrorResponse(403, "permission_error", publicOAuthAuthenticationErrorMessage(err)), publicOAuthErrorPresentation(err));
1309
+ }
1310
+ throw err;
1311
+ }
1287
1312
  if (proactiveKeyProvider) route.provider = proactiveKeyProvider;
1313
+ if (isProviderApiKeyPaused(route.provider)) {
1314
+ const err = new ProviderApiKeyPausedError();
1315
+ return markProxyError(formatErrorResponse(403, "permission_error", publicOAuthAuthenticationErrorMessage(err)), publicOAuthErrorPresentation(err));
1316
+ }
1288
1317
  route.provider = resolveProviderTransport(
1289
1318
  route.providerName,
1290
1319
  route.provider,
@@ -14,10 +14,15 @@
14
14
  * hosted tools into client execution, so every hazard that reaches the wire was visible here,
15
15
  * and a hazard visible here may already have been removed. A cheap fail-closed answer beats
16
16
  * re-parsing a multi-megabyte outbound body on every send.
17
+ *
18
+ * One removal is certain enough to judge on directly: a `previous_response_id` this proxy
19
+ * expanded from its own replay state. The native adapter strips that id from every send, so the
20
+ * wire carries the complete input and no continuation handle (#8453).
17
21
  */
18
- import type { OcxProviderConfig } from "../../types";
22
+ import type { OcxParsedRequest, OcxProviderConfig } from "../../types";
19
23
  import { resetReplayPolicyFor } from "../../providers/key-failover";
20
- import type { AmbiguousResendAllowance } from "../../lib/request-resend-gate";
24
+ import { authorizeResendForRecovery, type AmbiguousResendAllowance, type ResendDecision } from "../../lib/request-resend-gate";
25
+ import type { RequestFailureStage } from "../../lib/request-failure-model";
21
26
 
22
27
  /** Input items a client owns end to end: replaying them re-runs nothing but the model. */
23
28
  const CLIENT_INPUT_ITEM_TYPES: ReadonlySet<string> = new Set([
@@ -78,6 +83,57 @@ export function selfContainedResponsesBody(body: unknown): boolean {
78
83
  });
79
84
  }
80
85
 
86
+ /**
87
+ * The native passthrough body to judge: the inbound body, minus a `previous_response_id` the
88
+ * proxy already expanded into `input`.
89
+ *
90
+ * `expandPreviousResponseInput` keeps the id on the expanded body because Kiro and Cursor read
91
+ * their conversation ids from it, so the inbound body always names it. The native Responses
92
+ * adapter (and the Azure adapter that wraps it) removes it whenever `_previousResponseInputExpanded`
93
+ * is set, which is the flag read here. Judging the id that never reaches the wire refused every
94
+ * chained Codex turn, so an operator's `retryOnReset` opt-in applied only to first turns.
95
+ *
96
+ * An id that was NOT expanded is forwarded to the destination and still refuses: that send
97
+ * continues state stored on the origin.
98
+ */
99
+ export function nativePassthroughReplayJudgmentBody(
100
+ parsed: Pick<OcxParsedRequest, "_rawBody" | "_previousResponseInputExpanded">,
101
+ ): unknown {
102
+ const body = parsed._rawBody;
103
+ if (parsed._previousResponseInputExpanded !== true || !record(body) || !Object.hasOwn(body, "previous_response_id")) {
104
+ return body;
105
+ }
106
+ const { previous_response_id: _expandedLocally, ...wire } = body;
107
+ return wire;
108
+ }
109
+
110
+ /**
111
+ * Log why an ambiguous reset was not replaced. Operators who opted in otherwise saw only the
112
+ * terminal 429 and could not tell a missing policy from a request judged not replayable or an
113
+ * allowance already spent (#8453). Host label, stage and reason only: no body, no credential.
114
+ */
115
+ export function warnAmbiguousResendRefusal(decision: ResendDecision, hostLabel: string): void {
116
+ if (decision.allowed || !decision.refusal.startsWith("ambiguous-")) return;
117
+ console.warn(`[upstream-retry] ambiguous reset not replaced (${hostLabel}, ${decision.stage}): ${decision.refusal}`);
118
+ }
119
+
120
+ /**
121
+ * One gate answer for every ambiguous row of a lane -- pre-header, post-header SSE, and a Codex
122
+ * WebSocket that died under its create frame -- asked through `authorizeResendForRecovery` and
123
+ * with its refusal reason logged. The allowance and host label are read per ask, because the
124
+ * recovery loop reassigns the provider row and the request URL.
125
+ */
126
+ export function ambiguousResendAuthorizer(
127
+ allowance: () => AmbiguousResendAllowance | undefined,
128
+ hostLabel: () => string,
129
+ ): (stage: RequestFailureStage) => boolean {
130
+ return stage => {
131
+ const decision = authorizeResendForRecovery(stage, "connection-reset", allowance());
132
+ warnAmbiguousResendRefusal(decision, hostLabel());
133
+ return decision.allowed;
134
+ };
135
+ }
136
+
81
137
  /**
82
138
  * Chat Completions tools are executed by the client by spec -- the origin only emits the call.
83
139
  * Anything else (`web_search`, `code_interpreter`, a vendor hosted tool) runs on the origin during