@bitkyc08/opencodex 2.98.0 → 2.99.0-preview.20261108

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 (109) hide show
  1. package/bin/ocx.mjs +6 -19
  2. package/gui/dist/assets/{App-6TFtZsUF.css → App-C1hGwaN1.css} +1 -1
  3. package/gui/dist/assets/App-CWz0areF.js +59 -0
  4. package/gui/dist/assets/Tray-BosDoskm.js +1 -0
  5. package/gui/dist/assets/{brand-mark-A03mw_9y.js → brand-mark-DpiBmFGI.js} +1 -1
  6. package/gui/dist/assets/{index-BjTIN4to.js → index-CAxjGWkm.js} +13 -13
  7. package/gui/dist/assets/index-bnUWypyz.css +2 -0
  8. package/gui/dist/assets/{segment-thumb-features-Bf6vpwf8.js → segment-thumb-features-JcszQ18T.js} +1 -1
  9. package/gui/dist/classic/assets/App-BOEsFmiN.js +58 -0
  10. package/gui/dist/classic/assets/Tray-5v86r9Az.js +1 -0
  11. package/gui/dist/classic/assets/{index-DFAFnven.js → index-ClZ_zZ77.js} +13 -13
  12. package/gui/dist/classic/assets/{quota-summary-C-4HP4_5.js → quota-summary-xwvDtvu7.js} +1 -1
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/package.json +1 -1
  16. package/src/adapters/coding-agent/protocol.ts +8 -3
  17. package/src/adapters/coding-agent/turn.ts +6 -2
  18. package/src/adapters/command-code.ts +8 -5
  19. package/src/adapters/devin.ts +11 -1
  20. package/src/adapters/kiro/stream.ts +5 -4
  21. package/src/adapters/openai-chat/destination-policy.ts +25 -0
  22. package/src/adapters/openai-chat/native-content.ts +32 -0
  23. package/src/adapters/openai-chat/passthrough.ts +14 -1
  24. package/src/adapters/openai-chat/reasoning-wire.ts +42 -1
  25. package/src/adapters/openai-chat.ts +2 -2
  26. package/src/adapters/qoder/adapter.ts +9 -0
  27. package/src/bridge/response-json.ts +13 -1
  28. package/src/bridge/sse.ts +112 -22
  29. package/src/cli/account-affinity-reset.ts +42 -0
  30. package/src/cli/account.ts +5 -0
  31. package/src/cli/capabilities-accounts.ts +8 -0
  32. package/src/cli/capabilities-agents-routing.ts +5 -4
  33. package/src/cli/message-command.ts +1 -1
  34. package/src/cli/message-mcp-command.ts +8 -5
  35. package/src/client/orphan-token-recovery.ts +1 -1
  36. package/src/codex/autostart-health.ts +4 -2
  37. package/src/generated/compatibility-version.json +128 -76
  38. package/src/lib/desktop-cli-handoff.mjs +5 -8
  39. package/src/lib/failure-detail.ts +5 -2
  40. package/src/lib/launcher-signal-forwarding.d.mts +8 -0
  41. package/src/lib/launcher-signal-forwarding.mjs +36 -0
  42. package/src/lib/privacy.ts +6 -0
  43. package/src/lib/request-execution-budget.ts +188 -33
  44. package/src/lib/upstream-validation-detail.ts +47 -0
  45. package/src/lib/workflow-budget.ts +35 -16
  46. package/src/messaging/mcp-queue-rpc.ts +7 -3
  47. package/src/messaging/mcp-queue-server.ts +6 -0
  48. package/src/messaging/mcp-reply-cursor.ts +34 -0
  49. package/src/messaging/mcp-reply-tools.ts +93 -0
  50. package/src/oauth/anthropic-routing.ts +46 -3
  51. package/src/oauth/anthropic-session-affinity-store.ts +23 -10
  52. package/src/protocols/codecs/ollama.ts +22 -12
  53. package/src/providers/registry/entries-extended.ts +14 -0
  54. package/src/remote/hub-usage.ts +7 -0
  55. package/src/responses/parser.ts +27 -0
  56. package/src/responses/reasoning-envelope.ts +4 -0
  57. package/src/responses/schema.ts +1 -0
  58. package/src/server/chat-completions.ts +3 -0
  59. package/src/server/chat-native-sse.ts +14 -10
  60. package/src/server/chat-native.ts +24 -11
  61. package/src/server/index/websocket-handler.ts +12 -1
  62. package/src/server/management/oauth-account-routes.ts +65 -13
  63. package/src/server/management/route-registry.ts +1 -0
  64. package/src/server/messages-native.ts +21 -5
  65. package/src/server/request-log-attempt-recovery.ts +17 -0
  66. package/src/server/request-log-failure-detail.ts +18 -1
  67. package/src/server/request-log.ts +5 -18
  68. package/src/server/responses/account-auto-pause-recovery.ts +29 -1
  69. package/src/server/responses/adapter-continuation.ts +12 -5
  70. package/src/server/responses/adapter-dispatch.ts +50 -51
  71. package/src/server/responses/antigravity-model-denial-recovery.ts +4 -2
  72. package/src/server/responses/codex-ws-exchange.ts +13 -4
  73. package/src/server/responses/combo-required-tool-contract.ts +22 -3
  74. package/src/server/responses/core-codex-account.ts +92 -86
  75. package/src/server/responses/core-combo-failure.ts +7 -0
  76. package/src/server/responses/core-combo.ts +11 -4
  77. package/src/server/responses/core-lifetime.ts +3 -0
  78. package/src/server/responses/deferred-send-reporter.ts +18 -1
  79. package/src/server/responses/fetch-helpers.ts +9 -3
  80. package/src/server/responses/native-continuation-refusal.ts +8 -0
  81. package/src/server/responses/native-continuation-send.ts +34 -0
  82. package/src/server/responses/passthrough-delivery.ts +6 -2
  83. package/src/server/responses/passthrough-dispatch.ts +48 -33
  84. package/src/server/responses/passthrough-execution.ts +1 -0
  85. package/src/server/responses/policy-fallback.ts +32 -5
  86. package/src/server/responses/policy-request-scope.ts +26 -0
  87. package/src/server/responses/request-prepare.ts +11 -2
  88. package/src/server/responses/request-send-budget.ts +96 -14
  89. package/src/server/responses/request-spend-target.ts +19 -0
  90. package/src/server/responses/request-spend.ts +80 -28
  91. package/src/server/responses/request-transport.ts +106 -53
  92. package/src/server/responses/run-turn-execution.ts +3 -0
  93. package/src/server/responses/sidecar-execution.ts +2 -1
  94. package/src/server/responses/ws-upstream.ts +2 -1
  95. package/src/server/workflow-refusal.ts +38 -4
  96. package/src/server/ws-bridge.ts +10 -3
  97. package/src/service/desktop-startup.ts +76 -13
  98. package/src/types/request.ts +2 -1
  99. package/src/usage/app-breakdown.ts +23 -0
  100. package/src/usage/summary.ts +34 -1
  101. package/src/web-search/anthropic-executor.ts +25 -9
  102. package/src/web-search/loop.ts +3 -1
  103. package/src/web-search/passthrough-bridge.ts +3 -0
  104. package/src/web-search/run-turn-loop.ts +3 -1
  105. package/gui/dist/assets/App-FQ0OtiMJ.js +0 -59
  106. package/gui/dist/assets/Tray-D2d5wqLq.js +0 -1
  107. package/gui/dist/assets/index-5REODpG3.css +0 -2
  108. package/gui/dist/classic/assets/App-C9Eg3nUo.js +0 -58
  109. package/gui/dist/classic/assets/Tray-B8P8cokE.js +0 -1
@@ -3,6 +3,8 @@ import { markProxyError } from "../../lib/client-error-body";
3
3
  import { CodexInstallationIdUnavailableError } from "../../codex/installation-id";
4
4
  import { passthroughBuildErrorResponse } from "./passthrough-build-error";
5
5
  import { recoverAutoPausedAccount, rotatePassthroughKeyOn429 } from "./passthrough-key-rotation";
6
+ import { createAutoPauseRefreshErrorMapper } from "./account-auto-pause-recovery";
7
+ import { physicalSendAccounting } from "./deferred-send-reporter";
6
8
  import { adoptCodexWsStage, capturePassthroughAffinity } from "./passthrough-observations";
7
9
  import { spendLedgerStorageErrorResponse } from "./spend-storage-error";
8
10
  import { requestPacingOverloadResponse } from "./pacing-overload";
@@ -19,8 +21,7 @@ import type {
19
21
  import type { PreparedResponsesRequest } from "./request-prepare";
20
22
  import { CopilotAutoAdapterHandoff, type ResponsesTransport } from "./request-transport";
21
23
  import type { ResponsesEffects } from "./response-effects";
22
- import type { ResponsesSendBudget } from "./request-send-budget";
23
- import { transientSendCapFor } from "./request-send-budget";
24
+ import { transientSendCapFor, type ResponsesSendBudget } from "./request-send-budget";
24
25
  import { renewMainQuotaDispatchForAttempt } from "../../codex/main-account-cache";
25
26
  import { isCanonicalOpenAiForwardProvider } from "../../providers/openai-tiers";
26
27
  import { isLocalUpstream } from "../../lib/local-upstream";
@@ -174,6 +175,7 @@ import { upstreamErrorMessageFromPayload, ENCRYPTED_FUNCTION_OUTPUT_REJECTION }
174
175
  import { isTransientConsoleGoUploadRejection } from "../../providers/opencode-zen-rate-limit";
175
176
  import { planReasoningEffortDowngrade } from "../../providers/reasoning-metadata";
176
177
  import { unboundPoolSpendRefusalResponse } from "../workflow-refusal";
178
+ import { createNativeContinuationDispatch } from "./native-continuation-send";
177
179
  import { guardPassthroughCompletion, parseOutboundRequestBody } from "./passthrough-completion";
178
180
 
179
181
  /** Transfer an uncommitted Copilot exchange to the existing translated pipeline without new admission. */
@@ -220,7 +222,7 @@ export async function preparePassthroughExchange(
220
222
  | "genericFailovers"
221
223
  | "genericFailoverLimit"
222
224
  | "applyFailoverSnapshot"
223
- | "noteRoutedAttemptSend"
225
+ | "noteRoutedAttemptSend" | "deferPhysicalAttribution"
224
226
  | "selectionIsCurrent"
225
227
  | "requestBindings"
226
228
  >,
@@ -238,6 +240,7 @@ export async function preparePassthroughExchange(
238
240
  | "remainingTransientSendBudget"
239
241
  | "noteTransientSends"
240
242
  | "transientSendReporter"
243
+ | "continuationSendReporter"
241
244
  | "recoverySendAllowance"
242
245
  | "recoveryClassFor"
243
246
  | "sendBudgetExhausted"
@@ -800,13 +803,16 @@ export async function preparePassthroughExchange(
800
803
  * row replaces an HTTP stream, which a WS create frame is not, and the WebSocket row replaces
801
804
  * the transport that just failed.
802
805
  */
806
+ const copilotSendAccounting = (permit?: Parameters<typeof transientSendReporter>[0]) => physicalSendAccounting(
807
+ transientSendReporter(permit), route.providerName === "github-copilot" && route.provider.authMode !== "forward"
808
+ ? { permit, destination: () => errorDestinationLabel(request.url) } : undefined);
803
809
  const sendAmbiguousReplacement = (
804
810
  signal: AbortSignal = upstream.signal,
805
811
  ): Promise<Response> => {
806
812
  if (admissionState.authCtx.kind === "main" && admissionState.authCtx.mainQuotaDispatch) {
807
813
  admissionState.authCtx.mainQuotaDispatch = renewMainQuotaDispatchForAttempt(admissionState.authCtx.mainQuotaDispatch);
808
814
  }
809
- const report = transientSendReporter();
815
+ const accounting = copilotSendAccounting(), report = accounting.report;
810
816
  let started = false;
811
817
  const run = () => fetchWithHeaderTimeout(
812
818
  request.url,
@@ -823,6 +829,7 @@ export async function preparePassthroughExchange(
823
829
  providerName: route.providerName,
824
830
  modelId: route.modelId,
825
831
  dispatchOverride: oauthDispatch(request, parsed, "passthrough"),
832
+ onPhysicalDispatch: accounting.onPhysicalDispatch ? () => { accounting.onPhysicalDispatch!(); started = true; } : undefined,
826
833
  beforeDispatch: headers => {
827
834
  if (signal.aborted) throw signal.reason;
828
835
  if (!transportState.selectionIsCurrent(transportState.requestBindings.get(request))) {
@@ -843,8 +850,10 @@ export async function preparePassthroughExchange(
843
850
  // Charged to the SAME request counter every other send goes through. The
844
851
  // replacement is bought here rather than by a nested retry helper, so there is
845
852
  // one charge for one send and no per-layer counter to reconcile.
846
- if (report.beforeSend?.() === false) throw new SendBudgetExhaustedError(errorDestinationLabel(request.url));
847
- started = true;
853
+ if (!accounting.onPhysicalDispatch) {
854
+ if (report.beforeSend?.() === false) throw new SendBudgetExhaustedError(errorDestinationLabel(request.url));
855
+ started = true;
856
+ }
848
857
  },
849
858
  }),
850
859
  route.provider.authMode === "forward",
@@ -993,9 +1002,11 @@ export async function preparePassthroughExchange(
993
1002
  // Stable per request: the Combo booking (`reserveDispatch`) already started and froze the spend
994
1003
  // policy, so `spendEnforced` cannot change before dispatch even though no reporter starts it here.
995
1004
  const receiptMode = !sendBudgetState.adapterSendBudget?.spendEnforced && Boolean(options.comboInitialSend);
1005
+ const initialAccounting = copilotSendAccounting();
996
1006
  // #6969: Pool sends hold empty lifecycle frames so a pre-output refusal reaches the ladder below.
997
1007
  const preOutputRefusals = new PoolPreOutputRefusals();
998
1008
  const preOutputRefusalHold = () => poolPreOutputRefusalHold(admissionState.authCtx, route.provider, connectMs, options.comboAttempt);
1009
+ const onContinuationDispatch = createNativeContinuationDispatch(sendBudgetState, logCtx);
999
1010
  try {
1000
1011
  // Transient-5xx pre-stream retry (devlog/_plan/260716_claudecode_hardening/010):
1001
1012
  // the ChatGPT backend emits transient 502/520s that an immediate retry absorbs.
@@ -1022,7 +1033,8 @@ export async function preparePassthroughExchange(
1022
1033
  dispatchOverride: oauthDispatch(request, parsed, "passthrough"),
1023
1034
  providerName: route.providerName,
1024
1035
  modelId: route.modelId,
1025
- onPhysicalDispatch: receiptMode ? sendBudgetState.noteInitialDispatch : undefined,
1036
+ onPhysicalDispatch: receiptMode ? sendBudgetState.noteInitialDispatch : initialAccounting.onPhysicalDispatch,
1037
+ onContinuationDispatch,
1026
1038
  accountAutoPause: (name, provider, headers) => captureAccountAutoPauseAttempt(name, provider, { config, codex: admissionState.authCtx }, headers),
1027
1039
  onCodexWsQuota: codexWsQuotaObserver(admissionState.authCtx, route.provider, route.modelId),
1028
1040
  beforeDispatch: isCanonicalOpenAiForwardProvider(route.provider)
@@ -1038,7 +1050,7 @@ export async function preparePassthroughExchange(
1038
1050
  attempts: sendBudgetState.initialSendAllowance(transientSendAttempts()),
1039
1051
  // Reporter path: direct requests and enforced spend. Receipt-mode sends are settled
1040
1052
  // by `onPhysicalDispatch`; a reporter as well would count them twice.
1041
- ...(receiptMode ? {} : { onSendsConsumed: transientSendReporter() }),
1053
+ ...(receiptMode ? {} : { onSendsConsumed: initialAccounting.report }),
1042
1054
  claimAmbiguousResend: claimPreHeaderResend,
1043
1055
  },
1044
1056
  );
@@ -1062,13 +1074,10 @@ export async function preparePassthroughExchange(
1062
1074
  adapterName: refreshedAdapter.name,
1063
1075
  oauthCredentialSnapshot: transportState.replayOAuthCredentialSnapshot,
1064
1076
  });
1065
- logCtx.providerAdapter = refreshedAdapter.name;
1066
- sealRequestAttemptIdentity(
1067
- logCtx.activeAttempt,
1068
- logCtx.provider,
1069
- refreshedAdapter.name,
1070
- logCtx.accountLogLabel,
1071
- );
1077
+ if (!transportState.deferPhysicalAttribution) {
1078
+ logCtx.providerAdapter = refreshedAdapter.name;
1079
+ sealRequestAttemptIdentity(logCtx.activeAttempt, logCtx.provider, refreshedAdapter.name, logCtx.accountLogLabel);
1080
+ }
1072
1081
  recordAttemptCredentialSource(logCtx.activeAttempt, route.providerName, route.provider, refreshedAdapter.name);
1073
1082
  }
1074
1083
  /** Transfer adapter ownership without retaining the native abort link or request cache. */
@@ -1120,13 +1129,10 @@ export async function preparePassthroughExchange(
1120
1129
  : undefined;
1121
1130
  if (passthroughEstimate !== undefined) logCtx.usageLogInputTokens = passthroughEstimate;
1122
1131
  refreshUndeclaredToolGuard(request);
1123
- logCtx.providerAdapter = retryAdapter.name;
1124
- sealRequestAttemptIdentity(
1125
- logCtx.activeAttempt,
1126
- logCtx.provider,
1127
- retryAdapter.name,
1128
- logCtx.accountLogLabel,
1129
- );
1132
+ if (!transportState.deferPhysicalAttribution) {
1133
+ logCtx.providerAdapter = retryAdapter.name;
1134
+ sealRequestAttemptIdentity(logCtx.activeAttempt, logCtx.provider, retryAdapter.name, logCtx.accountLogLabel);
1135
+ }
1130
1136
  recordAttemptCredentialSource(logCtx.activeAttempt, route.providerName, route.provider, retryAdapter.name);
1131
1137
  const rebuiltBodyRefusal = refuseOversizedOutboundBody(request);
1132
1138
  if (rebuiltBodyRefusal) return { failed: rebuiltBodyRefusal };
@@ -1141,12 +1147,13 @@ export async function preparePassthroughExchange(
1141
1147
  { allowFinalRecoveryReserve: transientSendPolicy() === null },
1142
1148
  );
1143
1149
  if (recovery === "empty-completion") allowance.attempts = Math.min(1, allowance.attempts);
1150
+ const recoveryAccounting = copilotSendAccounting(allowance.permit);
1144
1151
  try {
1145
1152
  return await fetchWithTransientRetry(
1146
1153
  innerRecovery => {
1147
1154
  // Gated on the return, not fire-and-forget: a consumed permit means this leg
1148
1155
  // already sent once, and letting the second call through would be a free send.
1149
- if (allowance.permit && !allowance.permit.use()) {
1156
+ if (!recoveryAccounting.onPhysicalDispatch && allowance.permit && !allowance.permit.use()) {
1150
1157
  throw new SendBudgetExhaustedError(errorDestinationLabel(request.url));
1151
1158
  }
1152
1159
  transportState.noteRoutedAttemptSend(passthroughEstimate, innerRecovery ?? recovery);
@@ -1161,8 +1168,10 @@ export async function preparePassthroughExchange(
1161
1168
  && responseEffects.plaintextV2AgentMessageToolNames.size === 0
1162
1169
  ? options.nativeControl : undefined,
1163
1170
  dispatchOverride: oauthDispatch(request, parsed, "passthrough"),
1171
+ onPhysicalDispatch: recoveryAccounting.onPhysicalDispatch,
1164
1172
  providerName: route.providerName,
1165
1173
  modelId: route.modelId,
1174
+ onContinuationDispatch,
1166
1175
  accountAutoPause: (name, provider, headers) => captureAccountAutoPauseAttempt(name, provider, { config, codex: admissionState.authCtx }, headers),
1167
1176
  onCodexWsQuota: codexWsQuotaObserver(admissionState.authCtx, route.provider, route.modelId),
1168
1177
  beforeDispatch: isCanonicalOpenAiForwardProvider(route.provider)
@@ -1172,7 +1181,7 @@ export async function preparePassthroughExchange(
1172
1181
  .then(adoptObservedResponse);
1173
1182
  },
1174
1183
  { abortSignal: upstream.signal, label: safeHostLabel(request.url), destination: errorDestinationLabel(request.url), attempts: allowance.attempts,
1175
- onSendsConsumed: transientSendReporter(allowance.permit),
1184
+ onSendsConsumed: recoveryAccounting.report,
1176
1185
  claimAmbiguousResend: recovery === "empty-completion" ? undefined : claimPreHeaderResend },
1177
1186
  );
1178
1187
  } catch (err) {
@@ -1190,6 +1199,7 @@ export async function preparePassthroughExchange(
1190
1199
  if (wasAccountAutoPaused(upstreamResponse) && route.provider.authMode !== "forward") {
1191
1200
  const recovered = await recoverAutoPausedAccount({ requestKey: transportState, reserve: reserveCredentialHop,
1192
1201
  remaining: transientSendCapFor(transientRetryPolicyFor(route.provider)?.attempts, sendBudgetState.targetSendsUsed),
1202
+ mapRefreshError: createAutoPauseRefreshErrorMapper(upstreamResponse, upstream, cleanupUpstreamAbort, copilotRefusalResponse, () => (options.abortSignal ?? req.signal).aborted, clientCancelledResponse),
1193
1203
  refresh: () => transportState.recoverAutoPausedSelection(parsed), refetch: () => rebuildAndRefetch("oauth-account-429"), setPermit: permit => { sendBudgetState.pendingHopPermit = permit; } });
1194
1204
  if (!recovered) break;
1195
1205
  if ("failed" in recovered) return recovered.failed;
@@ -1281,6 +1291,7 @@ export async function preparePassthroughExchange(
1281
1291
  dispatchOverride: oauthDispatch(request, parsed, "passthrough"),
1282
1292
  providerName: route.providerName,
1283
1293
  modelId: route.modelId,
1294
+ onContinuationDispatch,
1284
1295
  accountAutoPause: (name, provider, headers) => captureAccountAutoPauseAttempt(name, provider, { config, codex: admissionState.authCtx }, headers),
1285
1296
  onCodexWsQuota: codexWsQuotaObserver(admissionState.authCtx, route.provider, route.modelId),
1286
1297
  beforeDispatch: headers => {
@@ -1358,11 +1369,6 @@ export async function preparePassthroughExchange(
1358
1369
  releaseCodexAuthContextProbeLease(admissionState.authCtx);
1359
1370
  return markProxyError(formatErrorResponse(401, "authentication_error", publicOAuthAuthenticationErrorMessage(new Error("Cloud Code Assist project is required"))));
1360
1371
  }
1361
- transportState.sentOAuthSnapshot = refreshed;
1362
- transportState.replayOAuthCredentialSnapshot = {
1363
- accountId: refreshed.accountId,
1364
- generation: refreshed.generation,
1365
- };
1366
1372
  if (route.providerName === "kiro") {
1367
1373
  parsed._kiroAuthContext = { ...(refreshed.kiro ?? {}) };
1368
1374
  }
@@ -1378,10 +1384,13 @@ export async function preparePassthroughExchange(
1378
1384
  ? resolveCopilotApiBaseUrl(refreshed.apiBaseUrl)
1379
1385
  : undefined,
1380
1386
  );
1381
- route.provider = refreshedProvider;
1382
- try { await resolveCopilotSelection(parsed); }
1387
+ try { await resolveCopilotSelection(parsed, false, refreshedProvider); }
1383
1388
  catch (err) { return transportFailureResponse(err); }
1384
1389
  refreshedProvider = route.provider;
1390
+ if (route.providerName !== "github-copilot") {
1391
+ transportState.sentOAuthSnapshot = refreshed;
1392
+ transportState.replayOAuthCredentialSnapshot = { accountId: refreshed.accountId, generation: refreshed.generation };
1393
+ }
1385
1394
  const refreshedAdapter = resolveSelectionAdapter(
1386
1395
  resolveWireProtocolOverride(route.providerName, route.modelId, refreshedProvider, inboundWire, route.staticPolicy),
1387
1396
  config.cacheRetention,
@@ -1413,6 +1422,7 @@ export async function preparePassthroughExchange(
1413
1422
  refreshUndeclaredToolGuard(request);
1414
1423
  const refreshedBodyRefusal = refuseOversizedOutboundBody(request);
1415
1424
  if (refreshedBodyRefusal) return refreshedBodyRefusal;
1425
+ const oauthReplayAccounting = copilotSendAccounting();
1416
1426
  try {
1417
1427
  upstreamResponse = await fetchWithTransientRetry(
1418
1428
  recovery => {
@@ -1428,8 +1438,10 @@ export async function preparePassthroughExchange(
1428
1438
  && responseEffects.plaintextV2AgentMessageToolNames.size === 0
1429
1439
  ? options.nativeControl : undefined,
1430
1440
  dispatchOverride: oauthDispatch(request, parsed, "passthrough"),
1441
+ onPhysicalDispatch: oauthReplayAccounting.onPhysicalDispatch,
1431
1442
  providerName: route.providerName,
1432
1443
  modelId: route.modelId,
1444
+ onContinuationDispatch,
1433
1445
  accountAutoPause: (name, provider, headers) => captureAccountAutoPauseAttempt(name, provider, { config, codex: admissionState.authCtx }, headers),
1434
1446
  onCodexWsQuota: codexWsQuotaObserver(admissionState.authCtx, route.provider, route.modelId),
1435
1447
  beforeDispatch: isCanonicalOpenAiForwardProvider(route.provider)
@@ -1439,7 +1451,7 @@ export async function preparePassthroughExchange(
1439
1451
  .then(adoptObservedResponse);
1440
1452
  },
1441
1453
  { abortSignal: upstream.signal, label: safeHostLabel(request.url), destination: errorDestinationLabel(request.url), attempts: remainingTransientSendBudget(transientSendAttempts()),
1442
- onSendsConsumed: transientSendReporter(), claimAmbiguousResend: claimPreHeaderResend },
1454
+ onSendsConsumed: oauthReplayAccounting.report, claimAmbiguousResend: claimPreHeaderResend },
1443
1455
  );
1444
1456
  } catch (err) {
1445
1457
  return transportFailureResponse(err);
@@ -1558,6 +1570,7 @@ export async function preparePassthroughExchange(
1558
1570
  upstream.abort();
1559
1571
  return clientCancelledResponse();
1560
1572
  }
1573
+ const failoverAccounting = copilotSendAccounting();
1561
1574
  try {
1562
1575
  upstreamResponse = await fetchWithTransientRetry(
1563
1576
  recovery => {
@@ -1575,8 +1588,10 @@ export async function preparePassthroughExchange(
1575
1588
  && responseEffects.plaintextV2AgentMessageToolNames.size === 0
1576
1589
  ? options.nativeControl : undefined,
1577
1590
  dispatchOverride: oauthDispatch(request, parsed, "passthrough"),
1591
+ onPhysicalDispatch: failoverAccounting.onPhysicalDispatch,
1578
1592
  providerName: route.providerName,
1579
1593
  modelId: route.modelId,
1594
+ onContinuationDispatch,
1580
1595
  accountAutoPause: (name, provider, headers) => captureAccountAutoPauseAttempt(name, provider, { config, codex: admissionState.authCtx }, headers),
1581
1596
  onCodexWsQuota: codexWsQuotaObserver(admissionState.authCtx, route.provider, route.modelId),
1582
1597
  beforeDispatch: isCanonicalOpenAiForwardProvider(route.provider)
@@ -1586,7 +1601,7 @@ export async function preparePassthroughExchange(
1586
1601
  .then(adoptObservedResponse);
1587
1602
  },
1588
1603
  { abortSignal: upstream.signal, label: safeHostLabel(request.url), destination: errorDestinationLabel(request.url), attempts: remainingTransientSendBudget(transientSendAttempts()),
1589
- onSendsConsumed: transientSendReporter(), claimAmbiguousResend: claimPreHeaderResend },
1604
+ onSendsConsumed: failoverAccounting.report, claimAmbiguousResend: claimPreHeaderResend },
1590
1605
  );
1591
1606
  } catch (err) {
1592
1607
  return transportFailureResponse(err);
@@ -47,6 +47,7 @@ export async function executePassthroughResponse(
47
47
  sidecarState,
48
48
  responseEffects,
49
49
  nativeExchange,
50
+ sendBudgetState.dispatchSidecarSend,
50
51
  );
51
52
  // Delivery has already classified SSE (including a missing upstream content type)
52
53
  // and consumed bounded JSON/errors. Guard only its remaining direct body, outside
@@ -1,6 +1,7 @@
1
1
  import { comboFailureDecision } from "../../combos/failover";
2
2
  import { readBoundedResponseBody } from "../../lib/bounded-body";
3
3
  import { isVerifiedModelNotInPlanResponse } from "../../lib/errors";
4
+ import { isShadowSourceModel } from "../../lib/shadow-call";
4
5
  import { isNonReplayableResponse } from "../../lib/upstream-retry";
5
6
  import { finishRequestAttempt, type RequestLogContext } from "../request-log";
6
7
  import { linkRequestSessionLane } from "../request-log-conversation";
@@ -13,7 +14,7 @@ import { captureCallerDirectAuth } from "../../providers/caller-authorization";
13
14
  import { resolvePolicyProfileId } from "../../routing/profile";
14
15
  import { parseSyntheticRowId } from "../fast-row";
15
16
  import { routeConcreteModel } from "../../router";
16
- import { isPolicyCandidateRefusal, policyWireDestination, type PolicyRequestScope } from "./policy-request-scope";
17
+ import { isPolicyCandidateRefusal, isMandatoryToolChoiceRefusal, mandatoryToolChoiceUnavailableResponse, policyWireDestination, type PolicyRequestScope } from "./policy-request-scope";
17
18
  import { fallbackTriggerForStatus, guardFallbackHop } from "../../routing/fallback-policy";
18
19
  import { captureAdmissionPolicy } from "../capture-admission-policy";
19
20
  import { upstreamCodeForComboFailure } from "../../bridge/errors";
@@ -205,7 +206,15 @@ export async function handleResponsesWithPolicyFallback(
205
206
  && typeof (body as { model?: unknown }).model === "string") {
206
207
  const model = (body as { model: string }).model;
207
208
  const { fastRow, effortRow } = parseSyntheticRowId(model, config);
208
- if (resolvePolicyProfileId(config, fastRow?.baseId ?? effortRow?.baseId ?? model) === null) return;
209
+ // A shadow-intercepted request is rewritten to its configured target after this hook —
210
+ // and that target may resolve through a routing profile. The snapshot has to exist now,
211
+ // while the body still names the source: a captured policy route without a replay body
212
+ // skips traversal and leaks the internal candidate refusal to the caller.
213
+ const intercept = config.shadowCallIntercept;
214
+ const shadowRewritable = Boolean(intercept?.enabled && intercept.model)
215
+ && isShadowSourceModel(model, intercept?.sourceModels);
216
+ if (resolvePolicyProfileId(config, fastRow?.baseId ?? effortRow?.baseId ?? model) === null
217
+ && !shadowRewritable) return;
209
218
  // Recovery and other core preparation may mutate the parsed body in place. Keep an
210
219
  // immutable snapshot of the original wire body so a retry cannot serialize those
211
220
  // mutations. Object-identity metadata is re-established by each attempt, not serialized.
@@ -247,12 +256,17 @@ export async function handleResponsesWithPolicyFallback(
247
256
  }));
248
257
  let current = resolvedPolicyTarget(config, initialTrace.selected);
249
258
  const policyRoute = `policy/${initialTrace.profile!.id}`;
259
+ let toolChoiceRefusalsOnly = isMandatoryToolChoiceRefusal(response);
250
260
 
251
261
  while (!storedPool401ReplayDispatched && await shouldHopPolicyCandidate(response, req.signal)) {
252
262
  if (req.signal.aborted) return response;
253
263
  const next = rankPolicyFallbackCandidates(initialTrace, tried)
254
264
  .find(candidate => staysWithinPolicyAfterRedirect(config, policyEligibility, candidate, policyScope.triedDestinations));
255
- if (!next) return response;
265
+ if (!next) {
266
+ if (!toolChoiceRefusalsOnly) return response;
267
+ try { await response.body?.cancel(); } catch { /* the terminal diagnostic replaces this body */ }
268
+ return mandatoryToolChoiceUnavailableResponse();
269
+ }
256
270
  // OCX-11: the next candidate is a hop; the fallback policy decides before it is sent, on the
257
271
  // redirected destination the guard above already validated.
258
272
  const nextTarget = resolvedPolicyTarget(config, next);
@@ -281,16 +295,29 @@ export async function handleResponsesWithPolicyFallback(
281
295
  delete policyScope.preparedDestination;
282
296
  try {
283
297
  try {
284
- const nextResponse = await runCore(retryRequest, config, logCtx, { ...coreOptions, policyFallbackCandidate: next });
298
+ const nextResponse = await runCore(retryRequest, config, logCtx, {
299
+ ...coreOptions,
300
+ policyFallbackCandidate: next,
301
+ // A shadow-intercepted request retried on a candidate keeps helper isolation and
302
+ // its suppressed selector label; a first-party policy request leaves the flag unset.
303
+ ...(logCtx.shadowCallRewrittenFrom ? { shadowCallIntercepted: true } : {}),
304
+ });
305
+ toolChoiceRefusalsOnly &&= isMandatoryToolChoiceRefusal(nextResponse);
285
306
  // A locally skipped route owns neither the returned failure nor its usage/settlement.
286
307
  // Preparation can replace route metadata and the tracker, or add fields absent before it.
287
- if (isPolicyCandidateRefusal(nextResponse)) {
308
+ // The sendCount seam separates that skip from a refusal minted only after a physical
309
+ // send — a re-negotiated Copilot destination refused inside 401 or account recovery.
310
+ // The send happened, so the hop it rode commits below and the sent destination becomes
311
+ // the next hop's source, which is what a provider-scoped fallback refusal keys on.
312
+ if (isPolicyCandidateRefusal(nextResponse) && (logCtx.activeAttempt?.sendCount ?? 0) === 0) {
313
+ try { await nextResponse.body?.cancel(); } catch { /* settle the skipped candidate's lifetime owners */ }
288
314
  for (const key of Object.keys(logCtx)) {
289
315
  if (!Object.hasOwn(failureLog, key)) Reflect.deleteProperty(logCtx, key);
290
316
  }
291
317
  Object.assign(logCtx, failureLog);
292
318
  } else {
293
319
  // Dispatched: only a candidate that was not locally skipped counts as a taken hop.
320
+ try { await response.body?.cancel(); } catch { /* the dispatched candidate replaces the retained failure */ }
294
321
  hop.commit();
295
322
  response = nextResponse;
296
323
  current = nextTarget;
@@ -1,4 +1,5 @@
1
1
  import { formatErrorResponse } from "../../bridge";
2
+ import { markProxyError } from "../../lib/client-error-body";
2
3
  import type { RouteResult } from "../../router";
3
4
  import type { RouteDecisionTraceV1 } from "../../routing/trace";
4
5
  import { resolveOpenAiVirtualModel } from "../../providers/openai-virtual-models";
@@ -27,12 +28,26 @@ export class PolicyCandidateUnavailableError extends Error {
27
28
  }
28
29
  }
29
30
 
31
+ export class MandatoryToolChoiceUnavailableError extends PolicyCandidateUnavailableError {
32
+ constructor() {
33
+ super();
34
+ this.name = "MandatoryToolChoiceUnavailableError";
35
+ }
36
+ }
37
+
38
+ export function mandatoryToolChoiceUnavailableResponse(): Response {
39
+ return markProxyError(formatErrorResponse(400, "invalid_request_error",
40
+ "This mandatory tool_choice cannot be preserved for a translated Chat destination."));
41
+ }
42
+
30
43
  const localRefusals = new WeakSet<Response>();
44
+ const mandatoryToolRefusals = new WeakSet<Response>();
31
45
 
32
46
  export function policyCandidateRefusalResponse(error: unknown): Response | undefined {
33
47
  if (!(error instanceof PolicyCandidateUnavailableError)) return undefined;
34
48
  const response = formatErrorResponse(409, "policy_candidate_unavailable", error.message);
35
49
  localRefusals.add(response);
50
+ if (error instanceof MandatoryToolChoiceUnavailableError) mandatoryToolRefusals.add(response);
36
51
  return response;
37
52
  }
38
53
 
@@ -41,6 +56,17 @@ export function isPolicyCandidateRefusal(response: Response): boolean {
41
56
  return localRefusals.has(response);
42
57
  }
43
58
 
59
+ export function isMandatoryToolChoiceRefusal(response: Response): boolean {
60
+ return mandatoryToolRefusals.has(response);
61
+ }
62
+
63
+ /** Preserve local refusal authority when response lifetime owners wrap the body. */
64
+ export function carryPolicyCandidateRefusal(source: Response, target: Response): Response {
65
+ if (localRefusals.has(source)) localRefusals.add(target);
66
+ if (mandatoryToolRefusals.has(source)) mandatoryToolRefusals.add(target);
67
+ return target;
68
+ }
69
+
44
70
  export function capturePolicyRequestRoute(scope: PolicyRequestScope, route: RouteResult): RouteResult {
45
71
  if (!scope.eligibility && route.policyEligibility && route.routeDecision?.routeKind === "policy") {
46
72
  scope.eligibility = new Set(route.policyEligibility);
@@ -8,7 +8,7 @@ import type { PolicyRequestEvidence } from "../../routing/evaluator";
8
8
  import type { RequestLogContext } from "../request-log";
9
9
  import { markProtocolEntry, protocolMarkFeatures } from "../../protocols/trace";
10
10
  import { isAntigravityRoute } from "../antigravity-direct-eligibility";
11
- import { capturePolicyRequestRoute, assertPolicyNormalizedRoute, recordPolicyPreparedDestination, policyCandidateRefusalResponse } from "./policy-request-scope";
11
+ import { capturePolicyRequestRoute, assertPolicyNormalizedRoute, recordPolicyPreparedDestination, policyCandidateRefusalResponse, MandatoryToolChoiceUnavailableError, mandatoryToolChoiceUnavailableResponse } from "./policy-request-scope";
12
12
  import {
13
13
  agentTaskRecoveryConfig,
14
14
  restoreCachedEncryptedAgentTasks,
@@ -74,6 +74,7 @@ import {
74
74
  previousResponseProviderState,
75
75
  } from "../../responses/state";
76
76
  import { formatErrorResponse } from "../../bridge";
77
+ import { chatCanPreserveMandatoryToolChoice } from "./combo-required-tool-contract";
77
78
  import { mapCodexAuthContextErrorToResponse } from "./codex-auth-error";
78
79
  import type { OcxParsedRequest } from "../../types";
79
80
  import { buildToolBridgeMaps } from "./collaboration";
@@ -1460,12 +1461,20 @@ export async function prepareResponsesRequest(
1460
1461
  });
1461
1462
  try {
1462
1463
  assertPolicyNormalizedRoute(policyScope, admittedPolicyRoute, route);
1464
+ const copilotNegotiationPending = route.providerName === "github-copilot" && route.provider.authMode !== "forward";
1465
+ if (!copilotNegotiationPending && route.provider.adapter === "openai-chat"
1466
+ && !chatCanPreserveMandatoryToolChoice(parsed._rawBody, route.provider, route.modelId, parsed.context.tools ?? [])) {
1467
+ // Combo children carry the refusal's local identity too, so a compatible sibling target
1468
+ // can still be tried; a direct request keeps the client-facing 400 below.
1469
+ if (policyScope.eligibility || options.comboAttempt) throw new MandatoryToolChoiceUnavailableError();
1470
+ return mandatoryToolChoiceUnavailableResponse();
1471
+ }
1463
1472
  } catch (error) {
1464
1473
  const policyRefusal = policyCandidateRefusalResponse(error);
1465
1474
  if (policyRefusal) return policyRefusal;
1466
1475
  throw error;
1467
1476
  }
1468
- // Normalization is the last thing that can move the destination: resolving an
1477
+ // Static normalization can move the destination: resolving an
1469
1478
  // OpenAI virtual model rewrites route.modelId to the wire id that will
1470
1479
  // actually be billed. A scope checked only before this would authorize the
1471
1480
  // public selector and send the wire model, so the settled route is checked