@bitkyc08/opencodex 2.98.0 → 2.99.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 (109) hide show
  1. package/bin/ocx.mjs +6 -19
  2. package/gui/dist/assets/App-BepstgEN.js +59 -0
  3. package/gui/dist/assets/{App-6TFtZsUF.css → App-C1hGwaN1.css} +1 -1
  4. package/gui/dist/assets/Tray-BinxbEZo.js +1 -0
  5. package/gui/dist/assets/{brand-mark-A03mw_9y.js → brand-mark-wzPe3R-J.js} +1 -1
  6. package/gui/dist/assets/{index-BjTIN4to.js → index-C-9X2yaI.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-fYEMxBaW.js} +1 -1
  9. package/gui/dist/classic/assets/App-DX88_GCW.js +58 -0
  10. package/gui/dist/classic/assets/Tray-BqZueZOx.js +1 -0
  11. package/gui/dist/classic/assets/{index-DFAFnven.js → index-fSP71pLB.js} +13 -13
  12. package/gui/dist/classic/assets/{quota-summary-C-4HP4_5.js → quota-summary-y2fl0WBv.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
@@ -73,7 +73,7 @@ import {
73
73
  CodexPoolAccountCreditsOffError,
74
74
  } from "../../codex/auth-context";
75
75
  import { ACCOUNT_GATED_NATIVE_OPENAI_MODELS } from "../../codex/catalog/native-models";
76
- import { isRequestExecutionBudget } from "../../lib/request-execution-budget";
76
+ import { createBoundedSameTargetRecovery, hasWorkflowSendObserver, isRequestExecutionBudget } from "../../lib/request-execution-budget";
77
77
  import type { SingleUseDispatchPermit } from "../../lib/request-execution-budget";
78
78
  import { codexRouteCredentialOwnership, type CodexCredentialOwnershipOptions } from "./core-auth";
79
79
  import { bindRouteReasoningReplayScope } from "./core-replay";
@@ -90,7 +90,8 @@ import {
90
90
  noteProviderAttemptSend,
91
91
  } from "../request-log";
92
92
  import { codexAuthContextLogLabel } from "../../codex/account-label";
93
- import { chargeWorkflowSends } from "../../lib/workflow-budget";
93
+ import { reserveWorkflowSend, workflowSendCeilingReached } from "../../lib/workflow-budget";
94
+ import { currentWorkflowBudgetPolicy } from "../../lib/workflow-budget-config";
94
95
  import type { ResponsesTerminalStatus } from "../../bridge";
95
96
 
96
97
  export function sidecarOutcomeRecorder(
@@ -952,23 +953,6 @@ export async function retryCodexPoolOnAlternateAccount(
952
953
  recordAdapterReasoning(logCtx, request);
953
954
  recordAdapterTier(logCtx, request);
954
955
 
955
- await firstResponse.body?.cancel().catch(() => undefined);
956
- options.onCodexAuthContextResolved?.(retryAuthCtx);
957
- route.provider = retryProvider;
958
- logCtx.provider = formatCodexProviderForLog(
959
- route.providerName,
960
- retryAuthCtx.accountId,
961
- config,
962
- );
963
- logCtx.accountLogLabel = codexAuthContextLogLabel(retryAuthCtx, config);
964
- sealRequestAttemptIdentity(
965
- logCtx.activeAttempt,
966
- logCtx.provider,
967
- retryAdapter.name,
968
- logCtx.accountLogLabel,
969
- );
970
- recordAttemptCredentialSource(logCtx.activeAttempt, route.providerName, route.provider, retryAdapter.name);
971
-
972
956
  const retrySameConfirmedAccount = outcomeStatus === 400
973
957
  && ACCOUNT_GATED_NATIVE_OPENAI_MODELS.has(route.modelId)
974
958
  && retryAuthCtx.accountId === firstAuthCtx.accountId;
@@ -978,15 +962,6 @@ export async function retryCodexPoolOnAlternateAccount(
978
962
  // exact allow-listed body and fresh entitlement before every later send. Alternate-account and
979
963
  // quota recovery retain their historical one-send bound.
980
964
  //
981
- // Two different bounds, and the effective one is the smaller. `maxRetrySends` answers "how
982
- // many times is it worth re-asking THIS account for a model its roster still grants"; the
983
- // shared budget answers "how many times may this LOGICAL REQUEST reach upstream in total,
984
- // across every layer that can re-send". A ladder of eight layered on sends the request had
985
- // already made is exactly the per-request multiplication #4546 is about, so the ladder is
986
- // capped at what the request has left. The floor of one keeps the single retry this function
987
- // was called to make -- the move already paid for itself with its own permit -- and each rung
988
- // past the first reserves its own send below, so a refusal stops the ladder with the last
989
- // upstream answer intact.
990
965
  // The ladder replays to the SAME account, so it must reserve under the same target key the
991
966
  // other legs use. Folding the account id in made every rung read as a target change, which
992
967
  // spent the one cross-account slot a real move needs on a same-account replay.
@@ -996,18 +971,41 @@ export async function retryCodexPoolOnAlternateAccount(
996
971
  // at eight same-account dispatches (tests/server/server-auth.test.ts), and a request that has
997
972
  // already spent sends would silently stop short of it. Reconciling an eight-send same-account
998
973
  // ladder with a four-send request total is a policy decision, not a clamp to add in passing.
999
- // What this diff does fix is that the rungs are now CHARGED instead of free.
974
+ // Every physical rung still needs the workflow's allowance, including the first same-account
975
+ // retry and a rung admitted by that historical request-local exception.
1000
976
  const maxRetrySends = retrySameConfirmedAccount ? 7 : 1;
977
+ const sameAccountRecovery = retrySameConfirmedAccount && executionBudget
978
+ ? createBoundedSameTargetRecovery(executionBudget, ladderTargetKey, maxRetrySends) : undefined;
979
+ const workflowObserved = sameAccountRecovery?.workflowCountObserved
980
+ ?? (executionBudget && hasWorkflowSendObserver(executionBudget));
981
+ const claimRetrySend = (permit?: SingleUseDispatchPermit): boolean => {
982
+ const workflowPolicy = currentWorkflowBudgetPolicy();
983
+ // Legacy permits cannot refund after use(). Check the root first, then use the permit
984
+ // and reserve the root in this same synchronous turn. A failed permit claims no root
985
+ // slot, and a root refusal can still release the unused request reservation.
986
+ if (!workflowObserved && workflowSendCeilingReached(options.workflowRootId, workflowPolicy)) {
987
+ permit?.release();
988
+ return false;
989
+ }
990
+ if (permit && !permit.use()) {
991
+ permit.release();
992
+ return false;
993
+ }
994
+ // Observed sends always own a spend-backed permit, including the bounded same-account
995
+ // exception. Its use() already claimed the root; a root claim alone is no spend grant.
996
+ if (workflowObserved) return permit !== undefined;
997
+ return reserveWorkflowSend(options.workflowRootId, workflowPolicy);
998
+ };
1001
999
  let retrySendCount = 0;
1002
1000
  // The gated-model 400 has no roster kind; it stays unattributed as before.
1003
1001
  const moveRecovery: AttemptRecoveryKind | undefined = outcomeStatus === 429 ? "oauth-account-429"
1004
1002
  : outcomeStatus === 402 ? "oauth-account-402"
1005
1003
  : isTransientUpstreamStatus(outcomeStatus) ? "transient-5xx" : undefined;
1006
- let upstreamResponse: Response;
1004
+ let upstreamResponse = firstResponse;
1007
1005
  try {
1008
1006
  while (true) {
1009
- // The same-account gated-model 400 ladder below keeps its own `maxRetrySends` bound and
1010
- // does not take the reserve again; only the move itself does.
1007
+ // A same-account rung uses its bounded recovery owner. Only an account move takes the
1008
+ // ordinary final-recovery reserve and the pool-wide recovery window.
1011
1009
  if (accountMovePermit) {
1012
1010
  // The pool-wide recovery window is consulted BEFORE the request-local permit is used.
1013
1011
  // `reserveDispatch` charges at reservation time and `release()` is the only way back, so
@@ -1027,49 +1025,76 @@ export async function retryCodexPoolOnAlternateAccount(
1027
1025
  recordUnmovedTransientOutcome();
1028
1026
  return { kind: "no-alternate" };
1029
1027
  }
1030
- const charged = accountMovePermit.use();
1031
- accountMovePermit = undefined;
1032
- if (!charged) {
1028
+ }
1029
+ const rung = sameAccountRecovery?.reserve();
1030
+ if (rung && !rung.allowed) {
1031
+ if (retrySendCount > 0) break;
1032
+ releaseCodexAuthContextProbeLease(retryAuthCtx);
1033
+ return { kind: "no-alternate" };
1034
+ }
1035
+ const permit = accountMovePermit ?? (rung?.allowed ? rung.permit : undefined);
1036
+ accountMovePermit = undefined;
1037
+ try {
1038
+ const dispatch = async (): Promise<Response | undefined> => {
1039
+ // Spend admission must see the credential the retry will use. Restore the original
1040
+ // label if admission refuses, while leaving that original response readable.
1041
+ const priorAccountLabel = logCtx.accountLogLabel;
1042
+ logCtx.accountLogLabel = codexAuthContextLogLabel(retryAuthCtx, config);
1043
+ let admitted = false;
1044
+ try {
1045
+ if (!claimRetrySend(permit)) return undefined;
1046
+ admitted = true;
1047
+ await upstreamResponse.body?.cancel().catch(() => undefined);
1048
+ if (retrySendCount === 0) {
1049
+ options.onCodexAuthContextResolved?.(retryAuthCtx);
1050
+ route.provider = retryProvider;
1051
+ logCtx.provider = formatCodexProviderForLog(route.providerName, retryAuthCtx.accountId, config);
1052
+ sealRequestAttemptIdentity(logCtx.activeAttempt, logCtx.provider, retryAdapter.name, logCtx.accountLogLabel);
1053
+ recordAttemptCredentialSource(logCtx.activeAttempt, route.providerName, route.provider, retryAdapter.name);
1054
+ }
1055
+ // A move seals the first account's attempt with the answer that account returned.
1056
+ if (logCtx.activeAttempt && logCtx.activeAttempt.status < 100) logCtx.activeAttempt.status = firstResponse.status;
1057
+ noteProviderAttemptSend(logCtx, route.providerName, route.provider, passthroughEstimate, moveRecovery);
1058
+ return await fetchWithHeaderTimeout(
1059
+ request.url,
1060
+ { method: request.method, headers: request.headers, body: request.body },
1061
+ upstream.signal,
1062
+ connectMs,
1063
+ stream,
1064
+ providerFetch(route.provider, options.codexWsRuntimeIdentity, {
1065
+ httpOnly,
1066
+ providerName: route.providerName,
1067
+ modelId: route.modelId,
1068
+ preOutputRefusalHold: args.preOutputRefusalHold,
1069
+ accountAutoPause: (name, provider, headers) => captureAccountAutoPauseAttempt(name, provider, { config, codex: retryAuthCtx }, headers),
1070
+ onCodexWsQuota: codexWsQuotaObserver(retryAuthCtx, route.provider, route.modelId),
1071
+ beforeDispatch: isCanonicalOpenAiForwardProvider(route.provider)
1072
+ ? createCodexAuthDispatchGuard(retryAuthCtx, options.codexAuthPolicy ?? config, route.modelId, options.admission, options.visionDescribeTerminal === true) : undefined,
1073
+ }),
1074
+ // Credential-bearing forward send: never follow a redirect into a
1075
+ // dead-host rejection after the credential was seen (#914).
1076
+ route.provider.authMode === "forward",
1077
+ );
1078
+ } finally {
1079
+ if (!admitted) logCtx.accountLogLabel = priorAccountLabel;
1080
+ }
1081
+ };
1082
+ // Keep the physical producer open through the fetch; use() without its executor span
1083
+ // closes it immediately and loses the selected start before a credential rebind.
1084
+ const response = permit?.execute ? await permit.execute(dispatch) : await dispatch();
1085
+ if (!response) {
1086
+ if (retrySendCount > 0) break;
1033
1087
  releaseCodexAuthContextProbeLease(retryAuthCtx);
1034
1088
  recordUnmovedTransientOutcome();
1035
1089
  return { kind: "no-alternate" };
1036
1090
  }
1037
- // The move is a physical send like any other, so the root workflow is charged too.
1038
- chargeWorkflowSends(args.options.workflowRootId, 1);
1039
- }
1040
- // A move seals the first account's attempt here. Give it the status that account actually
1041
- // answered, not the 502 the split infers, and name why the second send exists.
1042
- if (logCtx.activeAttempt && logCtx.activeAttempt.status < 100) logCtx.activeAttempt.status = firstResponse.status;
1043
- noteProviderAttemptSend(logCtx, route.providerName, route.provider, passthroughEstimate, moveRecovery);
1044
- try {
1045
- upstreamResponse = await fetchWithHeaderTimeout(
1046
- request.url,
1047
- {
1048
- method: request.method,
1049
- headers: request.headers,
1050
- body: request.body,
1051
- },
1052
- upstream.signal,
1053
- connectMs,
1054
- stream,
1055
- providerFetch(route.provider, options.codexWsRuntimeIdentity, {
1056
- httpOnly,
1057
- providerName: route.providerName,
1058
- modelId: route.modelId,
1059
- preOutputRefusalHold: args.preOutputRefusalHold,
1060
- accountAutoPause: (name, provider, headers) => captureAccountAutoPauseAttempt(name, provider, { config, codex: retryAuthCtx }, headers),
1061
- onCodexWsQuota: codexWsQuotaObserver(retryAuthCtx, route.provider, route.modelId),
1062
- beforeDispatch: isCanonicalOpenAiForwardProvider(route.provider)
1063
- ? createCodexAuthDispatchGuard(retryAuthCtx, options.codexAuthPolicy ?? config, route.modelId, options.admission, options.visionDescribeTerminal === true) : undefined,
1064
- }),
1065
- // Credential-bearing forward send: never follow a redirect into a
1066
- // dead-host rejection after the credential was seen (#914).
1067
- route.provider.authMode === "forward",
1068
- );
1091
+ upstreamResponse = response;
1069
1092
  } catch (error) {
1070
1093
  // Only the forward send is a transport boundary. Entitlement resolver throws below are
1071
1094
  // deliberately outside this catch so programming errors retain their original path.
1072
1095
  return { kind: "transport", error, authCtx: retryAuthCtx };
1096
+ } finally {
1097
+ permit?.release();
1073
1098
  }
1074
1099
  retrySendCount += 1;
1075
1100
  args.onResponse?.(upstreamResponse, retryAuthCtx, request);
@@ -1112,25 +1137,6 @@ export async function retryCodexPoolOnAlternateAccount(
1112
1137
  throw error;
1113
1138
  }
1114
1139
  if (!entitledCodexAccountIdsForModel(refreshed, route.modelId)?.has(retryAuthCtx.accountId)) break;
1115
- // The next rung is another physical send of this logical request: a same-account,
1116
- // same-target replay, charged as an ordinary transient send rather than as a move.
1117
- // Reserved here, immediately before looping back, so a refusal stops the ladder with the
1118
- // last upstream 400 intact instead of spending a send it cannot make.
1119
- // Every rung is CHARGED, and a refusal does not end the ladder. That asymmetry is
1120
- // deliberate and it is the one place the shared cap yields. This is a same-account,
1121
- // same-target replay of a model-gating 400 whose own bound is eight dispatches, pinned by
1122
- // #2097; letting a spent request budget cut it to four would break a recovery that works
1123
- // today, which is precisely the mistake 040_send_budget.md warns a flat ceiling makes.
1124
- // The request total still governs everything that changes target or credential.
1125
- if (executionBudget) {
1126
- const rung = executionBudget.reserveDispatch({
1127
- sendClass: "transient",
1128
- targetKey: ladderTargetKey,
1129
- });
1130
- if (rung.allowed) rung.permit.use();
1131
- chargeWorkflowSends(args.options.workflowRootId, 1);
1132
- }
1133
- await upstreamResponse.body?.cancel().catch(() => undefined);
1134
1140
  }
1135
1141
  } finally {
1136
1142
  request.releaseBodyObservation?.();
@@ -1,5 +1,8 @@
1
+ import { recordUpstreamValidationDetail, type FailureDetail } from "../request-log-failure-detail";
1
2
  import { carryProxyErrorPresentation } from "../../lib/client-error-body";
3
+ import { carryPolicyCandidateRefusal } from "./policy-request-scope";
2
4
  import { comboFailureEvidence, carryProxyError } from "../../lib/client-error-body";
5
+ import { carryWorkflowRefusal } from "../workflow-refusal";
3
6
  import { codexAccountModelRefusal, codexAccountModelRefusalHardStopCode, type CodexAccountModelRefusal } from "../../combos/failover";
4
7
  import { parseRetryAfterMs } from "../../combos";
5
8
  import type { ConsumedComboFailure, HandleResponsesOptions } from "./core-options";
@@ -41,6 +44,7 @@ export async function consumeComboFailure(
41
44
  response: Response,
42
45
  signal?: AbortSignal,
43
46
  now = Date.now(),
47
+ logCtx?: { failureDetail?: FailureDetail },
44
48
  ): Promise<ConsumedComboFailure> {
45
49
  // Read before the body: the marker lives on this Response object, and the failure below is
46
50
  // rebuilt as a new one that would otherwise lose it.
@@ -79,6 +83,7 @@ export async function consumeComboFailure(
79
83
  && isRateLimitOrQuotaFailureMessage(quotaMessage);
80
84
  }
81
85
  if (body.displaySafe && !body.truncated) {
86
+ if (logCtx) recordUpstreamValidationDetail(logCtx, response.status, body.text);
82
87
  if (response.status === 400) codexModelRefusal = codexAccountModelRefusal(response.status, body.text);
83
88
  const normalized = normalizeUpstreamErrorText(body.text, fallback);
84
89
  if (utf8Trusted || isCyberPolicyCode(normalized.code) || isCyberPolicyMessage(normalized.safeText)) {
@@ -144,8 +149,10 @@ export async function consumeComboFailure(
144
149
  );
145
150
  if (nonReplayable) markResponseNonReplayable(failureResponse);
146
151
  carryProxyError(response, failureResponse);
152
+ carryWorkflowRefusal(response, failureResponse);
147
153
  carryReplayRefusal(response, failureResponse);
148
154
  carryProxyErrorPresentation(response, failureResponse);
155
+ carryPolicyCandidateRefusal(response, failureResponse);
149
156
  if (verifiedPlanRefusal) markVerifiedModelNotInPlanResponse(failureResponse);
150
157
  carryAnthropicRefusalCredential(response, failureResponse);
151
158
  carryCodexAccountCooldownResponse(response, failureResponse);
@@ -7,6 +7,7 @@ import { effectiveAzureOutputBudget } from "../../adapters/azure";
7
7
  import { buildResponsesTransport } from "../../adapters/openai-responses/transport";
8
8
  import { isMetaAiResponsesDestination } from "../../responses/muse-tool-name-alias";
9
9
  import { chatCanPreserveMandatoryToolChoice, hasMandatoryToolChoice } from "./combo-required-tool-contract";
10
+ import { isPolicyCandidateRefusal, isMandatoryToolChoiceRefusal } from "./policy-request-scope";
10
11
  import { isCodexAccountCooldownResponse } from "../../codex/account-cooldown-response";
11
12
  import { resolveWireProtocolOverride } from "../adapter-resolve";
12
13
  import { parseSyntheticRowId } from "../fast-row";
@@ -562,6 +563,8 @@ export async function executeComboResponses(
562
563
  const policy = captureRouteStaticPolicy(route.providerName, modelId, route.provider,
563
564
  route.staticPolicy.effectiveAlias, inboundWire);
564
565
  const provider = resolveWireProtocolOverride(route.providerName, modelId, route.provider, inboundWire, policy);
566
+ // Copilot's Auto account may settle on a different wire; the child checks that result.
567
+ if (route.providerName === "github-copilot" && provider.authMode !== "forward") return true;
565
568
  return provider.adapter === "openai-chat" ? chatCanPreserveMandatoryToolChoice(body, provider, modelId)
566
569
  : provider.adapter !== "openai-responses" || !isMetaAiResponsesDestination(buildResponsesTransport(provider, { headers: req.headers }).url);
567
570
  } catch {
@@ -909,6 +912,7 @@ export async function executeComboResponses(
909
912
  // Local input admission refusals (#1524), while every failed target so far was one: such a
910
913
  // target sent nothing, so an exhausted ladder must not be reported as a provider rejection.
911
914
  let localAdmissionRefusals: string[] | undefined = [];
915
+ let toolChoiceRefusalsOnly: boolean | undefined;
912
916
  // The first quota/rate-limit refusal of the ladder. A fallback that then refuses its own
913
917
  // credential or plan (401/403, or a 400 the ladder hopped past) says nothing about why the
914
918
  // request failed: the primary target ran out. Returning that fallback refusal told clients
@@ -919,7 +923,7 @@ export async function executeComboResponses(
919
923
  // Snapshotted before dispatch: a 401/403 inside this ladder cools its own provider, and that
920
924
  // fresh cooldown is not a reason the request found no target.
921
925
  const quotaCooldownSnapshot = snapshotComboQuotaCooldowns(config, comboId);
922
- const exhaustedFailure = (): Response => {
926
+ const exhaustedFailure = (targetsExhausted = false): Response => {
923
927
  if (contextFailure) {
924
928
  adoptFailedChildLog(contextFailure.childLog);
925
929
  return contextFailure.response;
@@ -927,6 +931,7 @@ export async function executeComboResponses(
927
931
  const returnsQuota = lastFailure && [400, 401, 403].includes(lastFailure.status) && quotaFailure;
928
932
  const failedChildLog = returnsQuota ? quotaFailedChildLog : lastFailedChildLog;
929
933
  if (failedChildLog) adoptFailedChildLog(failedChildLog);
934
+ if (targetsExhausted && toolChoiceRefusalsOnly === true) return comboUnavailableResponse("No available targets for combo; attempted targets cannot preserve mandatory tool_choice");
930
935
  if (!lastFailure || ![400, 401, 403].includes(lastFailure.status)) return lastFailure!;
931
936
  if (quotaFailure) return quotaFailure;
932
937
  // The quota-refused target was cooled before this request picked, so the ladder never saw
@@ -1330,7 +1335,7 @@ export async function executeComboResponses(
1330
1335
  let failure: ConsumedComboFailure;
1331
1336
  try {
1332
1337
  failure = consumedChildFailure
1333
- ?? await consumeComboFailure(response, options.abortSignal);
1338
+ ?? await consumeComboFailure(response, options.abortSignal, Date.now(), childLog);
1334
1339
  if (hasProxyErrorMessage(childLog, failure.upstreamMessage ?? "", { type: failure.upstreamType, code: failure.upstreamCode })) markProxyError(failure.response);
1335
1340
  if (preflightModelRefusal !== undefined) failure = { ...failure, codexModelRefusal: preflightModelRefusal };
1336
1341
  } catch (error) {
@@ -1376,6 +1381,7 @@ export async function executeComboResponses(
1376
1381
  }
1377
1382
  attemptRetained = true;
1378
1383
  lastFailure = failure.response;
1384
+ toolChoiceRefusalsOnly = (toolChoiceRefusalsOnly ?? true) && isMandatoryToolChoiceRefusal(failure.response);
1379
1385
  // A real target failure ends the session pin; the next turn is decided afresh (#7525).
1380
1386
  jevPin?.forget();
1381
1387
  if (!quotaFailure && (lastFailure.status === 429 || lastFailure.status === 402)) {
@@ -1401,6 +1407,7 @@ export async function executeComboResponses(
1401
1407
  // send that already ran the turn, so no later target may receive it, whatever its status says.
1402
1408
  const failureDecision = failure.nonReplayable || spentReplacement
1403
1409
  ? "stop"
1410
+ : isPolicyCandidateRefusal(failure.response) ? "hop"
1404
1411
  : comboFailureDecision(failure.response.status, failure.classificationText, {
1405
1412
  code: failure.upstreamCode,
1406
1413
  codexModelRefusal: failure.codexModelRefusal,
@@ -1473,7 +1480,7 @@ export async function executeComboResponses(
1473
1480
  );
1474
1481
  const failureNow = Date.now();
1475
1482
  const attemptedTargets = pick.attempted;
1476
- const failureCooldownScope = comboFailureCooldownScope(failure.response.status, failure.classificationText, {
1483
+ const failureCooldownScope = isPolicyCandidateRefusal(failure.response) ? "none" : comboFailureCooldownScope(failure.response.status, failure.classificationText, {
1477
1484
  code: failure.upstreamCode,
1478
1485
  });
1479
1486
  const failedTargetKey = targetKey(pick.target);
@@ -1584,7 +1591,7 @@ export async function executeComboResponses(
1584
1591
  if (!initialSend?.producerOwned) initialSend?.permit.release();
1585
1592
  }
1586
1593
  }
1587
- const failure = exhaustedFailure();
1594
+ const failure = exhaustedFailure(true);
1588
1595
  if (
1589
1596
  failure === lastFailure && lastFailure?.status === 413
1590
1597
  && lastFailureClassifiesOverflow
@@ -1,6 +1,7 @@
1
1
  import { carryProxyError } from "../../lib/client-error-body";
2
2
  import type { TranslatorBudget } from "../../lib/translator-budget";
3
3
  import { carryResponseToolOwnership } from "./response-tool-ownership";
4
+ import { carryPolicyCandidateRefusal } from "./policy-request-scope";
4
5
  import { finalizeTranslatorBudgetResponse } from "../../lib/translator-budget";
5
6
  import { carryReplayRefusal, isNonReplayableResponse, markResponseNonReplayable } from "../../lib/upstream-retry";
6
7
  import { isVerifiedModelNotInPlanResponse, markVerifiedModelNotInPlanResponse } from "../../lib/errors";
@@ -57,6 +58,7 @@ export function finalizeOwnedTranslatorBudget(response: Response, budget: Transl
57
58
  if (isVerifiedModelNotInPlanResponse(response)) markVerifiedModelNotInPlanResponse(finalizedResponse);
58
59
  if (runTurnAdapterSseResponses.has(response)) runTurnAdapterSseResponses.add(finalizedResponse);
59
60
  carryCodexAccountCooldownResponse(response, finalizedResponse);
61
+ carryPolicyCandidateRefusal(response, finalizedResponse);
60
62
  return carryResponseToolOwnership(response, carryFormattedQuotaSource(response, finalizedResponse));
61
63
  }
62
64
 
@@ -86,6 +88,7 @@ export function finalizeAccountLease(response: Response, release: () => void, on
86
88
  if (runTurnAdapterSseResponses.has(response)) runTurnAdapterSseResponses.add(wrapped);
87
89
  // Retained compaction delivers through this lease wrapper; keep a local cooldown refusal local (#7850).
88
90
  carryCodexAccountCooldownResponse(response, wrapped);
91
+ carryPolicyCandidateRefusal(response, wrapped);
89
92
  return carryResponseToolOwnership(response, carryReplayRefusal(response, carryFormattedQuotaSource(response, wrapped)));
90
93
  }
91
94
 
@@ -1,4 +1,6 @@
1
- import type { PhysicalSendReporter } from "../../lib/request-execution-budget";
1
+ import type { PhysicalSendReporter, SingleUseDispatchPermit } from "../../lib/request-execution-budget";
2
+ import { SendBudgetExhaustedError } from "../../lib/upstream-retry";
3
+ import type { ErrorDestinationLabel } from "../../lib/error-destination";
2
4
 
3
5
  /** Retry thunks can fail in pacing; settle only starts admitted at the physical executor. */
4
6
  export function deferPhysicalSendReporter(physical: PhysicalSendReporter) {
@@ -23,3 +25,18 @@ export function deferPhysicalSendReporter(physical: PhysicalSendReporter) {
23
25
  },
24
26
  };
25
27
  }
28
+
29
+ /** Keep legacy reporting unless a negotiated leg confirms its reservation at the physical send. */
30
+ export function physicalSendAccounting(reporter: PhysicalSendReporter, deferred?: {
31
+ destination: () => ErrorDestinationLabel; permit?: SingleUseDispatchPermit;
32
+ }) {
33
+ const pending = deferred ? deferPhysicalSendReporter(reporter) : undefined;
34
+ let permitDispatched = false;
35
+ return { report: pending?.report ?? reporter, onPhysicalDispatch: pending ? () => {
36
+ if (permitDispatched) throw new SendBudgetExhaustedError(deferred!.destination());
37
+ if (!pending.beforeDispatch() || deferred?.permit && !deferred.permit.use()) {
38
+ throw new SendBudgetExhaustedError(deferred!.destination());
39
+ }
40
+ permitDispatched = Boolean(deferred?.permit);
41
+ } : undefined };
42
+ }
@@ -58,9 +58,13 @@ export type AccountAutoPauseObserver = ((response: Response) => Promise<Response
58
58
  physical?: (sameDestination: boolean, headers: Headers) => void;
59
59
  };
60
60
  /** Init fragment that reports the final send of the observer's attempt; empty when nothing observes. */
61
- export function physicalSendObserverInit(observer: AccountAutoPauseObserver | undefined, target: string): Record<symbol, unknown> {
61
+ export function physicalSendObserverInit(observer: AccountAutoPauseObserver | undefined, target: string, onPhysicalSend?: () => void): Record<symbol, unknown> {
62
62
  const physical = observer?.physical;
63
- return physical ? { [PHYSICAL_SEND_OBSERVER]: (destination: string, headers: Headers) => physical(destination === target, headers) } : {};
63
+ let noted = false;
64
+ return physical || onPhysicalSend ? { [PHYSICAL_SEND_OBSERVER]: (destination: string, headers: Headers) => {
65
+ if (onPhysicalSend && !noted) { onPhysicalSend(); noted = true; }
66
+ physical?.(destination === target, headers);
67
+ } } : {};
64
68
  }
65
69
  // One WS attempt and its HTTP fallback are one logical physical-send receipt.
66
70
  const WS_FALLBACK_RECEIPT = Symbol.for("opencodex.ws-fallback-receipt");
@@ -285,6 +289,8 @@ export interface ProviderFetchOptions {
285
289
  beforeDispatch?: (headers: Headers) => void;
286
290
  /** One-shot receipt after final local HTTP admission, immediately before executor entry. */
287
291
  onPhysicalDispatch?: () => void;
292
+ /** Repeatable admission for native successor creates, after pacing and auth checks. */
293
+ onContinuationDispatch?: (frame: { body: Record<string, unknown>; text: string }) => void;
288
294
  /**
289
295
  * Opt-in (#6969): let a Codex WebSocket send hold empty lifecycle frames so an authoritative
290
296
  * upstream refusal before any output settles as a replayable gateway status. Only a caller that
@@ -420,7 +426,7 @@ export function providerFetch(
420
426
  const wsSend = codexWsExecutor((url: Parameters<typeof globalThis.fetch>[0], wsInit?: RequestInit) => codexWsUpstreamFetch(String(url),
421
427
  { ...(wsInit ?? init), [TURN_STATE_BINDING_INIT]: turnStateBinding(providerName, sendHeaders(wsInit ?? init)) } as RequestInit,
422
428
  fallback, runtime, options.onCodexWsQuota, options.beforeDispatch, options.nativeControl,
423
- async () => { (await waitForPacing(init.signal ?? undefined))?.release(); }, notifyOnce, options.preOutputRefusalHold),
429
+ async () => { (await waitForPacing(init.signal ?? undefined))?.release(); }, notifyOnce, options.preOutputRefusalHold, options.onContinuationDispatch),
424
430
  { provider, http: markEgressTransparentExecutor(fallback) });
425
431
  // A WS frame is a physical send like any other, so it runs the same override: that is where a
426
432
  // key-auth send is committed to its attempt row and the send budget is rebound to the
@@ -0,0 +1,8 @@
1
+ /** An internally constructed local refusal after a native response has already started. */
2
+ export class NativeContinuationRefusalError extends Error {
3
+ /** Keep the original response's process-local provenance and refusal headers. */
4
+ constructor(readonly response: Response) {
5
+ super("Native continuation refused before dispatch");
6
+ this.name = "NativeContinuationRefusalError";
7
+ }
8
+ }
@@ -0,0 +1,34 @@
1
+ import { formatErrorResponse } from "../../bridge";
2
+ import { markProxyError } from "../../lib/client-error-body";
3
+ import type { PhysicalSendReporter } from "../../lib/request-execution-budget";
4
+ import { SendBudgetExhaustedError } from "../../lib/upstream-retry";
5
+ import type { RequestLogContext } from "../request-log";
6
+ import { workflowSendCeilingRefusalResponse, workflowRefusalResponse } from "../workflow-refusal";
7
+ import { NativeContinuationRefusalError } from "./native-continuation-refusal";
8
+ import type { RequestSpendTracker } from "./request-spend";
9
+ import type { ResponsesSendBudget } from "./request-send-budget";
10
+
11
+ /** Every native-capable leg admits the reconstructed successor as a new physical send. */
12
+ export function createNativeContinuationDispatch(
13
+ budget: Pick<ResponsesSendBudget, "continuationSendReporter" | "workflowRootId">,
14
+ logCtx: RequestLogContext,
15
+ ): (frame: { body: Record<string, unknown>; text: string }) => void {
16
+ return frame => claimNativeContinuationSend(budget.continuationSendReporter(frame), logCtx, budget.workflowRootId);
17
+ }
18
+
19
+ /** Claim one successor's physical start; never borrow an initial or recovery receipt. */
20
+ export function claimNativeContinuationSend(reporter: PhysicalSendReporter, logCtx: RequestLogContext, rootId?: string): void {
21
+ const tracker = logCtx.spendTracker as RequestSpendTracker | undefined;
22
+ const before = tracker?.refusals ?? 0;
23
+ try {
24
+ if (reporter.beforeSend?.() === false) {
25
+ const denied = tracker && tracker.refusals > before ? tracker.lastRefusal : undefined;
26
+ const refusal = (denied ? workflowRefusalResponse(denied.reason, logCtx, undefined, undefined, denied.spend) : undefined)
27
+ ?? workflowSendCeilingRefusalResponse(logCtx, rootId)
28
+ ?? markProxyError(formatErrorResponse(429, "request_send_budget_exhausted", new SendBudgetExhaustedError().message));
29
+ logCtx.terminalHttpStatus = refusal.status;
30
+ throw new NativeContinuationRefusalError(refusal);
31
+ }
32
+ reporter(1);
33
+ } finally { reporter.close?.(); }
34
+ }
@@ -1,5 +1,6 @@
1
1
  import { clientFacingModelText } from "../../lib/error-destination";
2
2
  import { projectLocalModelRefusalLog } from "../request-log-failure-detail";
3
+ import { carryPolicyCandidateRefusal } from "./policy-request-scope";
3
4
  import { markProxyError, rememberProxyErrorMessage, carryProxyError } from "../../lib/client-error-body";
4
5
  import { releaseRequestOwnedMainOnOutcome, isKeyedRequestOwnedMain } from "../../codex/request-owned-affinity";
5
6
  import { wasPermanentAccountRefusal } from "../../oauth/account-auto-pause";
@@ -17,6 +18,7 @@ import type { ResponsesTransport } from "./request-transport";
17
18
  import type { ResponsesSidecarAuth } from "./request-sidecar-auth";
18
19
  import type { ResponsesEffects } from "./response-effects";
19
20
  import type { PassthroughExchange } from "./passthrough-dispatch";
21
+ import type { AuxiliaryModelSend } from "../../lib/request-execution-budget";
20
22
  import {
21
23
  sanitizePassthroughHeaders,
22
24
  createSseInspector,
@@ -432,6 +434,7 @@ export async function deliverPassthroughResponse(
432
434
  | "localUpstream"
433
435
  | "terminalOutcomeRecorded"
434
436
  >,
437
+ dispatchSidecarSend?: AuxiliaryModelSend,
435
438
  ): Promise<Response> {
436
439
  const { route } = requestState;
437
440
  // The proof must belong to the response whose headers are published.
@@ -662,13 +665,13 @@ export async function deliverPassthroughResponse(
662
665
  turnAdmissionLease: options.turnAdmissionLease,
663
666
  });
664
667
  if (policyRefusal) return policyRefusal;
665
- return carryProxyError(upstreamResponse, formatPassthroughUpstreamError(upstreamResponse.status, errorText, {
668
+ return carryPolicyCandidateRefusal(upstreamResponse, carryProxyError(upstreamResponse, formatPassthroughUpstreamError(upstreamResponse.status, errorText, {
666
669
  statusText: upstreamResponse.statusText,
667
670
  headers,
668
671
  // Provenance, not inference: `errorText` is empty when the bounded read finds nothing
669
672
  // display-safe, and an empty body is exactly what the retryable-429 default fires on.
670
673
  replayRefusal: isReplayRefusalResponse(upstreamResponse),
671
- }));
674
+ })));
672
675
  }
673
676
 
674
677
  if (options.nativeControl && isNativeControlResponse(upstreamResponse) && upstreamResponse.body) {
@@ -782,6 +785,7 @@ export async function deliverPassthroughResponse(
782
785
  );
783
786
  },
784
787
  execute: createPassthroughWebSearchBridgeExecutor(webSearchBridgePlan, {
788
+ dispatchSidecarSend,
785
789
  providerApiKey: route.provider.apiKey ?? "",
786
790
  auth: webSearchBridgeAuth,
787
791
  hostedTool: parsed._webSearch,