@bitkyc08/opencodex 2.92.0 → 2.93.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 (258) hide show
  1. package/bin/ocx.mjs +10 -5
  2. package/gui/dist/assets/{App-sUf_8afJ.js → App-CizjBqyk.js} +18 -18
  3. package/gui/dist/assets/{Tray-BSsxznDm.js → Tray-DamiMqcX.js} +1 -1
  4. package/gui/dist/assets/{index-BlFE_VB_.js → index-DQsht3vH.js} +12 -12
  5. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  6. package/gui/dist/assets/{quota-summary-BRlbXgw0.js → quota-summary-BXu4zE8H.js} +1 -1
  7. package/gui/dist/index.html +2 -2
  8. package/package.json +5 -5
  9. package/src/adapters/anthropic.ts +28 -5
  10. package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
  11. package/src/adapters/coding-agent/profile.ts +54 -16
  12. package/src/adapters/coding-agent/turn.ts +30 -2
  13. package/src/adapters/command-code.ts +114 -7
  14. package/src/adapters/cursor/native-exec-fs.ts +11 -9
  15. package/src/adapters/devin/live-models.ts +4 -0
  16. package/src/adapters/google-wire-compiler.ts +1 -2
  17. package/src/adapters/kiro/reasoning.ts +2 -0
  18. package/src/adapters/kiro-refusal.ts +6 -1
  19. package/src/adapters/kiro-wire.ts +1 -1
  20. package/src/adapters/openai-chat/messages.ts +8 -2
  21. package/src/adapters/openai-chat/passthrough.ts +35 -14
  22. package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
  23. package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
  24. package/src/adapters/openai-chat/required-tool-result.ts +64 -0
  25. package/src/adapters/openai-chat.ts +7 -8
  26. package/src/adapters/openai-responses/passthrough.ts +7 -4
  27. package/src/adapters/openai-responses/reasoning.ts +13 -0
  28. package/src/adapters/openai-responses/request-strips.ts +1 -1
  29. package/src/adapters/qoder/adapter.ts +129 -8
  30. package/src/adapters/qoder/scaffold-guard.ts +5 -0
  31. package/src/adapters/reasoning-controls.ts +16 -0
  32. package/src/adapters/tool-call-id.ts +1 -3
  33. package/src/bridge/errors.ts +27 -0
  34. package/src/bridge.ts +1 -1
  35. package/src/chat/inbound.ts +4 -1
  36. package/src/chat/outbound.ts +9 -2
  37. package/src/chat/reasoning-details.ts +28 -5
  38. package/src/claude/desktop-first-party.ts +54 -4
  39. package/src/claude/desktop-picker.ts +11 -8
  40. package/src/claude/first-party-settings.ts +3 -1
  41. package/src/claude/inbound.ts +2 -1
  42. package/src/claude/intercept/local-ca.ts +2 -1
  43. package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
  44. package/src/claude/intercept/picker-ca-startup.ts +3 -1
  45. package/src/claude/intercept/picker-models.ts +6 -3
  46. package/src/claude/intercept/picker-runtime.ts +3 -2
  47. package/src/claude/intercept/runtime.ts +6 -3
  48. package/src/claude/model-info.ts +31 -8
  49. package/src/cli/account-api.ts +11 -0
  50. package/src/cli/capabilities-agents-routing.ts +2 -2
  51. package/src/cli/capabilities-base.ts +7 -1
  52. package/src/cli/capabilities-observe-system.ts +10 -0
  53. package/src/cli/claude-desktop.ts +9 -8
  54. package/src/cli/claude.ts +3 -2
  55. package/src/cli/codex-shim-autorestore.ts +9 -0
  56. package/src/cli/combo-result.ts +7 -0
  57. package/src/cli/combo.ts +18 -0
  58. package/src/cli/cross-home-owner.ts +13 -1
  59. package/src/cli/dispatch.ts +25 -6
  60. package/src/cli/ensure-desired-integrations.ts +8 -6
  61. package/src/cli/export-command.ts +4 -1
  62. package/src/cli/help.ts +2 -1
  63. package/src/cli/index.ts +45 -45
  64. package/src/cli/integration-plan-dto.ts +4 -0
  65. package/src/cli/opencode.ts +20 -9
  66. package/src/cli/registry.ts +6 -4
  67. package/src/cli/root.ts +9 -0
  68. package/src/cli/status.ts +59 -1
  69. package/src/cli/stop-restore.ts +113 -0
  70. package/src/cli/sync-expectation.ts +60 -0
  71. package/src/cli/uninstall-integrations.ts +41 -7
  72. package/src/client/connect.ts +40 -3
  73. package/src/client/link-home.ts +10 -1
  74. package/src/client/machine-api.ts +3 -1
  75. package/src/client/sync-expectation.ts +118 -0
  76. package/src/clients/config-export/agent-clients.ts +96 -0
  77. package/src/clients/config-export/contracts.ts +25 -7
  78. package/src/clients/config-export/qoder.ts +38 -23
  79. package/src/clients/config-export/reasoning-metadata.ts +55 -8
  80. package/src/clients/config-export.ts +12 -0
  81. package/src/clients/lazycodex.ts +7 -2
  82. package/src/clients/reasoning-controls.ts +49 -0
  83. package/src/codex/auth-api/account-identity.ts +14 -0
  84. package/src/codex/auth-api/account-list.ts +29 -2
  85. package/src/codex/auth-api/http.ts +13 -0
  86. package/src/codex/auth-api/main-account-probe.ts +2 -2
  87. package/src/codex/auth-api/pool-mode-gate.ts +16 -3
  88. package/src/codex/auth-api/pool-quota-probe.ts +15 -0
  89. package/src/codex/auth-context.ts +15 -12
  90. package/src/codex/catalog/build-entries.ts +22 -0
  91. package/src/codex/catalog/configured-tiers.ts +70 -0
  92. package/src/codex/catalog/effort.ts +44 -10
  93. package/src/codex/catalog/gather-capture.ts +1 -0
  94. package/src/codex/catalog/heal-observation.ts +155 -13
  95. package/src/codex/catalog/metadata.ts +6 -0
  96. package/src/codex/catalog/model-hints.ts +60 -11
  97. package/src/codex/catalog/model-visibility.ts +3 -2
  98. package/src/codex/catalog/native-models.ts +18 -3
  99. package/src/codex/catalog/parsing.ts +10 -8
  100. package/src/codex/catalog/pinned-models.ts +2 -1
  101. package/src/codex/catalog/provider-models.ts +4 -5
  102. package/src/codex/catalog/retained-sync.ts +2 -1
  103. package/src/codex/catalog/routed-gather.ts +19 -20
  104. package/src/codex/catalog/write-audit.ts +3 -2
  105. package/src/codex/catalog-self-heal.ts +43 -23
  106. package/src/codex/collision-identity.ts +30 -5
  107. package/src/codex/convergence.ts +4 -3
  108. package/src/codex/data/roster-pinned-models.json +177 -1
  109. package/src/codex/desired-state.ts +6 -1
  110. package/src/codex/desktop-compatibility/installed-build.ts +88 -12
  111. package/src/codex/desktop-compatibility/runtime.ts +29 -5
  112. package/src/codex/desktop-compatibility/usage-controller.ts +2 -0
  113. package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
  114. package/src/codex/inject/config-toml.ts +0 -18
  115. package/src/codex/inject/plan.ts +18 -3
  116. package/src/codex/inject/remove.ts +6 -2
  117. package/src/codex/inject.ts +1 -1
  118. package/src/codex/journal.ts +61 -1
  119. package/src/codex/model-entitlements.ts +1 -1
  120. package/src/codex/native-main-owner.ts +27 -1
  121. package/src/codex/native-profile-store.ts +2 -1
  122. package/src/codex/pool-credit-policy.ts +35 -1
  123. package/src/codex/quota-types.ts +3 -0
  124. package/src/codex/quota.ts +24 -4
  125. package/src/codex/role-auto-assign.ts +6 -2
  126. package/src/codex/subagent-defaults.ts +49 -4
  127. package/src/combos/failover.ts +17 -2
  128. package/src/combos/jev-decision-contract.ts +22 -1
  129. package/src/combos/jev-service-exchange.ts +3 -1
  130. package/src/combos/jev.ts +95 -9
  131. package/src/combos/resolve.ts +45 -1
  132. package/src/combos/types.ts +24 -0
  133. package/src/config/load-degrade.ts +5 -0
  134. package/src/config/paths.ts +19 -3
  135. package/src/config/pending-teardown.ts +22 -1
  136. package/src/config/provider-validation.ts +15 -4
  137. package/src/config/removed-opencode-free.ts +11 -0
  138. package/src/config/schema/leaf-validators.ts +5 -0
  139. package/src/generated/compatibility-version.json +314 -230
  140. package/src/generated/model-metadata.ts +5 -5
  141. package/src/images/loop.ts +16 -2
  142. package/src/integrations/catalog-refresh.ts +1 -1
  143. package/src/integrations/hermes-profiles.ts +251 -0
  144. package/src/integrations/merge.ts +8 -0
  145. package/src/integrations/mutation-plan.ts +19 -4
  146. package/src/integrations/registry.ts +5 -0
  147. package/src/integrations/state.ts +36 -1
  148. package/src/integrations/writer.ts +18 -4
  149. package/src/lib/bun-path-runtime.mjs +2 -1
  150. package/src/lib/errors.ts +62 -0
  151. package/src/lib/eventstream-decoder.ts +81 -37
  152. package/src/lib/opaque-proxy-tunnel.ts +32 -8
  153. package/src/lib/pinned-http.ts +35 -2
  154. package/src/lib/process-control.ts +13 -1
  155. package/src/lib/socks5-fetch.ts +59 -64
  156. package/src/lib/socks5-upload-waiter.ts +50 -0
  157. package/src/lib/sse-decoder.ts +7 -2
  158. package/src/lib/state-store-sweeper.ts +40 -14
  159. package/src/lib/windows-native-principal-worker.ts +14 -0
  160. package/src/lib/windows-native-principal.ts +188 -0
  161. package/src/lib/windows-secret-acl.ts +39 -3
  162. package/src/lib/windows-user-principal.ts +62 -18
  163. package/src/link/ssh-config.ts +35 -3
  164. package/src/providers/account-quota-disk.ts +12 -4
  165. package/src/providers/codebuddy-models.ts +6 -0
  166. package/src/providers/codex-capacity.ts +3 -1
  167. package/src/providers/derive.ts +28 -0
  168. package/src/providers/kiro-models.ts +3 -0
  169. package/src/providers/mimo-thinking.ts +12 -0
  170. package/src/providers/model-rename-fields.ts +1 -0
  171. package/src/providers/model-rename-migration.ts +10 -0
  172. package/src/providers/openai-sidecar-credit.ts +2 -2
  173. package/src/providers/reasoning-capabilities.ts +76 -0
  174. package/src/providers/registry/entries-core.ts +14 -12
  175. package/src/providers/registry/entries-extended.ts +63 -20
  176. package/src/providers/registry/model-ids.ts +2 -0
  177. package/src/providers/registry/model-seeds.ts +93 -28
  178. package/src/providers/registry/types.ts +10 -1
  179. package/src/providers/resolved-model-policy.ts +26 -6
  180. package/src/providers/routed-config.ts +9 -1
  181. package/src/providers/stale-model-roster-migration.ts +44 -7
  182. package/src/remote-control/workspace-pi-runtime.ts +11 -6
  183. package/src/responses/compaction-summary.ts +45 -0
  184. package/src/responses/muse-tool-name-alias.ts +1 -2
  185. package/src/responses/parser.ts +3 -2
  186. package/src/responses/schema.ts +1 -0
  187. package/src/responses/thought-signature-replay.ts +10 -2
  188. package/src/routing/capability.ts +8 -2
  189. package/src/routing/history/ingest.ts +28 -3
  190. package/src/server/auth-cors.ts +3 -2
  191. package/src/server/chat-completions.ts +7 -0
  192. package/src/server/chat-native-eligibility.ts +7 -0
  193. package/src/server/chat-native-reasoning.ts +14 -4
  194. package/src/server/direct-local-http.ts +5 -2
  195. package/src/server/effort-policy.ts +5 -1
  196. package/src/server/index/live-sideband.ts +18 -15
  197. package/src/server/index/serve-options.ts +5 -4
  198. package/src/server/management/agent-settings-routes.ts +27 -15
  199. package/src/server/management/combo-routes.ts +4 -0
  200. package/src/server/management/config-routes.ts +2 -2
  201. package/src/server/management/decision-discovery.ts +12 -2
  202. package/src/server/management/hermes-profile-routes.ts +156 -0
  203. package/src/server/management/integration-routes.ts +85 -24
  204. package/src/server/management/model-routes.ts +2 -2
  205. package/src/server/management/model-row-export-metadata.ts +25 -6
  206. package/src/server/management/model-rows.ts +15 -20
  207. package/src/server/management/native-integration-routes.ts +11 -8
  208. package/src/server/management/route-registry.ts +4 -0
  209. package/src/server/management-api.ts +5 -0
  210. package/src/server/models-capabilities.ts +21 -3
  211. package/src/server/responses/adapter-delivery.ts +11 -1
  212. package/src/server/responses/adapter-dispatch.ts +2 -2
  213. package/src/server/responses/codex-ws-exchange.ts +39 -9
  214. package/src/server/responses/codex-ws-session.ts +38 -4
  215. package/src/server/responses/codex-ws-wire.ts +6 -1
  216. package/src/server/responses/combo-required-tool-contract.ts +103 -0
  217. package/src/server/responses/combo-stream-preflight.ts +8 -1
  218. package/src/server/responses/compact.ts +4 -3
  219. package/src/server/responses/context-overflow.ts +8 -1
  220. package/src/server/responses/core-combo-failure.ts +10 -0
  221. package/src/server/responses/core-combo.ts +23 -15
  222. package/src/server/responses/core-lifetime.ts +3 -0
  223. package/src/server/responses/core-normalize.ts +11 -1
  224. package/src/server/responses/core-options.ts +2 -0
  225. package/src/server/responses/main-hard-lock-routing.ts +60 -44
  226. package/src/server/responses/passthrough-delivery.ts +40 -2
  227. package/src/server/responses/policy-fallback.ts +6 -1
  228. package/src/server/responses/request-compression.ts +12 -7
  229. package/src/server/responses/request-prepare.ts +22 -2
  230. package/src/server/responses/request-sidecar-auth.ts +2 -0
  231. package/src/server/responses/response-effects.ts +22 -10
  232. package/src/server/responses/sidecar-execution.ts +11 -3
  233. package/src/server/stop-teardown.ts +36 -1
  234. package/src/server/ws-bridge.ts +1 -1
  235. package/src/service/desktop-supervision.d.mts +7 -4
  236. package/src/service/desktop-supervision.mjs +90 -13
  237. package/src/service/ownership-mutation-lease.mjs +21 -7
  238. package/src/types/config.ts +8 -2
  239. package/src/types/provider.ts +20 -6
  240. package/src/types/request.ts +10 -0
  241. package/src/types.ts +1 -0
  242. package/src/update/bind-probe.ts +29 -0
  243. package/src/update/job.ts +10 -29
  244. package/src/update/npm-install-job.ps1 +173 -0
  245. package/src/update/npm-install.mjs +70 -0
  246. package/src/update/stop-contract.d.mts +1 -0
  247. package/src/update/stop-contract.mjs +14 -0
  248. package/src/update/stop-decision.d.mts +1 -1
  249. package/src/update/stop-decision.mjs +13 -3
  250. package/src/update/teardown-handover.ts +166 -0
  251. package/src/update/transactional-install.d.mts +14 -3
  252. package/src/update/transactional-install.mjs +33 -7
  253. package/src/usage/expected-prices.ts +64 -31
  254. package/src/usage/timeline.ts +19 -9
  255. package/src/vision/eligibility.ts +15 -5
  256. package/src/vision/plan.ts +2 -2
  257. package/src/web-search/loop.ts +16 -2
  258. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
@@ -0,0 +1,103 @@
1
+ import { REQUIRED_TOOL_CONTRACT_CODE } from "../../lib/errors";
2
+ import { applyReplayRefusalClientHeaders, isNonReplayableResponse, markResponseNonReplayable } from "../../lib/upstream-retry";
3
+ import { clientWireOf } from "../inference/client-wire";
4
+ import { isPreinspectedJsonResponse, markPreinspectedJsonResponse } from "../relay";
5
+ import { isAuthorizedProviderExecutedCall } from "../responses-undeclared-tool-guard";
6
+ import { carryResponseToolOwnership, responseToolOwnership } from "./response-tool-ownership";
7
+
8
+ export type RequiredToolContract =
9
+ | { kind: "any"; hostedCallTypes: ReadonlySet<string> }
10
+ | { kind: "named"; name: string };
11
+
12
+ const hostedCalls = new Map([
13
+ ["web_search", "web_search_call"], ["web_search_preview", "web_search_call"],
14
+ ["file_search", "file_search_call"], ["code_interpreter", "code_interpreter_call"],
15
+ ["image_generation", "image_generation_call"], ["image_gen", "image_generation_call"],
16
+ ["mcp", "mcp_call"], ["computer_use", "computer_call"],
17
+ ["computer_use_preview", "computer_call"],
18
+ ]);
19
+
20
+ /** Unknown declarations abstain: their successful output spelling is not ours to guess. */
21
+ export function requiredToolContractOf(rawBody: unknown): RequiredToolContract | undefined {
22
+ if (!rawBody || typeof rawBody !== "object" || Array.isArray(rawBody)) return;
23
+ const { tools, tool_choice: choice } = rawBody as Record<string, unknown>;
24
+ if (!Array.isArray(tools) || tools.length === 0) return;
25
+ if (choice === "required") {
26
+ const hostedCallTypes = new Set<string>();
27
+ for (const tool of tools) {
28
+ if (!tool || typeof tool !== "object" || Array.isArray(tool)) return;
29
+ const type = (tool as Record<string, unknown>).type;
30
+ if (type === "function" || type === "custom") continue;
31
+ const callType = typeof type === "string" ? hostedCalls.get(type) : undefined;
32
+ if (!callType) return;
33
+ hostedCallTypes.add(callType);
34
+ }
35
+ return { kind: "any", hostedCallTypes };
36
+ }
37
+ if (choice && typeof choice === "object" && !Array.isArray(choice)) {
38
+ const named = choice as Record<string, unknown>;
39
+ if ((named.type === "function" || named.type === "custom")
40
+ && typeof named.name === "string" && named.name.trim()) {
41
+ return { kind: "named", name: named.name };
42
+ }
43
+ }
44
+ }
45
+
46
+ /** Only a parsed completed output array can prove a missing required call. */
47
+ export async function judgeBufferedRequiredTool(response: Response, requirement: RequiredToolContract): Promise<Response> {
48
+ const text = await response.text();
49
+ let payload: Record<string, unknown> | undefined;
50
+ try {
51
+ const parsed: unknown = JSON.parse(text);
52
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) payload = parsed as Record<string, unknown>;
53
+ } catch { /* An opaque body is not evidence of a required-tool violation. */ }
54
+ const output = payload?.output;
55
+ if (payload?.status === "completed" && Array.isArray(output)) {
56
+ const calls = output.filter((item): item is Record<string, unknown> =>
57
+ !!item && typeof item === "object" && !Array.isArray(item));
58
+ const ownership = responseToolOwnership(response);
59
+ const providerExecuted = (call: Record<string, unknown>) =>
60
+ ownership !== undefined && isAuthorizedProviderExecutedCall(call, ownership);
61
+ const satisfied = calls.some(call => {
62
+ if (requirement.kind === "any" && requirement.hostedCallTypes.has(String(call.type))) return true;
63
+ if (providerExecuted(call)) return false;
64
+ if (call.type !== "function_call" && call.type !== "custom_tool_call") return false;
65
+ // Name-less calls cannot prove a selected-name mismatch.
66
+ return requirement.kind === "any" || typeof call.name !== "string" || call.name === requirement.name;
67
+ });
68
+ if (!satisfied) {
69
+ const hostedEffect = calls.some(call => providerExecuted(call)
70
+ || (typeof call.type === "string" && call.type.endsWith("_call")
71
+ && call.type !== "function_call" && call.type !== "custom_tool_call"));
72
+ const failure = Response.json({
73
+ error: {
74
+ type: "upstream_error", code: REQUIRED_TOOL_CONTRACT_CODE,
75
+ message: "Target completed the response without the tool call required by tool_choice",
76
+ },
77
+ ...(payload.usage !== undefined ? { usage: payload.usage } : {}),
78
+ }, { status: hostedEffect ? 400 : 502 });
79
+ // Hosted/unknown call items can already have executed remotely. Report the violation,
80
+ // but never buy another execution merely because the required client call is missing.
81
+ if (hostedEffect) {
82
+ markResponseNonReplayable(failure);
83
+ applyReplayRefusalClientHeaders(failure.headers);
84
+ }
85
+ return failure;
86
+ }
87
+ }
88
+ const headers = new Headers(response.headers);
89
+ headers.delete("content-encoding");
90
+ headers.delete("content-length");
91
+ const rebuilt = new Response(text, { status: response.status, statusText: response.statusText, headers });
92
+ if (isPreinspectedJsonResponse(response)) markPreinspectedJsonResponse(rebuilt);
93
+ return carryResponseToolOwnership(response, rebuilt);
94
+ }
95
+
96
+ /** Native buffered Responses only; translated Chat and runTurn retain their terminal owners. */
97
+ export async function guardBufferedComboRequiredTool(response: Response, rawBody: unknown, adapter?: string): Promise<Response> {
98
+ if (!response.ok || adapter !== "openai-responses" || clientWireOf(response) !== undefined
99
+ || isNonReplayableResponse(response)
100
+ || !(response.headers.get("content-type") ?? "").includes("application/json")) return response;
101
+ const requirement = requiredToolContractOf(rawBody);
102
+ return requirement ? judgeBufferedRequiredTool(response, requirement) : response;
103
+ }
@@ -29,6 +29,10 @@ const TERMINAL_EVENTS = new Set([
29
29
  "response.incomplete",
30
30
  ]);
31
31
 
32
+ // A failed terminal carrying one of these codes is a contract verdict, not a transient
33
+ // upstream failure: another target would spend a request the adapter already refused.
34
+ const NON_REPLAYABLE_FAILED_CODES = new Set(["required_tool_not_called"]);
35
+
32
36
  const RETRYABLE_ZERO_OUTPUT_INCOMPLETE_REASONS = new Set([
33
37
  "adapter_eof",
34
38
  "missing_terminal_event",
@@ -118,7 +122,10 @@ function retryableZeroOutputTerminal(payload: unknown): boolean {
118
122
  response?: { incomplete_details?: { reason?: unknown }; output?: unknown };
119
123
  };
120
124
  if (bareErrorIsRetryable(event)) return true;
121
- if (event.type === "response.failed") return true;
125
+ if (event.type === "response.failed") {
126
+ const code = (event.response as { error?: { code?: unknown } } | undefined)?.error?.code;
127
+ return !(typeof code === "string" && NON_REPLAYABLE_FAILED_CODES.has(code));
128
+ }
122
129
  if (event.type !== "response.incomplete") return false;
123
130
  const reason = event.response?.incomplete_details?.reason;
124
131
  // A terminal-only upstream can carry output without preceding delta/item events.
@@ -25,7 +25,7 @@ import { parseRequest } from "../../responses/parser";
25
25
  import { buildCompactV1Output, COMPACT_PROMPT, decodeCompactionSummary, extractCompactUserMessages } from "../../responses/compaction";
26
26
  import { applyReasoningRetention, appendRetentionNotice, type ReasoningRetentionResult } from "../../responses/reasoning-retention";
27
27
  import { FORWARD_HEADERS, sanitizeReasoningInputContent } from "../../adapters/openai-responses";
28
- import { stripProviderInputItemMetadata } from "../../adapters/openai-responses/request-strips";
28
+ import { repairUrlCitationAnnotations, stripProviderInputItemMetadata } from "../../adapters/openai-responses/request-strips";
29
29
  import { expandPreviousResponseInput, previousResponseProviderState, rememberResponseState } from "../../responses/state";
30
30
  import { repairLegacyDottedToolCallNames } from "../../responses/legacy-dotted-tool-name-repair";
31
31
  import { NoEligiblePolicyCandidateError, routeCompactionModel } from "../../router";
@@ -949,7 +949,7 @@ export async function handleResponsesCompact(
949
949
  // #5095: the compact endpoint forwards `raw` directly, so it needs the same legacy dotted
950
950
  // call-name repair the adapter applies. A damaged item here refuses the compaction itself,
951
951
  // which is the request a long task depends on to keep going.
952
- // This branch is OpenAI-only and bypasses the adapter's Google replay projection (#7111).
952
+ // Direct compact bypasses the adapter's Google replay projection (#7111).
953
953
  const compactBody = repairLegacyDottedToolCallNames(
954
954
  stripProviderInputItemMetadata(sanitizeReasoningInputContent(compactBodyRaw, {
955
955
  preserveRawReasoningContent: !isOpenAiOperatedResponsesDestination(compactProvider)
@@ -1160,8 +1160,9 @@ export async function handleResponsesCompact(
1160
1160
  if (!isOpenAiOperatedResponsesDestination(sendProvider) && sendProvider.preserveResponsesMessageMetadata !== true) {
1161
1161
  replayBody = stripInternalChatMessageMetadataPassthrough(replayBody) as typeof replayBody;
1162
1162
  }
1163
+ // A queued key selection can refresh the destination; project only for this send.
1163
1164
  return isOpenAiOperatedResponsesDestination(sendProvider)
1164
- ? replayBody : stripCanonicalOnlyInputItems(stripCanonicalOnlyTopLevelFields(replayBody));
1165
+ ? repairUrlCitationAnnotations(replayBody) : stripCanonicalOnlyInputItems(stripCanonicalOnlyTopLevelFields(replayBody));
1165
1166
  };
1166
1167
  const doFetch = (upstreamRecovery?: UpstreamSendRecovery) => fetchWithHeaderTimeout(
1167
1168
  compactUrl,
@@ -2,7 +2,7 @@ import { bridgeToResponsesSSE, formatErrorResponse } from "../../bridge";
2
2
  import { OLLAMA_LATE_ATTRIBUTION_LIMIT_MESSAGE } from "../../adapters/ollama-native";
3
3
  import { isThroughputLimitText } from "../../claude/outbound";
4
4
  import { isDefiniteContextOverflow } from "../../combos/failover";
5
- import { classifyError } from "../../lib/errors";
5
+ import { classifyError, MODEL_NOT_IN_PLAN_STREAM_CODE } from "../../lib/errors";
6
6
  import type { TranslatorBudget } from "../../lib/translator-budget";
7
7
  import type { AdapterEvent } from "../../types";
8
8
 
@@ -99,6 +99,8 @@ export interface SidecarLoopFailure {
99
99
  upstreamCode?: string;
100
100
  /** The failed response was marked non-replayable: the provider may already have run the turn. */
101
101
  nonReplayable?: boolean;
102
+ /** The failed response was a verified plan refusal; the loop's own envelope must carry the mark. */
103
+ verifiedPlanRefusal?: boolean;
102
104
  }
103
105
 
104
106
  /**
@@ -127,6 +129,11 @@ export function sidecarLoopOverflowEvent(
127
129
  export function sidecarLoopTerminalEvent(
128
130
  failure: SidecarLoopFailure,
129
131
  ): Extract<AdapterEvent, { type: "error" }> | undefined {
132
+ // A verified plan refusal in a later iteration lands inside an already committed 200 stream,
133
+ // where only a terminal refusal code ends the turn; `model_not_in_plan` would be reconnected.
134
+ if (failure.verifiedPlanRefusal && failure.event) {
135
+ return { ...failure.event, code: MODEL_NOT_IN_PLAN_STREAM_CODE, retryable: false };
136
+ }
130
137
  const overflow = sidecarLoopOverflowEvent(failure);
131
138
  if (overflow || failure.event) return overflow;
132
139
  if (classifyError(failure.status, "upstream_error", failure.message).code !== "context_length_exceeded") return undefined;
@@ -11,6 +11,9 @@ import {
11
11
  isCyberPolicyMessage,
12
12
  CYBER_POLICY_ERROR_CODE,
13
13
  CYBER_POLICY_FALLBACK_MESSAGE,
14
+ isModelNotInPlanRefusal,
15
+ markVerifiedModelNotInPlanResponse,
16
+ namesModelNotInPlanCode,
14
17
  } from "../../lib/errors";
15
18
  import { normalizeUpstreamErrorText } from "./core-errors";
16
19
  import { resolveClientRetryAfter } from "../../lib/retry-after";
@@ -54,6 +57,7 @@ export async function consumeComboFailure(
54
57
  // A local key-scope refusal is already the client's answer: rebuilding it as an upstream_error
55
58
  // would hide the stable model_not_allowed_for_key type clients branch on.
56
59
  let scopeRefusalBody: string | undefined;
60
+ let verifiedPlanRefusal = false;
57
61
  try {
58
62
  const body = await readBoundedResponseBody(response, { signal, reportUtf8Validity: serverError });
59
63
  // A 5xx body counts as quota or classification evidence only when it decoded as valid
@@ -73,6 +77,10 @@ export async function consumeComboFailure(
73
77
  if (utf8Trusted || isCyberPolicyCode(normalized.code) || isCyberPolicyMessage(normalized.safeText)) {
74
78
  classificationText = normalized.safeText;
75
79
  upstreamCode = codexAccountModelRefusalHardStopCode(response.status, body.text) ?? normalized.code;
80
+ // Only the adapter's own normalized refusal may claim the plan-refusal hop; another
81
+ // upstream echoing the code in any spelling keeps the meaning it had before, which was none.
82
+ if (namesModelNotInPlanCode(upstreamCode) && !isModelNotInPlanRefusal(response, upstreamCode)) upstreamCode = undefined;
83
+ verifiedPlanRefusal = isModelNotInPlanRefusal(response, upstreamCode);
76
84
  upstreamMessage = normalized.message;
77
85
  upstreamType = normalized.type;
78
86
  }
@@ -126,10 +134,12 @@ export async function consumeComboFailure(
126
134
  },
127
135
  );
128
136
  if (nonReplayable) markResponseNonReplayable(failureResponse);
137
+ if (verifiedPlanRefusal) markVerifiedModelNotInPlanResponse(failureResponse);
129
138
  carryAnthropicRefusalCredential(response, failureResponse);
130
139
  return {
131
140
  response: failureResponse,
132
141
  ...(nonReplayable ? { nonReplayable: true } : {}),
142
+ ...(verifiedPlanRefusal ? { verifiedPlanRefusal: true } : {}),
133
143
  classificationText,
134
144
  ...(codexModelRefusal !== undefined ? { codexModelRefusal } : {}),
135
145
  ...(normalizedUpstreamCode !== undefined ? { upstreamCode: normalizedUpstreamCode } : {}),
@@ -509,12 +509,14 @@ export async function executeComboResponses(
509
509
  const payloadEligible = (target: (typeof combo.targets)[number]): boolean =>
510
510
  comboPayloadReadable || !unreadableEncryptedAgentTask || canDecryptUnreadableAgentTask(target);
511
511
  const meteredAllowed = admissionMayUseMeteredComboTargets(config, options.admission, combo);
512
- const targetEligible = (target: (typeof combo.targets)[number]): boolean =>
512
+ // Recovery can replace unreadable encrypted input, but cannot relax other admission checks.
513
+ const recoveryEligible = (target: (typeof combo.targets)[number]): boolean =>
513
514
  (meteredAllowed || !target.metered)
514
515
  && (combo.strategy !== "jev" || target.provider !== JEV_PROVIDER_ID)
515
- && payloadEligible(target)
516
516
  && reasoningReplayEligible(target)
517
517
  && (protocolLanes?.pickable(target) ?? true);
518
+ const targetEligible = (target: (typeof combo.targets)[number]): boolean =>
519
+ payloadEligible(target) && recoveryEligible(target);
518
520
  const onlyReplayIncompatibleTargetsRemain = (excluded: Iterable<string> = []): boolean => {
519
521
  const excludedKeys = new Set(excluded);
520
522
  const remaining = combo.targets.filter(target => {
@@ -528,16 +530,13 @@ export async function executeComboResponses(
528
530
  let encryptedTaskRecoveryAttempted = false;
529
531
  let recoveryFailureReason: AgentTaskRecoveryFailureReason | undefined;
530
532
  let storedPool401ReplayDispatched = false;
533
+ const recovery = agentTaskRecoveryConfig(config);
534
+ const encryptedTaskRecoveryAdmitted = (options.inboundWire ?? "responses") === "responses"
535
+ && isThreadSpawnRequest(req.headers) && !!recovery && !options.comboAttempt;
531
536
  const recoverUnreadableEncryptedTask = async (): Promise<boolean> => {
532
537
  if (encryptedTaskRecoveryAttempted) return false;
533
538
  encryptedTaskRecoveryAttempted = true;
534
- const recovery = agentTaskRecoveryConfig(config);
535
- if (
536
- (options.inboundWire ?? "responses") !== "responses"
537
- || !isThreadSpawnRequest(req.headers)
538
- || !recovery
539
- || options.comboAttempt
540
- ) {
539
+ if (!encryptedTaskRecoveryAdmitted || !recovery) {
541
540
  discardEncryptedAgentTaskRecovery(
542
541
  req,
543
542
  (body as { input?: unknown } | undefined)?.input,
@@ -582,6 +581,7 @@ export async function executeComboResponses(
582
581
  const pickWithWait = (pickOptions: {
583
582
  exclude?: Iterable<string>;
584
583
  eligible?: (target: NonNullable<typeof combo>["targets"][number]) => boolean;
584
+ allowCooldownReprobe?: boolean;
585
585
  now?: number;
586
586
  }) => pickComboTargetWithWait(config, comboId, {
587
587
  ...pickOptions,
@@ -613,7 +613,11 @@ export async function executeComboResponses(
613
613
  : jevSessionPinScope({ combo, comboId, admission: options.admission, lane: sessionLaneIdFromRequest(req.headers) });
614
614
 
615
615
  if (unreadableEncryptedAgentTask && !pick) {
616
- pick = await pickWithWait({ now: initialNow });
616
+ pick = await pickWithWait({
617
+ eligible: recoveryEligible,
618
+ allowCooldownReprobe: encryptedTaskRecoveryAdmitted,
619
+ now: initialNow,
620
+ });
617
621
  if (!pick) {
618
622
  discardEncryptedAgentTaskRecovery(
619
623
  req,
@@ -624,7 +628,7 @@ export async function executeComboResponses(
624
628
  return options.abortSignal?.aborted
625
629
  ? clientCancelledResponse()
626
630
  : comboUnavailable(comboId, undefined,
627
- comboExclusionReasons(config, comboId, target => meteredAllowed || !target.metered));
631
+ comboExclusionReasons(config, comboId, recoveryEligible));
628
632
  }
629
633
  if (!(await recoverUnreadableEncryptedTask())) {
630
634
  return options.abortSignal?.aborted
@@ -855,8 +859,8 @@ export async function executeComboResponses(
855
859
  // The physical destination after provider aliases and blockedModelRedirects: hops are
856
860
  // classified by where the request really goes, not by the selector the combo names.
857
861
  const targetRoute = routeConcreteModel(config, `${pick.target.provider}/${pick.target.model}`);
858
- // The hard-lock rewrite may have previewed a different random pick. Enforce this actual
859
- // first destination against the locked source, after aliases and redirects resolve.
862
+ // Selection-free hard-lock preflight grants no hop. Enforce this actual first destination
863
+ // against the locked source, after aliases and redirects resolve.
860
864
  if (firstComboTarget && options.mainHardLockFallbackOverride) {
861
865
  const hop = guardFallbackHop(config, {
862
866
  site: "combo",
@@ -1258,6 +1262,7 @@ export async function executeComboResponses(
1258
1262
  : comboFailureDecision(failure.response.status, failure.classificationText, {
1259
1263
  code: failure.upstreamCode,
1260
1264
  codexModelRefusal: failure.codexModelRefusal,
1265
+ verifiedPlanRefusal: failure.verifiedPlanRefusal,
1261
1266
  // The adapter the failed leg actually resolved: a configured `kiro` provider can route a
1262
1267
  // model through another wire via `modelAdapters`, and an unresolved leg grants no hop.
1263
1268
  failedAdapter: childLog.providerAdapter,
@@ -1273,6 +1278,7 @@ export async function executeComboResponses(
1273
1278
  const recoveredTarget = await pickWithWait({
1274
1279
  exclude: pick.attempted,
1275
1280
  eligible: target => {
1281
+ if (!recoveryEligible(target)) return false;
1276
1282
  try {
1277
1283
  const route = routeConcreteModel(config, `${target.provider}/${target.model}`);
1278
1284
  return route.codexAccountMode === undefined
@@ -1361,10 +1367,11 @@ export async function executeComboResponses(
1361
1367
  const failedTargetCooled = failureCooldownScope !== "none"
1362
1368
  && failedTargetCooldownRecorded
1363
1369
  && isComboTargetInCooldown(comboId, pick.target, failureNow);
1364
- // Same target selector as the exclusionary pick below, minus `exclude`: the only
1365
- // difference is deliberate and is the whole point of the single-target retry.
1370
+ // Drop exclusions for the single-target retry, but wait for normal cooldown
1371
+ // expiry: an in-flight request cannot reserve a fresh recovery pass.
1366
1372
  const retryAfterCooldown = () =>
1367
1373
  pickWithWait({
1374
+ allowCooldownReprobe: false,
1368
1375
  eligible: targetEligible,
1369
1376
  now: failureNow,
1370
1377
  });
@@ -1406,6 +1413,7 @@ export async function executeComboResponses(
1406
1413
  if (unreadableEncryptedAgentTask && !comboPayloadReadable) {
1407
1414
  const recoveredTarget = await pickWithWait({
1408
1415
  exclude: attemptedTargets,
1416
+ eligible: recoveryEligible,
1409
1417
  now: failureNow,
1410
1418
  });
1411
1419
  if (recoveredTarget && await recoverUnreadableEncryptedTask()) {
@@ -2,6 +2,7 @@ import type { TranslatorBudget } from "../../lib/translator-budget";
2
2
  import { carryResponseToolOwnership } from "./response-tool-ownership";
3
3
  import { finalizeTranslatorBudgetResponse } from "../../lib/translator-budget";
4
4
  import { carryReplayRefusal, isNonReplayableResponse, markResponseNonReplayable } from "../../lib/upstream-retry";
5
+ import { isVerifiedModelNotInPlanResponse, markVerifiedModelNotInPlanResponse } from "../../lib/errors";
5
6
  import {
6
7
  isNativePassthroughSseResponse,
7
8
  markNativePassthroughSseResponse,
@@ -50,6 +51,7 @@ export function finalizeOwnedTranslatorBudget(response: Response, budget: Transl
50
51
  }
51
52
  if (isPreinspectedJsonResponse(response)) markPreinspectedJsonResponse(finalizedResponse);
52
53
  if (isNonReplayableResponse(response)) markResponseNonReplayable(finalizedResponse);
54
+ if (isVerifiedModelNotInPlanResponse(response)) markVerifiedModelNotInPlanResponse(finalizedResponse);
53
55
  if (runTurnAdapterSseResponses.has(response)) runTurnAdapterSseResponses.add(finalizedResponse);
54
56
  return carryResponseToolOwnership(response, finalizedResponse);
55
57
  }
@@ -72,6 +74,7 @@ export function finalizeAccountLease(response: Response, release: () => void, on
72
74
  });
73
75
  const wrapped = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
74
76
  if (isNonReplayableResponse(response)) markResponseNonReplayable(wrapped);
77
+ if (isVerifiedModelNotInPlanResponse(response)) markVerifiedModelNotInPlanResponse(wrapped);
75
78
  if (isNativePassthroughSseResponse(response)) markNativePassthroughSseResponse(wrapped);
76
79
  if (isEagerRelaySseResponse(response)) markEagerRelaySseResponse(wrapped);
77
80
  if (isPreinspectedJsonResponse(response)) markPreinspectedJsonResponse(wrapped);
@@ -1,4 +1,6 @@
1
1
  import { effectiveAzureOutputBudget } from "../../adapters/azure";
2
+ import { normalizeThinkingOptions } from "../../clients/reasoning-controls";
3
+ import { nativeEffortClamp, shouldApplyNativeEffortClamp } from "../../codex/catalog";
2
4
  import { sanitizeLogMetadataString } from "../../lib/redact";
3
5
  import type { RouteResult } from "../../router";
4
6
  import type { InboundWire } from "../../providers/registry";
@@ -341,6 +343,15 @@ export async function applyFinalRouteRequestNormalization(args: {
341
343
  }
342
344
 
343
345
  {
346
+ // Native passthrough keeps its snapshot-owned effort contract, including saved exclusions.
347
+ if (!shouldApplyNativeEffortClamp(route.providerName, route.provider, finalSelectedModelId)) {
348
+ const previousEffort = parsed.options.reasoning;
349
+ normalizeThinkingOptions(route.provider, route.modelId, parsed.options);
350
+ if (previousEffort !== undefined && parsed.options.reasoning === undefined) {
351
+ const raw = parsed._rawBody as { reasoning?: unknown } | undefined;
352
+ if (raw) raw.reasoning = stripEmptyLadderEffort(raw.reasoning, []);
353
+ }
354
+ }
344
355
  const { applyEffortCap, effortCapAppliesTo, supportedLadderFor } = await import("../effort-policy");
345
356
  const surface = collabSurface(parsed);
346
357
  if (effortCapAppliesTo(surface, req.headers, config, parsed._compactionRequest === true)) {
@@ -357,7 +368,6 @@ export async function applyFinalRouteRequestNormalization(args: {
357
368
  }
358
369
 
359
370
  {
360
- const { nativeEffortClamp, shouldApplyNativeEffortClamp } = await import("../../codex/catalog");
361
371
  const raw = parsed._rawBody as { reasoning?: { effort?: string } } | undefined;
362
372
  // The parser folds `ultra` to `max` only in options.reasoning; the passthrough adapter
363
373
  // serializes the raw body, so a raw `ultra` must reach the clamp itself (#7590).
@@ -49,6 +49,8 @@ export interface ConsumedComboFailure {
49
49
  * marker, so the combo loop reads it here and stops instead of sending the turn to a later target.
50
50
  */
51
51
  nonReplayable?: boolean;
52
+ /** The failed attempt was an adapter-normalized plan refusal; only this grants its combo hop. */
53
+ verifiedPlanRefusal?: boolean;
52
54
  }
53
55
 
54
56
 
@@ -1,8 +1,8 @@
1
1
  import type { OcxConfig } from "../../types";
2
- import { resolveComboId } from "../../combos";
2
+ import { getCombo, resolveComboId } from "../../combos";
3
3
  import { isBareOpenAiFamilyModel, previewRouteModel, routeConcreteModel } from "../../router";
4
4
  import { resolveChosenTarget } from "./shadow-target-availability";
5
- import { getRoutingProfile, resolvePolicyProfileId, type NormalizedRoutingProfile } from "../../routing/profile";
5
+ import { getRoutingProfile, resolvePolicyProfileId } from "../../routing/profile";
6
6
  import { NATIVE_RESERVE_MODEL } from "../../codex/catalog/native-models";
7
7
  import {
8
8
  getMainAccountHardLockStatus,
@@ -12,7 +12,10 @@ import { codexQuotaScopeForModel } from "../../codex/routing/health-store";
12
12
  import { getEligiblePoolAccounts } from "../../codex/routing/selection";
13
13
  import { OPENAI_CODEX_PROVIDER_ID, isCanonicalOpenAiForwardProvider } from "../../providers/openai-tiers";
14
14
  import { providerCodexAccountMode } from "../../providers/registry";
15
- import { FallbackRefusedError, guardFallbackHop, type FallbackAdmission, type FallbackTarget } from "../../routing/fallback-policy";
15
+ import {
16
+ FallbackRefusedError, fallbackDeviceIds, fallbackHopKind, guardFallbackHop, resolveFallbackPolicy,
17
+ type FallbackAdmission, type FallbackHop, type FallbackTarget,
18
+ } from "../../routing/fallback-policy";
16
19
  /** Resolves to a synchronous ownership proof, or null when the caller does not own the locked main. */
17
20
  export type MainHardLockCallerCheck = (sourceModel: string) => Promise<(() => boolean) | null>;
18
21
 
@@ -111,8 +114,26 @@ export async function applyMainHardLockFallbackOverride(
111
114
  // Combos and policies keep their own dispatch admission and declared failover/evidence.
112
115
  // Other chosen targets must resolve now; a removed qualifier cannot become a default send.
113
116
  const policyId = resolvePolicyProfileId(config, fallback.model);
114
- if (!isConfiguredComboSelector(config, fallback.model)
115
- && !(policyId && getRoutingProfile(config, policyId))) {
117
+ const profile = policyId ? getRoutingProfile(config, policyId) : undefined;
118
+ const comboId = resolveComboId(config, fallback.model);
119
+ const combo = comboId ? getCombo(config, comboId) : undefined;
120
+ if (profile || combo) {
121
+ // Match the actual first guard's selector order. This neither picks nor filters a target.
122
+ const denied = allDeclaredTargetsDenied(config, profile?.candidates ?? combo!.targets, {
123
+ site: "hard-lock",
124
+ route: profile ? parsed.model : `combo/${comboId}`,
125
+ aliases: profile ? [`policy/${policyId}`] : [parsed.model],
126
+ from: { provider: OPENAI_CODEX_PROVIDER_ID, model: parsed.model },
127
+ trigger: "hard_lock", admission, ...(now !== undefined ? { now } : {}),
128
+ });
129
+ if (denied) {
130
+ // One refusal witness for an all-denied declaration, never a speculative taken event.
131
+ const hop = guardFallbackHop(config, denied);
132
+ if (!hop.ok) throw new FallbackRefusedError(hop.response);
133
+ }
134
+ // Mixed or unresolved declarations grant nothing: actual first/retry guards still decide.
135
+ // A selector rewrite is not a selected hop and reserves no send or taken event here.
136
+ } else {
116
137
  try {
117
138
  const target = resolveChosenTarget(fallback.model, model => previewRouteModel(config, model));
118
139
  if ("unavailable" in target) return null;
@@ -120,23 +141,18 @@ export async function applyMainHardLockFallbackOverride(
120
141
  // An unavailable target keeps the source lock's refusal without touching the body.
121
142
  return null;
122
143
  }
144
+ // Concrete targets keep their existing proactive admission at body rewrite.
145
+ const hop = guardFallbackHop(config, {
146
+ site: "hard-lock",
147
+ route: parsed.model,
148
+ from: { provider: OPENAI_CODEX_PROVIDER_ID, model: parsed.model },
149
+ to: hardLockTargetOf(config, fallback.model),
150
+ trigger: "hard_lock", admission, ...(now !== undefined ? { now } : {}),
151
+ });
152
+ if (!hop.ok) throw new FallbackRefusedError(hop.response);
153
+ hop.commit();
123
154
  }
124
155
 
125
- // OCX-11: the reroute is a proactive model hop; refused, the request is answered with the
126
- // fallback refusal and the body is left untouched.
127
- const hop = guardFallbackHop(config, {
128
- site: "hard-lock",
129
- route: parsed.model,
130
- from: { provider: OPENAI_CODEX_PROVIDER_ID, model: parsed.model },
131
- to: hardLockTargetOf(config, parsed.model, fallback.model),
132
- trigger: "hard_lock",
133
- admission,
134
- ...(now !== undefined ? { now } : {}),
135
- });
136
- if (!hop.ok) throw new FallbackRefusedError(hop.response);
137
- // The rewrite is this site's admission: the body now names the fallback model.
138
- hop.commit();
139
-
140
156
  parsed.raw.model = fallback.model;
141
157
  if (fallback.reasoningEffort !== undefined) {
142
158
  const reasoning = parsed.raw.reasoning;
@@ -151,17 +167,31 @@ export async function applyMainHardLockFallbackOverride(
151
167
  }
152
168
 
153
169
  /**
154
- * The hop's destination for the fallback policy, read from config only. A routing profile picks
155
- * its candidate from request-history evidence, and evaluating it here would open that index under
156
- * OPENCODEX_HOME just to classify the hop (on Windows the open handle then outlives the request's
157
- * home); the profile's own dispatch still evaluates it. Its declared candidates are classified
158
- * instead, as the hop the profile could take: a candidate on another provider makes it a provider
159
- * hop. Combos, account namespaces and concrete targets resolve from config alone.
170
+ * Pure policy feasibility over declared concrete destinations. Unknown resolution is not denial.
171
+ * No picker, history, cooldown, event or send-budget operation runs for individual candidates.
172
+ * The first denied hop is only a refusal witness once every declaration is known denied.
160
173
  */
161
- function hardLockTargetOf(config: OcxConfig, sourceModel: string, model: string): FallbackTarget {
162
- const policyId = resolvePolicyProfileId(config, model);
163
- const profile = policyId ? getRoutingProfile(config, policyId) : undefined;
164
- if (profile) return profileHopTarget(config, sourceModel, profile);
174
+ function allDeclaredTargetsDenied(
175
+ config: OcxConfig, targets: readonly FallbackTarget[], hop: Omit<FallbackHop, "to">,
176
+ ): FallbackHop | undefined {
177
+ const deviceIds = fallbackDeviceIds(config, hop.admission, hop.now);
178
+ const routes = [hop.route, ...(hop.aliases ?? [])];
179
+ let witness: FallbackHop | undefined;
180
+ for (const target of targets) {
181
+ let to: FallbackTarget;
182
+ try {
183
+ const route = routeConcreteModel(config, `${target.provider}/${target.model}`);
184
+ to = { provider: route.providerName, model: route.modelId };
185
+ } catch { return undefined; }
186
+ const kind = fallbackHopKind(hop.from, to);
187
+ if (kind === null || resolveFallbackPolicy(config, { kind, routes, provider: hop.from.provider, deviceIds }).allowed) return undefined;
188
+ witness ??= { ...hop, to };
189
+ }
190
+ return witness;
191
+ }
192
+
193
+ /** Concrete and account-qualified targets retain the existing config-only resolution. */
194
+ function hardLockTargetOf(config: OcxConfig, model: string): FallbackTarget {
165
195
  try {
166
196
  const route = previewRouteModel(config, model);
167
197
  return { provider: route.providerName, model: route.modelId };
@@ -170,17 +200,3 @@ function hardLockTargetOf(config: OcxConfig, sourceModel: string, model: string)
170
200
  return slash > 0 ? { provider: model.slice(0, slash), model: model.slice(slash + 1) } : { provider: "", model };
171
201
  }
172
202
  }
173
-
174
- function profileHopTarget(config: OcxConfig, sourceModel: string, profile: NormalizedRoutingProfile): FallbackTarget {
175
- const targets = profile.candidates.map((candidate): FallbackTarget => {
176
- try {
177
- const route = routeConcreteModel(config, candidate.provider + "/" + candidate.model);
178
- return { provider: route.providerName, model: route.modelId };
179
- } catch {
180
- return { provider: candidate.provider, model: candidate.model };
181
- }
182
- });
183
- return targets.find(target => target.provider !== OPENAI_CODEX_PROVIDER_ID)
184
- ?? targets.find(target => target.model !== sourceModel)
185
- ?? { provider: OPENAI_CODEX_PROVIDER_ID, model: sourceModel };
186
- }
@@ -1,5 +1,7 @@
1
1
  import { wasPermanentAccountRefusal } from "../../oauth/account-auto-pause";
2
2
  import { isNativeControlResponse } from "./native-response-control";
3
+ import { guardBufferedComboRequiredTool } from "./combo-required-tool-contract";
4
+ import { attachResponseToolOwnership } from "./response-tool-ownership";
3
5
  import { createOutboundCredentialMask, createTerminalErrorRedactionBlockRewrite } from "./terminal-error-redaction";
4
6
  import type { ResponsesRequestContext, ResponsesAdmissionState } from "./core-options";
5
7
  import type { PreparedResponsesRequest } from "./request-prepare";
@@ -148,6 +150,8 @@ import {
148
150
  inspectResponseLogJson,
149
151
  inspectResponseLogSsePayloadParsed,
150
152
  noteUpstreamRequestId,
153
+ recordKeyWireAttemptUsage,
154
+ usageFromResponsesPayload,
151
155
  } from "../request-log";
152
156
  import { restoreRoutedCustomCallsInJson } from "../../responses/custom-tool-compat";
153
157
  import { restoreRoutedToolSearchCallsInJson } from "../../responses/tool-search-compat";
@@ -447,6 +451,15 @@ export async function deliverPassthroughResponse(
447
451
  const { requestBindings } = transportState;
448
452
 
449
453
  let upstreamResponse = nativeExchange.upstreamResponse;
454
+ // Judge the restored native payload before display projection can erase hosted-call evidence.
455
+ const requiredToolFailure = async (text: string): Promise<Response | undefined> => {
456
+ if (!options.comboAttempt || clientRequestedStream === true || isNonReplayableResponse(upstreamResponse)) return;
457
+ const candidate = attachResponseToolOwnership(new Response(text, {
458
+ status: upstreamResponse.status, headers: { "content-type": "application/json" },
459
+ }), providerExecutedCallTypes);
460
+ const verdict = await guardBufferedComboRequiredTool(candidate, parsed._rawBody, route.provider.adapter);
461
+ return verdict.ok ? undefined : verdict;
462
+ };
450
463
  const canonicalBufferedJson = clientRequestedStream !== true
451
464
  && isCanonicalOpenAiForwardProvider(route.provider);
452
465
  const originalContentType = upstreamResponse.headers.get("content-type");
@@ -887,7 +900,7 @@ export async function deliverPassthroughResponse(
887
900
  createTerminalErrorRedactionBlockRewrite(nativeExchange.request.headers, maskCredential),
888
901
  rememberPlaintextBlock,
889
902
  // Display-only projection must follow every continuation-cache observer.
890
- isLocalCodexImageClient(req.headers, options.admission?.kind, options.inboundWire)
903
+ (!canonicalBufferedJson || !options.comboAttempt) && isLocalCodexImageClient(req.headers, options.admission?.kind, options.inboundWire)
891
904
  ? createHostedImageDisplayRewrite()
892
905
  : undefined,
893
906
  ].filter((rewrite): rewrite is NonNullable<typeof rewrite> => rewrite !== undefined);
@@ -1030,6 +1043,29 @@ export async function deliverPassthroughResponse(
1030
1043
  };
1031
1044
  if (signal.aborted) return cancelAfterValidation();
1032
1045
 
1046
+ const requiredFailure = await requiredToolFailure(JSON.stringify(client.terminal.response));
1047
+ if (requiredFailure) {
1048
+ const usage = usageFromResponsesPayload(client.terminal.response.usage);
1049
+ if (usage && !logCtx.usageFromBridge) {
1050
+ if (!recordKeyWireAttemptUsage(logCtx, usage)) {
1051
+ logCtx.usage = usage;
1052
+ if (logCtx.activeAttempt) logCtx.activeAttempt.usage = usage;
1053
+ }
1054
+ logCtx.usageWireParsed = true;
1055
+ }
1056
+ return requiredFailure;
1057
+ }
1058
+ if (signal.aborted) return cancelAfterValidation();
1059
+ let clientJson = JSON.stringify(client.terminal.response);
1060
+ if (options.comboAttempt && isLocalCodexImageClient(req.headers, options.admission?.kind, options.inboundWire)) {
1061
+ const display = createHostedImageDisplayRewrite();
1062
+ try { clientJson = display.json(clientJson); }
1063
+ catch (error) {
1064
+ if (error instanceof RangeError) return formatErrorResponse(502, "upstream_error", "hosted image result exceeds local display limits");
1065
+ throw error;
1066
+ } finally { display.dispose?.(); }
1067
+ }
1068
+
1033
1069
  // Effects intentionally run only after both bounded validations. They inspect the same
1034
1070
  // upstream-facing transcript as the streaming relay and fire once; continuation storage
1035
1071
  // receives the final client-visible response once after all restorations succeeded.
@@ -1086,7 +1122,7 @@ export async function deliverPassthroughResponse(
1086
1122
 
1087
1123
  const jsonHeaders = sanitizePassthroughHeaders(headers, codexSafetyBufferingOptions);
1088
1124
  jsonHeaders.set("content-type", "application/json");
1089
- return markPreinspectedJsonResponse(new Response(JSON.stringify(client.terminal.response), {
1125
+ return markPreinspectedJsonResponse(new Response(clientJson, {
1090
1126
  status: upstreamResponse.status,
1091
1127
  statusText: upstreamResponse.statusText,
1092
1128
  headers: jsonHeaders,
@@ -1365,6 +1401,8 @@ export async function deliverPassthroughResponse(
1365
1401
  declaredBareWireToolNames,
1366
1402
  );
1367
1403
  }
1404
+ const requiredFailure = await requiredToolFailure(clientJson);
1405
+ if (requiredFailure) return requiredFailure;
1368
1406
  commitReasoningReplayServingRoute(nativeExchange.request.headers);
1369
1407
  try {
1370
1408
  rememberPassthroughResponseChecked(