@bitkyc08/opencodex 2.96.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-bwugJRKn.js → App-DuNhggE1.js} +15 -15
  3. package/gui/dist/assets/{Tray-BOPQyDbH.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-6HsrHQAy.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +11 -1
  16. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  17. package/src/adapters/openai-responses/passthrough.ts +5 -4
  18. package/src/adapters/openai-responses/reasoning.ts +9 -4
  19. package/src/adapters/openai-responses/request-strips.ts +1 -1
  20. package/src/adapters/physical-send.ts +3 -3
  21. package/src/adapters/zed-openai-stream.ts +2 -1
  22. package/src/bridge/errors.ts +11 -2
  23. package/src/bridge/response-json.ts +2 -1
  24. package/src/bridge/sse.ts +14 -6
  25. package/src/chat/failure-verdict.ts +21 -0
  26. package/src/chat/outbound.ts +139 -21
  27. package/src/claude/outbound.ts +49 -2
  28. package/src/cli/capabilities-base.ts +25 -3
  29. package/src/cli/capabilities-command.ts +12 -3
  30. package/src/cli/capability-contracts.ts +2 -0
  31. package/src/cli/codex-launch-auth.ts +30 -1
  32. package/src/cli/codex-launcher.ts +12 -5
  33. package/src/cli/codex-shim-autorestore.ts +5 -4
  34. package/src/cli/dispatch.ts +11 -176
  35. package/src/cli/help.ts +2 -2
  36. package/src/cli/index.ts +5 -1
  37. package/src/cli/link.ts +1 -1
  38. package/src/cli/registry.ts +11 -3
  39. package/src/cli/root.ts +8 -0
  40. package/src/cli/sync-command.ts +243 -0
  41. package/src/cli/sync-fanout-process.ts +92 -0
  42. package/src/cli/sync-fanout.ts +150 -0
  43. package/src/cli/sync-flags.ts +10 -0
  44. package/src/cli/sync-link-status.ts +39 -0
  45. package/src/cli/sync-update-guard.ts +18 -0
  46. package/src/client/connect.ts +31 -14
  47. package/src/client/link-home.ts +3 -2
  48. package/src/client/machine-listener.ts +3 -0
  49. package/src/client/restore-ownership.ts +19 -1
  50. package/src/client/runtime-restart.ts +12 -4
  51. package/src/client/runtime.ts +40 -11
  52. package/src/client/stop-routing.ts +62 -0
  53. package/src/client/sync-runtime.ts +65 -0
  54. package/src/clients/config-export.ts +32 -3
  55. package/src/codex/auth-context.ts +49 -103
  56. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  57. package/src/codex/catalog/provider-models.ts +6 -8
  58. package/src/codex/forward-transport-headers.ts +35 -6
  59. package/src/codex/inject/config-toml.ts +88 -0
  60. package/src/codex/inject/multi-agent-v2.ts +30 -4
  61. package/src/codex/inject/plan.ts +34 -7
  62. package/src/codex/inject-coordination.ts +11 -0
  63. package/src/codex/inject.ts +18 -7
  64. package/src/codex/lineage.ts +13 -7
  65. package/src/codex/quota.ts +22 -6
  66. package/src/codex/request-owned-affinity-key.ts +11 -0
  67. package/src/codex/request-owned-affinity.ts +118 -0
  68. package/src/codex/request-owned-main-pin.ts +86 -0
  69. package/src/codex/role-capability.ts +52 -41
  70. package/src/codex/routing/active-account.ts +13 -5
  71. package/src/codex/routing/selection.ts +40 -1
  72. package/src/codex/routing/thread-affinity-store.ts +916 -0
  73. package/src/codex/routing/thread-affinity.ts +90 -12
  74. package/src/codex/toml-source-lines.ts +72 -13
  75. package/src/combos/failover.ts +6 -109
  76. package/src/combos/request.ts +2 -2
  77. package/src/combos/resolve.ts +29 -11
  78. package/src/config/process-state.ts +5 -0
  79. package/src/config/schema/leaf-validators.ts +1 -0
  80. package/src/generated/compatibility-version.json +433 -165
  81. package/src/images/loop.ts +2 -1
  82. package/src/lib/client-error-body.ts +184 -0
  83. package/src/lib/client-retry-after.ts +66 -0
  84. package/src/lib/config-ownership.ts +4 -0
  85. package/src/lib/context-overflow-verdict.ts +113 -0
  86. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  87. package/src/lib/desktop-cli-handoff.mjs +11 -1
  88. package/src/lib/empty-tool-catalog.ts +25 -3
  89. package/src/lib/error-destination.ts +47 -0
  90. package/src/lib/failure-detail.ts +66 -0
  91. package/src/lib/model-identity.ts +44 -0
  92. package/src/lib/private-sqlite-path.ts +124 -0
  93. package/src/lib/response-service-tier.ts +17 -0
  94. package/src/lib/retry-after.ts +3 -0
  95. package/src/lib/spend-ledger-owner.ts +43 -4
  96. package/src/lib/upstream-condition.ts +142 -0
  97. package/src/lib/upstream-retry.ts +14 -11
  98. package/src/lib/windows-owner-acl.ts +13 -6
  99. package/src/link/remote-platform.ts +14 -0
  100. package/src/link/remote-windows.ts +51 -9
  101. package/src/link/ssh-argv.ts +63 -10
  102. package/src/oauth/generic-account-failover.ts +13 -11
  103. package/src/oauth/index.ts +36 -74
  104. package/src/oauth/oauth-errors.ts +67 -0
  105. package/src/oauth/store.ts +1 -1
  106. package/src/protocols/codecs/ollama.ts +197 -0
  107. package/src/protocols/encoders/adapter-events.ts +4 -0
  108. package/src/protocols/encoders/chat.ts +18 -10
  109. package/src/protocols/trace.ts +18 -0
  110. package/src/providers/fastwire.ts +3 -2
  111. package/src/providers/quota/anthropic-usage-windows.ts +13 -3
  112. package/src/providers/quota/vendor-probes-key.ts +60 -24
  113. package/src/providers/request-pacing.ts +3 -2
  114. package/src/responses/apply-patch-envelope.ts +45 -19
  115. package/src/responses/compaction-history-framing.ts +5 -1
  116. package/src/responses/freeform-wrapper-scan.ts +5 -3
  117. package/src/responses/progressive-freeform-input.ts +354 -45
  118. package/src/routing/fallback-policy.ts +3 -1
  119. package/src/server/admission-model-scope.ts +17 -6
  120. package/src/server/admitted-http-turn.ts +56 -0
  121. package/src/server/auth-cors.ts +5 -0
  122. package/src/server/chat-completions.ts +45 -20
  123. package/src/server/chat-native-sse.ts +52 -7
  124. package/src/server/chat-native.ts +60 -35
  125. package/src/server/claude-bridge-pool-session.ts +59 -0
  126. package/src/server/claude-messages.ts +51 -24
  127. package/src/server/context-history.ts +5 -1
  128. package/src/server/inbound-body-admission.ts +11 -4
  129. package/src/server/index/ollama-routes.ts +89 -0
  130. package/src/server/index/serve-options.ts +21 -4
  131. package/src/server/index/websocket-handler.ts +4 -2
  132. package/src/server/index.ts +6 -36
  133. package/src/server/inference/client-encoder-delivery.ts +4 -2
  134. package/src/server/json-serialized-bytes.ts +44 -0
  135. package/src/server/management/agent-settings-routes.ts +24 -21
  136. package/src/server/management/codex-cli-update-routes.ts +2 -1
  137. package/src/server/management/route-registry.ts +1 -1
  138. package/src/server/messages-native-scope.ts +2 -1
  139. package/src/server/messages-native-tool-guard.ts +1 -1
  140. package/src/server/messages-native.ts +12 -7
  141. package/src/server/messages-shared.ts +6 -2
  142. package/src/server/native-final-log.ts +93 -0
  143. package/src/server/ollama-inbound.ts +349 -0
  144. package/src/server/ollama-native-paths.ts +21 -0
  145. package/src/server/ollama-route-policy.ts +73 -0
  146. package/src/server/relay.ts +22 -3
  147. package/src/server/request-decompress.ts +4 -2
  148. package/src/server/request-log-failure-attribution.ts +22 -0
  149. package/src/server/request-log-failure-detail.ts +80 -0
  150. package/src/server/request-log-terminal-status.ts +4 -2
  151. package/src/server/request-log.ts +79 -42
  152. package/src/server/response-log-body.ts +6 -1
  153. package/src/server/responses/account-change-state.ts +17 -6
  154. package/src/server/responses/adapter-continuation.ts +9 -4
  155. package/src/server/responses/adapter-delivery.ts +5 -4
  156. package/src/server/responses/adapter-dispatch.ts +31 -30
  157. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  158. package/src/server/responses/codex-auth-error.ts +19 -18
  159. package/src/server/responses/codex-ws-exchange.ts +11 -8
  160. package/src/server/responses/codex-ws-metadata.ts +94 -21
  161. package/src/server/responses/codex-ws-request.ts +3 -1
  162. package/src/server/responses/compact.ts +53 -23
  163. package/src/server/responses/compaction-recovery.ts +4 -2
  164. package/src/server/responses/compaction-routing.ts +9 -4
  165. package/src/server/responses/core-auth.ts +32 -14
  166. package/src/server/responses/core-codex-account.ts +17 -6
  167. package/src/server/responses/core-combo-failure.ts +5 -1
  168. package/src/server/responses/core-combo-native.ts +2 -1
  169. package/src/server/responses/core-combo.ts +41 -27
  170. package/src/server/responses/core-errors.ts +22 -20
  171. package/src/server/responses/core-lifetime.ts +6 -3
  172. package/src/server/responses/core-normalize.ts +1 -0
  173. package/src/server/responses/core-options.ts +7 -0
  174. package/src/server/responses/core-pipeline.ts +4 -3
  175. package/src/server/responses/fetch-helpers.ts +7 -1
  176. package/src/server/responses/input-admission.ts +28 -2
  177. package/src/server/responses/native-injection.ts +1 -1
  178. package/src/server/responses/native-response-json.ts +13 -4
  179. package/src/server/responses/native-response-output.ts +1 -2
  180. package/src/server/responses/non-replayable-error.ts +2 -1
  181. package/src/server/responses/pacing-overload.ts +3 -2
  182. package/src/server/responses/passthrough-delivery.ts +55 -14
  183. package/src/server/responses/passthrough-dispatch.ts +19 -17
  184. package/src/server/responses/passthrough-error.ts +9 -9
  185. package/src/server/responses/policy-fallback.ts +2 -1
  186. package/src/server/responses/request-prepare.ts +67 -48
  187. package/src/server/responses/request-transport.ts +35 -31
  188. package/src/server/responses/run-turn-execution.ts +6 -6
  189. package/src/server/responses/sidecar-execution.ts +16 -12
  190. package/src/server/responses/spend-storage-error.ts +2 -1
  191. package/src/server/responses/ws-upstream.ts +9 -0
  192. package/src/server/responses-custom-tool-repair.ts +14 -3
  193. package/src/server/responses-terminal-repair.ts +5 -2
  194. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  195. package/src/server/safe-response-headers.ts +162 -13
  196. package/src/server/turn-state-handles.ts +164 -0
  197. package/src/server/workflow-refusal.ts +2 -1
  198. package/src/service/ownership-mutation-lease.d.mts +11 -2
  199. package/src/service/ownership-mutation-lease.mjs +53 -11
  200. package/src/types/config.ts +2 -0
  201. package/src/update/index.ts +133 -25
  202. package/src/update/npm-install.d.mts +8 -0
  203. package/src/update/npm-install.mjs +20 -1
  204. package/src/update/orchestrated-admission.d.mts +4 -0
  205. package/src/update/orchestrated-admission.mjs +12 -0
  206. package/src/update/orchestrated-arguments.d.mts +12 -0
  207. package/src/update/orchestrated-arguments.mjs +64 -0
  208. package/src/update/orchestrated-child.d.mts +12 -0
  209. package/src/update/orchestrated-child.mjs +70 -0
  210. package/src/update/orchestrated-entry.ts +234 -0
  211. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  212. package/src/update/orchestrated-identity.ts +53 -0
  213. package/src/update/orchestrated-live-identity.ts +48 -0
  214. package/src/update/orchestrated-node-driver.mjs +99 -0
  215. package/src/update/orchestrated-outcome.d.mts +21 -0
  216. package/src/update/orchestrated-outcome.mjs +40 -0
  217. package/src/update/orchestrated-plan.ts +49 -0
  218. package/src/update/orchestrated-pnpm.d.mts +8 -0
  219. package/src/update/orchestrated-pnpm.mjs +33 -0
  220. package/src/update/orchestrated-session.d.mts +37 -0
  221. package/src/update/orchestrated-session.mjs +264 -0
  222. package/src/update/orchestrated-token.d.mts +10 -0
  223. package/src/update/orchestrated-token.mjs +21 -0
  224. package/src/update/orchestrated-token.ts +3 -0
  225. package/src/update/orchestrated-tree.d.mts +1 -0
  226. package/src/update/orchestrated-tree.mjs +14 -0
  227. package/src/update/pnpm-global-install.d.mts +6 -0
  228. package/src/update/pnpm-global-install.mjs +9 -2
  229. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  230. package/src/update/posix-install-supervisor.d.mts +10 -0
  231. package/src/update/posix-install-supervisor.mjs +88 -0
  232. package/src/update/sync-update-mutex.d.mts +10 -0
  233. package/src/update/sync-update-mutex.mjs +164 -0
  234. package/src/update/sync-update-mutex.ts +1 -0
  235. package/src/update/test-home-guard.mjs +33 -0
  236. package/src/update/transactional-install.mjs +2 -2
  237. package/src/usage/error-detail.ts +225 -0
  238. package/src/usage/log.ts +60 -27
  239. package/src/web-search/loop.ts +31 -5
  240. package/gui/dist/assets/index-ebuVUtB7.js +0 -94
@@ -1,3 +1,8 @@
1
+ import { projectLocalModelRefusalLog } from "../request-log-failure-detail";
2
+ import { inputAdmissionRefusalMessage } from "./input-admission";
3
+ import { clientFacingModelLabel, clientFacingModelText } from "../../lib/error-destination";
4
+ import { markProxyError } from "../../lib/client-error-body";
5
+ import { completeClaudeBridgePoolIdentity } from "../claude-bridge-pool-session";
1
6
  import type { HandleResponsesOptions, ResponsesRequestContext, ResponsesAdmissionState, ResponsesDispatchers } from "./core-options";
2
7
  import type { PolicyRequestEvidence } from "../../routing/evaluator";
3
8
  import type { RequestLogContext } from "../request-log";
@@ -53,6 +58,7 @@ import {
53
58
  } from "./encrypted-payload";
54
59
  import {
55
60
  codexPoolAffinityKey,
61
+ codexRequestAffinityKey,
56
62
  previewCodexPoolLineage,
57
63
  applyCodexAuthContextToProvider,
58
64
  releaseCodexAuthContextProbeLease,
@@ -140,7 +146,7 @@ import {
140
146
  import { checkComboTargetInputAdmission, checkInputAdmission } from "./input-admission";
141
147
  import {
142
148
  admissionMayUseMeteredComboTargets,
143
- admissionModelDeniedResponse,
149
+ admissionModelDeniedResponse, projectAdmissionModelDeniedLog,
144
150
  AdmissionModelDeniedError,
145
151
  assertRouteAllowedByScope,
146
152
  resolveAdmissionModelScope,
@@ -152,6 +158,7 @@ import {
152
158
  currentTurnWireToolCatalogBody,
153
159
  hasExplicitEmptyToolCatalog,
154
160
  collectDeclaredWireToolNames,
161
+ collectTranslatedHostedToolNames,
155
162
  collectDeclaredBareCustomWireToolNames,
156
163
  } from "../responses-undeclared-tool-guard";
157
164
  import { streamingContextOverflowResponse } from "./context-overflow";
@@ -242,6 +249,11 @@ export async function prepareResponsesRequest(
242
249
  return decodeRequestErrorResponse(err, "responses");
243
250
  }
244
251
  // Remove display-only artifact paths before helpers, combo dispatch and upstream replay.
252
+ const originalSelector = options.mainHardLockFallbackOverride?.sourceModel ?? options.compactionRoutingOverride?.sourceModel
253
+ ?? (options.comboAttempt || options.policyFallbackCandidate || options.internalDecisionCall || options.memoryModelPhase
254
+ || options.visionDescribeTerminal || options.shadowCallIntercepted ? undefined
255
+ : body && typeof body === "object" ? (body as { model?: unknown }).model : undefined);
256
+ options.clientModelLabel ??= clientFacingModelLabel(originalSelector);
245
257
  redactHostedImageDisplayPaths(body);
246
258
  observeCacheDiagnosticInbound(
247
259
  logCtx,
@@ -386,7 +398,7 @@ export async function prepareResponsesRequest(
386
398
  // A decision model may be a plain model or a non-JEV combo. A JEV combo here would recurse
387
399
  // into another decision, so the call is refused and the parent decision fails open.
388
400
  if (options.internalDecisionCall && comboId && config.combos?.[comboId]?.strategy === "jev") {
389
- return formatErrorResponse(400, "invalid_request_error", "A JEV decision model cannot be a JEV combo");
401
+ return markProxyError(formatErrorResponse(400, "invalid_request_error", "A JEV decision model cannot be a JEV combo"));
390
402
  }
391
403
  if (comboId && Object.hasOwn(config.combos ?? {}, comboId)) {
392
404
  options.onRequestBodyRead?.();
@@ -427,11 +439,11 @@ export async function prepareResponsesRequest(
427
439
  }
428
440
  // Local replay failures require full client replay.
429
441
  if (replayFailure) {
430
- return formatErrorResponse(
442
+ return markProxyError(formatErrorResponse(
431
443
  400,
432
444
  "previous_response_not_found",
433
445
  "Continuation state is unavailable or corrupt; resend the full conversation without previous_response_id.",
434
- );
446
+ ));
435
447
  }
436
448
  }
437
449
  const previousResponseInputExpanded = options.comboReplaySnapshot?.previousResponseInputExpanded
@@ -482,17 +494,22 @@ export async function prepareResponsesRequest(
482
494
  if (options.directRequest) parsed = options.directRequest.decode(parsed);
483
495
  parsed._nativeReasoningRetention = resolveNativeReasoningRetention(config);
484
496
  // Capture before route rewrites or hosted sidecars can add tools; replayed catalogs are history.
485
- // The direct settings body omits tools, including current legacy Chat functions. Recover
486
- // their wire names only when this restriction needs a non-empty decoded catalog.
487
- const catalogBody = options.directRequest && options.clientDeclaredEmptyToolCatalog === true && parsed.context.tools?.length
488
- ? options.directRequest.bridgeConversation() : parsed._rawBody;
497
+ // Direct decoders already own current function names (including legacy Chat functions).
498
+ // Project only those names; bridging the conversation would retain its reasoning twice.
499
+ const catalogBody = options.directRequest && parsed.context.tools?.length
500
+ ? { tools: parsed.context.tools.map(tool => ({ type: "function", name: tool.name })) } : parsed._rawBody;
489
501
  const currentCatalog = currentTurnWireToolCatalogBody(catalogBody, parsed._replayPrefixLen);
490
- if (options.clientDeclaredEmptyToolCatalog === true || hasExplicitEmptyToolCatalog(currentCatalog)) {
491
- clientToolCatalogRestriction = {
492
- declaredToolNames: collectDeclaredWireToolNames(currentCatalog),
493
- bareCustomToolNames: collectDeclaredBareCustomWireToolNames(currentCatalog),
494
- };
495
- }
502
+ // A hosted tool declared this turn authorizes the function name its translation uses.
503
+ const translatedHostedNames = collectTranslatedHostedToolNames(currentCatalog);
504
+ clientToolCatalogRestriction = {
505
+ declaredToolNames: new Set([...collectDeclaredWireToolNames(currentCatalog), ...translatedHostedNames]),
506
+ bareCustomToolNames: collectDeclaredBareCustomWireToolNames(currentCatalog),
507
+ canonicalToolNames: new Set([...collectDeclaredWireToolNames(currentCatalog, { canonicalOnly: true }), ...translatedHostedNames]),
508
+ // Ordinary Responses validation stays with its delivery owner; replay cannot add authority.
509
+ enforceDeclaredToolNames: (inboundWire === "responses" && (parsed._replayPrefixLen ?? 0) > 0)
510
+ || options.clientDeclaredEmptyToolCatalog === true
511
+ || hasExplicitEmptyToolCatalog(currentCatalog),
512
+ };
496
513
  if (options.inboundWire === "anthropic") {
497
514
  parsed._nativeReasoningReplay = options.nativeReasoningReplay;
498
515
  parsed._nativeReasoningMint = options.nativeReasoningMint;
@@ -568,9 +585,9 @@ export async function prepareResponsesRequest(
568
585
  }
569
586
  } catch (err) {
570
587
  if (isTranslatorBudgetExceededError(err)) {
571
- return formatErrorResponse(413, "request_too_large", "request translation buffer exceeded the safe limit", {
588
+ return markProxyError(formatErrorResponse(413, "request_too_large", "request translation buffer exceeded the safe limit", {
572
589
  code: "translation_buffer_limit",
573
- });
590
+ }));
574
591
  }
575
592
  return formatErrorResponse(400, "invalid_request_error", err instanceof Error ? err.message : String(err));
576
593
  }
@@ -646,7 +663,8 @@ export async function prepareResponsesRequest(
646
663
  // The selector the caller actually sent, captured before shadow interception
647
664
  // or a subagent fallback rewrites it, so a refusal names the client's own
648
665
  // request rather than a destination it never asked for.
649
- const inboundSelector = options.mainHardLockFallbackOverride?.sourceModel ?? parsed.modelId;
666
+ const inboundSelector = options.clientModelLabel;
667
+ const inboundRoutingSelector = options.mainHardLockFallbackOverride?.sourceModel ?? parsed.modelId;
650
668
  const selectorTargetsSecondary = (selector: string): boolean => {
651
669
  const slash = selector.indexOf("/");
652
670
  if (slash <= 0) return false;
@@ -656,13 +674,13 @@ export async function prepareResponsesRequest(
656
674
  return qualifier === "anthropic2"
657
675
  || config.providers.anthropic2?.alias?.trim().toLowerCase() === qualifier.toLowerCase();
658
676
  };
659
- const explicitlyRequestsSecondary = selectorTargetsSecondary(inboundSelector);
677
+ const explicitlyRequestsSecondary = selectorTargetsSecondary(inboundRoutingSelector);
660
678
  const secondaryProvider = config.providers.anthropic2;
661
679
  // Reserve an explicit B selector before an absent row can default-route it to A.
662
680
  // Combo parents have already dispatched above; concrete children retain their own target.
663
681
  if (explicitlyRequestsSecondary && (!secondaryProvider || secondaryProvider.disabled === true
664
682
  || secondaryProvider.authMode === "oauth" && configuredAnthropicInstance(config, "anthropic2") !== "anthropic2")) {
665
- return formatErrorResponse(401, "authentication_error", "Anthropic Pool 2 requires an enabled configured provider");
683
+ return markProxyError(formatErrorResponse(401, "authentication_error", "Anthropic Pool 2 requires an enabled configured provider"));
666
684
  }
667
685
  const admissionScope = options.admissionScope ?? resolveAdmissionModelScope(config, options.admission);
668
686
  const advisorAdmissionPolicy = options.advisorAdmissionPolicy;
@@ -839,11 +857,11 @@ export async function prepareResponsesRequest(
839
857
  logCtx.policyEligibility = route.policyEligibility;
840
858
  } catch (err) {
841
859
  if (err instanceof AnthropicSecondaryInstanceUnavailableError) {
842
- return formatErrorResponse(401, "authentication_error", err.message);
860
+ return markProxyError(formatErrorResponse(401, "authentication_error", err.message));
843
861
  }
844
862
  const policyRefusal = policyCandidateRefusalResponse(err);
845
863
  if (policyRefusal) return policyRefusal;
846
- if (err instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(err);
864
+ if (err instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(err, logCtx));
847
865
  if (err instanceof NoAvailableComboTargetsError) {
848
866
  return comboUnavailable(err.comboId, undefined, err.reasons);
849
867
  }
@@ -951,17 +969,17 @@ export async function prepareResponsesRequest(
951
969
  let subagentFallbackModelEligibleAccountIdsForModel: SubagentModelEligibleAccountIds | undefined;
952
970
  let subagentQuotaFailureModel = parsed.modelId;
953
971
  const parentThreadId = req.headers.get("x-codex-parent-thread-id")?.trim() ?? null;
954
- const poolAffinityKey = codexPoolAffinityKey(req.headers) ?? null;
972
+ const poolAffinityKey = codexPoolAffinityKey(completeClaudeBridgePoolIdentity(req.headers, options)) ?? null;
955
973
  // Preview has to see the same lineage resolve does. Without it, a child's first turn is
956
974
  // previewed as a cold pick and resolved onto the family account, and the subagent fallback
957
975
  // then decides model eligibility against an account the request will never use.
958
976
  //
959
977
  // "The same" means both halves of the question the final resolution asks. The Authorization
960
978
  // it will be given, because the lineage scope is an HMAC of exactly that header; and its own
961
- // Pool-state predicate, because a fixed account selector and a request-owned credential
962
- // deliberately create no affinity at all -- previewing a family binding for one of those would
963
- // hand model fallback an account this request can never authenticate as. Read-only: the record
964
- // is written by the resolution that binds, never by a preview that may own no Pool state.
979
+ // Pool-state predicate: fixed selectors and request-owned credentials never use stored-credential
980
+ // lineage. An opt-in request-owned key has its own namespace; previewing a stored family binding
981
+ // would hand model fallback an account this request will not use. Preview is read-only: only
982
+ // eligible stored-credential resolutions record lineage.
965
983
  const poolLineage = previewCodexPoolLineage(previewAuthHeaders, options.codexAuthPolicy ?? config, {
966
984
  accountId: route.codexAccountId,
967
985
  modelId: route.modelId,
@@ -1000,7 +1018,7 @@ export async function prepareResponsesRequest(
1000
1018
  });
1001
1019
  const fallbackNow = Date.now();
1002
1020
  subagentFallbackAccountPreview = (modelId, previewNow, modelEligibleAccountIds) => previewCodexAccountForRequest(
1003
- poolAffinityKey,
1021
+ codexRequestAffinityKey(previewAuthHeaders, config, options.codexAuthPolicy ?? config, { accountId: route.codexAccountId, modelId, admission: options.admission, requestScopedMainCredential: previewRequestScopedMainCredential }) ?? null,
1004
1022
  config,
1005
1023
  previewNow,
1006
1024
  codexQuotaScopeForModel(modelId),
@@ -1063,7 +1081,7 @@ export async function prepareResponsesRequest(
1063
1081
  } catch (err) {
1064
1082
  const policyRefusal = policyCandidateRefusalResponse(err);
1065
1083
  if (policyRefusal) return policyRefusal;
1066
- if (err instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(err);
1084
+ if (err instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(err, logCtx));
1067
1085
  if (err instanceof NoAvailableComboTargetsError) {
1068
1086
  return comboUnavailable(err.comboId, undefined, err.reasons);
1069
1087
  }
@@ -1218,7 +1236,7 @@ export async function prepareResponsesRequest(
1218
1236
  // and then fail closed at final auth — the same class of stale-selection bug as
1219
1237
  // the quota scope, one layer over.
1220
1238
  subagentFallbackAccountPreview = (modelId, previewNow, modelEligibleAccountIds) => previewCodexAccountForRequest(
1221
- poolAffinityKey,
1239
+ codexRequestAffinityKey(recoveryAuthHeaders, config, options.codexAuthPolicy ?? config, { accountId: route.codexAccountId, modelId, admission: options.admission, requestScopedMainCredential: recoveryRequestScopedMainCredential }) ?? null,
1222
1240
  config,
1223
1241
  previewNow,
1224
1242
  codexQuotaScopeForModel(modelId),
@@ -1238,7 +1256,7 @@ export async function prepareResponsesRequest(
1238
1256
  }),
1239
1257
  },
1240
1258
  modelId,
1241
- poolLineage,
1259
+ previewCodexPoolLineage(recoveryAuthHeaders, options.codexAuthPolicy ?? config, { accountId: route.codexAccountId, modelId, admission: options.admission, requestScopedMainCredential: recoveryRequestScopedMainCredential }),
1242
1260
  );
1243
1261
  const recoveryPreviewAccountId = subagentFallbackAccountPreview(
1244
1262
  parsed.modelId,
@@ -1285,7 +1303,7 @@ export async function prepareResponsesRequest(
1285
1303
  } catch (err) {
1286
1304
  const policyRefusal = policyCandidateRefusalResponse(err);
1287
1305
  if (policyRefusal) return policyRefusal;
1288
- if (err instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(err);
1306
+ if (err instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(err, logCtx));
1289
1307
  if (err instanceof NoAvailableComboTargetsError) {
1290
1308
  return comboUnavailable(err.comboId, undefined, err.reasons);
1291
1309
  }
@@ -1385,11 +1403,11 @@ export async function prepareResponsesRequest(
1385
1403
  hasUnexpandedPreviousResponse
1386
1404
  && isCanonicalOpenAiForwardProvider(route.provider)
1387
1405
  ) {
1388
- return formatErrorResponse(
1406
+ return markProxyError(formatErrorResponse(
1389
1407
  400,
1390
1408
  "previous_response_not_found",
1391
1409
  "Continuation state is unavailable or corrupt; resend the full conversation without previous_response_id.",
1392
- );
1410
+ ));
1393
1411
  }
1394
1412
 
1395
1413
  if (hasUnexpandedPreviousResponse) {
@@ -1411,11 +1429,11 @@ export async function prepareResponsesRequest(
1411
1429
  // An unknown adapter is left to the resolution error it already raises below.
1412
1430
  : continuationWire === undefined || PROVIDER_OWNED_CONTINUATION_WIRES.has(continuationWire);
1413
1431
  if (!upstreamOwnsOmittedHistory) {
1414
- return formatErrorResponse(
1432
+ return markProxyError(formatErrorResponse(
1415
1433
  400,
1416
1434
  "previous_response_not_found",
1417
1435
  "Continuation state is unavailable or corrupt; resend the full conversation without previous_response_id.",
1418
- );
1436
+ ));
1419
1437
  }
1420
1438
  }
1421
1439
 
@@ -1453,8 +1471,14 @@ export async function prepareResponsesRequest(
1453
1471
  const scopedDestination = parsed._wireModelOverride === undefined
1454
1472
  ? route
1455
1473
  : { providerName: route.providerName, modelId: parsed._wireModelOverride };
1474
+ // Synthetic turns keep the original client envelope label across provider normalization.
1475
+ if (options.compactionRoutingOverride || options.mainHardLockFallbackOverride || options.clientResponseModelLabel
1476
+ || options.internalDecisionCall || options.memoryModelPhase || options.visionDescribeTerminal
1477
+ || options.policyFallbackCandidate || parsed._memoryModelPhase || logCtx.shadowCallRewrittenFrom) {
1478
+ parsed._responseModelId = clientFacingModelText(options.clientResponseModelLabel ?? inboundSelector);
1479
+ }
1456
1480
  if (!routeAllowedByScope(admissionScope, scopedDestination)) {
1457
- return admissionModelDeniedResponse(new AdmissionModelDeniedError(inboundSelector, scopedDestination));
1481
+ return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(new AdmissionModelDeniedError(inboundSelector, scopedDestination), logCtx));
1458
1482
  }
1459
1483
  // Attribute local auth/cooldown failures to the public selector too; exact auth may fail before
1460
1484
  // the normal post-resolution provider label is assigned.
@@ -1467,7 +1491,7 @@ export async function prepareResponsesRequest(
1467
1491
  if (isCanonicalOpenAiForwardProvider(route.provider)
1468
1492
  && isCodexReserveHelperUnsupported(options.codexAuthPolicy ?? config, route.modelId,
1469
1493
  options.admission, options.visionDescribeTerminal === true)) {
1470
- return formatErrorResponse(400, "invalid_request_error", CODEX_RESERVE_HELPER_UNSUPPORTED_MESSAGE);
1494
+ return markProxyError(formatErrorResponse(400, "invalid_request_error", CODEX_RESERVE_HELPER_UNSUPPORTED_MESSAGE));
1471
1495
  }
1472
1496
  // #4940: the opt-in is off, so every Reserve affordance in this process is inert -- no catalog
1473
1497
  // row, no main-credential substitution, no authorization handshake, and no `luna-reserve` header
@@ -1488,7 +1512,7 @@ export async function prepareResponsesRequest(
1488
1512
  && options.visionDescribeTerminal !== true
1489
1513
  && isCanonicalOpenAiForwardProvider(route.provider)
1490
1514
  && isCodexReserveOptInMissing(options.codexAuthPolicy ?? config, route.modelId, options.admission)) {
1491
- return formatErrorResponse(400, "invalid_request_error", CODEX_RESERVE_OPT_IN_REQUIRED_MESSAGE);
1515
+ return markProxyError(formatErrorResponse(400, "invalid_request_error", CODEX_RESERVE_OPT_IN_REQUIRED_MESSAGE));
1492
1516
  }
1493
1517
  // Refuse an input that cannot plausibly fit the model context window before spending auth,
1494
1518
  // circuit budget, or upstream bandwidth on a turn the provider will reject anyway (#1412).
@@ -1509,23 +1533,18 @@ export async function prepareResponsesRequest(
1509
1533
  // instead of treating the first incompatible candidate as the end of the chain. The
1510
1534
  // distinct code is what lets the fallback layer tell the two apart -- an upstream
1511
1535
  // `context_length_exceeded` still stops, because retrying it elsewhere is guesswork.
1536
+ projectLocalModelRefusalLog(logCtx, inboundSelector);
1512
1537
  if (clientRequestedStream && !options.comboAttempt) {
1513
1538
  return streamingContextOverflowResponse(
1514
- parsed._responseModelId ?? parsed.modelId,
1539
+ clientFacingModelText(inboundSelector),
1515
1540
  translatorBudget,
1516
1541
  );
1517
1542
  }
1518
- return formatErrorResponse(
1543
+ return markProxyError(formatErrorResponse(
1519
1544
  413,
1520
1545
  "input_admission_refused",
1521
- inputAdmission.requiredOutputHeadroom !== undefined
1522
- ? `Estimated input (~${inputAdmission.estimatedTokens} tokens) plus ${inputAdmission.requiredOutputHeadroom} `
1523
- + `tokens of requested output headroom cannot fit the context window of ${parsed.modelId} `
1524
- + `(${inputAdmission.ceiling} tokens).`
1525
- : `Estimated input (~${inputAdmission.estimatedTokens} tokens) is far past the context window `
1526
- + `of ${parsed.modelId} (${inputAdmission.ceiling} tokens). Start a new session or choose a `
1527
- + `model with a larger context window.`,
1528
- );
1546
+ inputAdmissionRefusalMessage(inputAdmission, inboundSelector),
1547
+ ));
1529
1548
  }
1530
1549
  }
1531
1550
  const preAuthHostKey = preAuthUpstreamHostCircuitKey(route, config);
@@ -1,4 +1,7 @@
1
- import { SendBudgetExhaustedError } from "../../lib/upstream-retry";
1
+ import { projectLocalModelRefusalLog } from "../request-log-failure-detail";
2
+ import { markProxyError } from "../../lib/client-error-body";
3
+ import { formatClientRetryAfter } from "../../lib/client-retry-after";
4
+ import { SendBudgetExhaustedError, errorDestinationText, providerErrorDestinationLabel } from "../../lib/upstream-retry";
2
5
  import { appendLoadedToolDefinitions, appendOnlyToolLoadingMatches } from "../../claude/inbound-tool-loading";
3
6
  import { isRec } from "../../claude/inbound-records";
4
7
  import { isOpenCodeGoResponsesUrl } from "../../adapters/opencode-go-additional-tools";
@@ -67,7 +70,7 @@ import { captureRouteStaticPolicy } from "../../router";
67
70
  import { CopilotAutoHttpError, resolveCopilotAuto } from "../../providers/github-copilot-auto";
68
71
  import {
69
72
  AdmissionModelDeniedError,
70
- admissionModelDeniedResponse,
73
+ admissionModelDeniedResponse, projectAdmissionModelDeniedLog,
71
74
  assertRouteAllowedByScope,
72
75
  } from "../admission-model-scope";
73
76
  import { renameRoutedIdentityInContext } from "../../adapters/identity";
@@ -141,7 +144,7 @@ export async function prepareResponsesTransport(
141
144
  ? configuredAnthropicInstance(config, route.providerName) : undefined;
142
145
  // Refuse custom/orphan B OAuth before any generic resolver can observe its auth row.
143
146
  if (route.providerName === "anthropic2" && route.provider.authMode === "oauth" && !anthropicInstance) {
144
- return formatErrorResponse(401, "authentication_error", "Anthropic Pool 2 requires an enabled builtin OAuth provider");
147
+ return markProxyError(formatErrorResponse(401, "authentication_error", "Anthropic Pool 2 requires an enabled builtin OAuth provider"));
145
148
  }
146
149
  const anthropicRouting = anthropicInstance ? anthropicRoutingFor(anthropicInstance) : undefined;
147
150
  const anthropicQuota = anthropicInstance ? anthropicModelQuotaFor(anthropicInstance) : undefined;
@@ -158,7 +161,7 @@ export async function prepareResponsesTransport(
158
161
  } catch { return false; }
159
162
  };
160
163
  if (!anthropicAdmissionIsCurrent()) {
161
- return formatErrorResponse(401, "authentication_error", "Anthropic Pool 2 provider target changed; retry the request");
164
+ return markProxyError(formatErrorResponse(401, "authentication_error", "Anthropic Pool 2 provider target changed; retry the request"));
162
165
  }
163
166
  const requireAnthropicAdmission = (): void => {
164
167
  if (!anthropicAdmissionIsCurrent()) throw new OAuthLoginRequiredError(anthropicInstance!);
@@ -178,9 +181,9 @@ export async function prepareResponsesTransport(
178
181
  && (kiroCap !== undefined || (config.pool?.kernel === true
179
182
  && config.providers.kiro?.oauthAccountFailover?.strategy === "least-loaded"
180
183
  && isProactivePreferenceEnabled(config, "kiro", Date.now())));
181
- const capacityResponse = () => new Response(JSON.stringify({ error: {
184
+ const capacityResponse = () => markProxyError(new Response(JSON.stringify({ error: {
182
185
  type: "server_error", code: "account_capacity", message: "Kiro account capacity is temporarily full; retry shortly.",
183
- } }), { status: 503, headers: { "content-type": "application/json", "retry-after": "1" } });
186
+ } }), { status: 503, headers: { "content-type": "application/json", "retry-after": "1" } }));
184
187
 
185
188
 
186
189
  // OAuth providers: swap in a fresh access token (auto-refreshed) as the Bearer key, so the
@@ -344,11 +347,12 @@ export async function prepareResponsesTransport(
344
347
  const copilotRequestedModel = route.modelId;
345
348
  /** Project only bounded Copilot refusal metadata; upstream bodies and session tokens never reach the client. */
346
349
  const copilotRefusalResponse = (error: unknown): Response | undefined => {
347
- if (error instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(error);
350
+ if (error instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(error, logCtx));
348
351
  if (!(error instanceof CopilotAutoHttpError) || ![401, 403, 429].includes(error.status)) return;
349
- const response = formatErrorResponse(error.status, error.status === 429 ? "rate_limit_error" : "authentication_error",
350
- error.message);
351
- if (error.retryAfter) response.headers.set("retry-after", error.retryAfter);
352
+ const response = markProxyError(formatErrorResponse(error.status, error.status === 429 ? "rate_limit_error" : "authentication_error",
353
+ error.message));
354
+ const advice = formatClientRetryAfter(error.retryAfter);
355
+ if (advice !== undefined) response.headers.set("retry-after", advice);
352
356
  return response;
353
357
  };
354
358
  let copilotSessionExpiresAt = Infinity;
@@ -950,7 +954,7 @@ export async function prepareResponsesTransport(
950
954
  const bodySize = checkOutboundBodySize(rebuilt.body, config.maxUpstreamBodyBytes);
951
955
  if (!bodySize.admitted) {
952
956
  rebuilt.releaseBodyObservation?.();
953
- return formatErrorResponse(413, "outbound_body_too_large", describeOutboundBodyRefusal(bodySize));
957
+ return markProxyError(formatErrorResponse(413, "outbound_body_too_large", describeOutboundBodyRefusal(bodySize)));
954
958
  }
955
959
  const headers = new Headers(dispatchInit.headers);
956
960
  for (const name of Object.keys(wireRequest.headers)) headers.delete(name);
@@ -988,11 +992,11 @@ export async function prepareResponsesTransport(
988
992
  try {
989
993
  if (anthropicInstance !== undefined && anthropicRouting!.isAnthropicAccountPoolEnabled(config)) {
990
994
  const routeResult = resolveAnthropicModelRouteForInstance(anthropicInstance, config, route.modelId);
991
- if (routeResult.error) return formatErrorResponse(400, "invalid_request_error", `Invalid Anthropic model routes: ${routeResult.error}`);
995
+ if (routeResult.error) return markProxyError(formatErrorResponse(400, "invalid_request_error", `Invalid Anthropic model routes: ${routeResult.error}`));
992
996
  anthropicRouteDecision = routeResult.decision;
993
997
  const selection = anthropicRouting!.resolveAnthropicAccountForSession(anthropicSessionKey, config, Date.now(), anthropicRouteDecision, route.modelId);
994
998
  if (!selection.accountId) {
995
- if (selection.reason === "paused") return formatErrorResponse(403, "permission_error", "Anthropic OAuth accounts are paused. Resume an account in account settings and retry.");
999
+ if (selection.reason === "paused") return markProxyError(formatErrorResponse(403, "permission_error", "Anthropic OAuth accounts are paused. Resume an account in account settings and retry."));
996
1000
  // Route names may resemble account IDs; log only the matched rule position.
997
1001
  if (anthropicRouteDecision) console.warn(`[${anthropicInstance}-pool] route:#${anthropicRouteDecision.position} ${selection.reason}; answering locally`);
998
1002
  if (selection.reason === "all-cooled") {
@@ -1001,10 +1005,10 @@ export async function prepareResponsesTransport(
1001
1005
  { comboAttempt: options.comboAttempt, logCtx },
1002
1006
  );
1003
1007
  }
1004
- return formatErrorResponse(401, "authentication_error", anthropicRouteDecision ? "No eligible Anthropic OAuth account for this model route" : "No eligible Anthropic OAuth account available");
1008
+ return markProxyError(formatErrorResponse(401, "authentication_error", anthropicRouteDecision ? "No eligible Anthropic OAuth account for this model route" : "No eligible Anthropic OAuth account available"));
1005
1009
  }
1006
1010
  const admitted = await commitResolvedOAuthSelection(await anthropicRouting!.getAnthropicPoolAccessSnapshot(selection.accountId), true, selection.reason);
1007
- if (!admitted) return formatErrorResponse(409, "conflict_error", "OAuth account selection changed; retry the request");
1011
+ if (!admitted) return markProxyError(formatErrorResponse(409, "conflict_error", "OAuth account selection changed; retry the request"));
1008
1012
  anthropicPoolAccountId = admitted.accountId;
1009
1013
  if (anthropicRouteDecision) console.info(`[${anthropicInstance}-pool] route:#${anthropicRouteDecision.position} ${selection.reason}`);
1010
1014
  route.provider = { ...route.provider, apiKey: admitted.accessToken };
@@ -1025,8 +1029,8 @@ export async function prepareResponsesTransport(
1025
1029
  // #7500: an Antigravity account whose own discovery omits the model is never sent to.
1026
1030
  // A usable listing (or not-yet-discovered) sibling replaces it, or the request is refused.
1027
1031
  const modelRoute = routeAntigravityModel(config, route.providerName,
1028
- proposedAccountId ?? oauthSelection?.accountId, route.modelId);
1029
- if (modelRoute.kind === "refuse") return formatErrorResponse(403, "permission_error", modelRoute.message);
1032
+ proposedAccountId ?? oauthSelection?.accountId, route.modelId, undefined, requestState.inboundSelector);
1033
+ if (modelRoute.kind === "refuse") { projectLocalModelRefusalLog(logCtx, requestState.inboundSelector); return markProxyError(formatErrorResponse(403, "permission_error", modelRoute.message)); }
1030
1034
  const routedAccountId = modelRoute.kind === "reroute" ? modelRoute.accountId : proposedAccountId;
1031
1035
  // An unchanged active choice must retain the ordinary resolver's terminal-refresh
1032
1036
  // recovery (not the speculative-preference fallback that resolves the same dead grant).
@@ -1093,12 +1097,12 @@ export async function prepareResponsesTransport(
1093
1097
  }
1094
1098
  // Resolution fallbacks can still land on an omitting account; answer with the refusal
1095
1099
  // here, since the commit below would only report it as a changed selection.
1096
- const unlisted = antigravityModelRefusal(config, route.providerName, resolved.accountId, route.modelId);
1097
- if (unlisted) return formatErrorResponse(403, "permission_error", unlisted);
1100
+ const unlisted = antigravityModelRefusal(config, route.providerName, resolved.accountId, route.modelId, undefined, requestState.inboundSelector);
1101
+ if (unlisted) { projectLocalModelRefusalLog(logCtx, requestState.inboundSelector); return markProxyError(formatErrorResponse(403, "permission_error", unlisted)); }
1098
1102
  const admitted = await commitResolvedOAuthSelection(resolved, safetyAlternateId === null);
1099
- if (!admitted) return formatErrorResponse(409, "conflict_error", "OAuth account selection changed; retry the request");
1103
+ if (!admitted) return markProxyError(formatErrorResponse(409, "conflict_error", "OAuth account selection changed; retry the request"));
1100
1104
  if (safetyAlternateId && admitted.accountId !== safetyAlternateId)
1101
- return formatErrorResponse(409, "conflict_error", "OAuth account selection changed; retry the request");
1105
+ return markProxyError(formatErrorResponse(409, "conflict_error", "OAuth account selection changed; retry the request"));
1102
1106
  if (kiroLoadEnabled) {
1103
1107
  const transportSignal = options.abortSignal ?? req.signal;
1104
1108
  const lease = await acquireAccountLease("kiro", admitted.accountId, {
@@ -1165,27 +1169,27 @@ export async function prepareResponsesTransport(
1165
1169
  // Project identity belongs to the admitted account on EVERY request, including
1166
1170
  // the request after a pool transition made that account the persisted active one.
1167
1171
  if (route.provider.googleMode === "cloud-code-assist") {
1168
- if (!resolved.projectId) return formatErrorResponse(401, "authentication_error", publicOAuthAuthenticationErrorMessage(new Error("Cloud Code Assist account project is unavailable")));
1172
+ if (!resolved.projectId) return markProxyError(formatErrorResponse(401, "authentication_error", publicOAuthAuthenticationErrorMessage(new Error("Cloud Code Assist account project is unavailable"))));
1169
1173
  route.provider = { ...route.provider, project: resolved.projectId };
1170
1174
  }
1171
1175
  }
1172
1176
  } catch (err) {
1173
1177
  if (err instanceof UnsupportedOAuthProviderError) {
1174
- const safeProviderName = redactSecretString(route.providerName);
1175
- return formatErrorResponse(
1178
+ const safeProviderName = redactSecretString(errorDestinationText(providerErrorDestinationLabel(route.providerName)));
1179
+ return markProxyError(formatErrorResponse(
1176
1180
  400,
1177
1181
  "invalid_request_error",
1178
1182
  `${redactSecretString(err.message)}. Remove or reconfigure provider '${safeProviderName}' in the OpenCodex configuration.`,
1179
- );
1183
+ ));
1180
1184
  }
1181
1185
  if (err instanceof OAuthTokenRefreshBusyError) {
1182
1186
  return options.abortSignal?.aborted || req.signal.aborted ? clientCancelledResponse()
1183
- : formatErrorResponse(503, "server_error", err.message, { retryAfter: "1" });
1187
+ : markProxyError(formatErrorResponse(503, "server_error", err.message, { retryAfter: "1" }));
1184
1188
  }
1185
1189
  if (err instanceof OAuthAccountPausedError) {
1186
- return formatErrorResponse(403, "permission_error", publicOAuthAuthenticationErrorMessage(err));
1190
+ return markProxyError(formatErrorResponse(403, "permission_error", publicOAuthAuthenticationErrorMessage(err)));
1187
1191
  }
1188
- return formatErrorResponse(401, "authentication_error", publicOAuthAuthenticationErrorMessage(err));
1192
+ return markProxyError(formatErrorResponse(401, "authentication_error", publicOAuthAuthenticationErrorMessage(err)));
1189
1193
  }
1190
1194
  }
1191
1195
  // Key-auth twin of the OAuth preference above: pick a warm key BEFORE the first attempt when
@@ -1221,7 +1225,7 @@ export async function prepareResponsesTransport(
1221
1225
  if ((options.abortSignal ?? req.signal).aborted) return clientCancelledResponse();
1222
1226
  const refusal = copilotRefusalResponse(error);
1223
1227
  if (refusal) return refusal;
1224
- return formatErrorResponse(502, "provider_error", "GitHub Copilot Auto negotiation failed; retry or check your Copilot account permissions.");
1228
+ return markProxyError(formatErrorResponse(502, "provider_error", "GitHub Copilot Auto negotiation failed; retry or check your Copilot account permissions."));
1225
1229
  }
1226
1230
  let adapterProvider = resolveWireProtocolOverride(route.providerName, route.modelId, route.provider, inboundWire, route.staticPolicy);
1227
1231
  if (copilotAutoAdapter) adapterProvider = { ...adapterProvider, adapter: copilotAutoAdapter };
@@ -1294,11 +1298,11 @@ export async function prepareResponsesTransport(
1294
1298
  if (!isPassthrough && Array.isArray(rawInput) && rawInput.some(
1295
1299
  item => item !== null && typeof item === "object" && item.type === "computer_call_output",
1296
1300
  )) {
1297
- return formatErrorResponse(
1301
+ return markProxyError(formatErrorResponse(
1298
1302
  400,
1299
1303
  "invalid_request_error",
1300
1304
  "computer_call_output requires a Responses passthrough route; send screenshots as user input_image content on translated routes.",
1301
- );
1305
+ ));
1302
1306
  }
1303
1307
 
1304
1308
  // Freeze the request ceiling before any 429 writes cooldowns. Selection still reads
@@ -1,3 +1,4 @@
1
+ import { formatClientRetryAfter } from "../../lib/client-retry-after";
1
2
  import { mapSpendLedgerStorageError } from "./spend-storage-error";
2
3
  import type { ResponsesRequestContext, ResponsesAdmissionState } from "./core-options";
3
4
  import type { PreparedResponsesRequest } from "./request-prepare";
@@ -49,7 +50,7 @@ import { rememberResponseState } from "../../responses/state";
49
50
  import { trackStreamLifetime } from "../lifecycle";
50
51
  import { awaitThoughtSignatureDurability } from "../../responses/thought-signature-replay";
51
52
  import { undeclaredToolCallMessage } from "../responses-undeclared-tool-guard";
52
- import { emptyToolCatalogRefusal, guardEmptyToolCatalogEvents, guardEmptyToolCatalogStream } from "../../lib/empty-tool-catalog";
53
+ import { currentTurnToolBridgeMaps, emptyToolCatalogRefusal, guardEmptyToolCatalogEvents, guardEmptyToolCatalogStream } from "../../lib/empty-tool-catalog";
53
54
  // LOCAL PATCH (runturn-websearch)
54
55
  import { planWebSearch } from "../../web-search";
55
56
  import { runTurnWebSearchInitialParsed, runTurnWebSearchLoop } from "../../web-search/run-turn-loop";
@@ -196,7 +197,7 @@ export async function executeResponsesRunTurn(
196
197
  } }), {
197
198
  status: 429,
198
199
  headers: { "Content-Type": "application/json",
199
- ...(usage.resetAt ? { "Retry-After": String(Math.max(1, Math.ceil((usage.resetAt - Date.now()) / 1000))) } : {}),
200
+ ...(usage.resetAt ? { "Retry-After": formatClientRetryAfter(Math.max(1, Math.ceil((usage.resetAt - Date.now()) / 1000)))! } : {}),
200
201
  },
201
202
  });
202
203
  markResponseNonReplayable(refusal);
@@ -755,8 +756,7 @@ export async function executeResponsesRunTurn(
755
756
 
756
757
  const clientToolCatalog = requestState.clientToolCatalogRestriction && route.provider.authMode !== "forward"
757
758
  ? requestState.clientToolCatalogRestriction : undefined;
758
- const { toolNsMap, declaredToolNames, toolParameterSchemas, freeformToolNames, bareCustomToolNames, toolSearchToolNames } = clientToolCatalog
759
- ? { ...toolBridgeMaps, ...clientToolCatalog } : toolBridgeMaps;
759
+ const { toolNsMap, declaredToolNames, toolParameterSchemas, freeformToolNames, bareCustomToolNames, toolSearchToolNames } = currentTurnToolBridgeMaps(toolBridgeMaps, clientToolCatalog);
760
760
  const enforceDeclaredToolNames = inboundWire !== "chat" && inboundWire !== "anthropic";
761
761
  const classifyUndeclaredFirstTool = (
762
762
  event: AdapterEvent,
@@ -772,7 +772,7 @@ export async function executeResponsesRunTurn(
772
772
  type: "error",
773
773
  status: 502,
774
774
  errorType: "upstream_error",
775
- message: undeclaredToolCallMessage(effectiveName),
775
+ message: undeclaredToolCallMessage(),
776
776
  };
777
777
  };
778
778
  const grokDevinPreflight = !options.comboAttempt && logCtx.surface === "grok" && inboundWire === "responses"
@@ -896,7 +896,7 @@ export async function executeResponsesRunTurn(
896
896
  queue.close();
897
897
  }, 2_000,
898
898
  {
899
- translatorBudget,
899
+ translatorBudget, proxyErrorContext: logCtx,
900
900
  replayCacheScope: parsed._reasoningReplayScope,
901
901
  ...(options.forceEmptyResponseId ? { responseId: "" } : {}),
902
902
  stallTimeoutSec,