@bitkyc08/opencodex 2.95.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
  3. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +21 -7
  16. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  17. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  18. package/src/adapters/openai-responses/passthrough.ts +8 -8
  19. package/src/adapters/openai-responses/reasoning.ts +9 -4
  20. package/src/adapters/openai-responses/request-strips.ts +1 -1
  21. package/src/adapters/openai-responses/transport.ts +17 -26
  22. package/src/adapters/physical-send.ts +3 -3
  23. package/src/adapters/qoder/adapter.ts +1 -1
  24. package/src/adapters/qoder/image-input.ts +5 -2
  25. package/src/adapters/zed-openai-stream.ts +2 -1
  26. package/src/bridge/errors.ts +11 -2
  27. package/src/bridge/response-json.ts +2 -1
  28. package/src/bridge/sse.ts +14 -6
  29. package/src/chat/failure-verdict.ts +21 -0
  30. package/src/chat/outbound.ts +139 -21
  31. package/src/claude/outbound.ts +49 -2
  32. package/src/cli/agent.ts +44 -15
  33. package/src/cli/capabilities-agents-routing.ts +9 -0
  34. package/src/cli/capabilities-base.ts +25 -3
  35. package/src/cli/capabilities-command.ts +12 -3
  36. package/src/cli/capability-contracts.ts +2 -0
  37. package/src/cli/codex-launch-auth.ts +30 -1
  38. package/src/cli/codex-launcher.ts +12 -5
  39. package/src/cli/codex-shim-autorestore.ts +5 -4
  40. package/src/cli/dispatch.ts +11 -176
  41. package/src/cli/ensure-desired-integrations.ts +4 -3
  42. package/src/cli/help.ts +2 -2
  43. package/src/cli/index.ts +9 -2
  44. package/src/cli/link.ts +1 -1
  45. package/src/cli/message-command.ts +2 -1
  46. package/src/cli/message-mcp-command.ts +29 -0
  47. package/src/cli/registry.ts +12 -4
  48. package/src/cli/root.ts +8 -0
  49. package/src/cli/sync-command.ts +243 -0
  50. package/src/cli/sync-fanout-process.ts +92 -0
  51. package/src/cli/sync-fanout.ts +150 -0
  52. package/src/cli/sync-flags.ts +10 -0
  53. package/src/cli/sync-link-status.ts +39 -0
  54. package/src/cli/sync-update-guard.ts +18 -0
  55. package/src/client/connect.ts +31 -14
  56. package/src/client/link-home.ts +3 -2
  57. package/src/client/machine-listener.ts +3 -0
  58. package/src/client/restore-ownership.ts +19 -1
  59. package/src/client/runtime-restart.ts +12 -4
  60. package/src/client/runtime.ts +40 -11
  61. package/src/client/stop-routing.ts +62 -0
  62. package/src/client/sync-runtime.ts +65 -0
  63. package/src/clients/config-export.ts +32 -3
  64. package/src/codex/account-store.ts +1 -0
  65. package/src/codex/auth-context-provider.ts +15 -0
  66. package/src/codex/auth-context.ts +59 -122
  67. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  68. package/src/codex/catalog/provider-models.ts +6 -8
  69. package/src/codex/forward-transport-headers.ts +65 -36
  70. package/src/codex/inject/config-toml.ts +88 -0
  71. package/src/codex/inject/multi-agent-v2.ts +30 -4
  72. package/src/codex/inject/plan.ts +34 -7
  73. package/src/codex/inject-coordination.ts +11 -0
  74. package/src/codex/inject.ts +18 -7
  75. package/src/codex/installation-id.ts +72 -0
  76. package/src/codex/lineage.ts +13 -7
  77. package/src/codex/quota.ts +22 -6
  78. package/src/codex/request-owned-affinity-key.ts +11 -0
  79. package/src/codex/request-owned-affinity.ts +118 -0
  80. package/src/codex/request-owned-main-pin.ts +86 -0
  81. package/src/codex/role-capability.ts +52 -41
  82. package/src/codex/routing/active-account.ts +13 -5
  83. package/src/codex/routing/selection.ts +40 -1
  84. package/src/codex/routing/thread-affinity-store.ts +916 -0
  85. package/src/codex/routing/thread-affinity.ts +90 -12
  86. package/src/codex/toml-source-lines.ts +72 -13
  87. package/src/combos/failover.ts +6 -109
  88. package/src/combos/request.ts +2 -2
  89. package/src/combos/resolve.ts +29 -11
  90. package/src/config/process-state.ts +5 -0
  91. package/src/config/schema/leaf-validators.ts +1 -0
  92. package/src/generated/compatibility-version.json +496 -192
  93. package/src/grok/sync.ts +10 -1
  94. package/src/images/loop.ts +2 -1
  95. package/src/lib/client-error-body.ts +184 -0
  96. package/src/lib/client-retry-after.ts +66 -0
  97. package/src/lib/config-ownership.ts +4 -0
  98. package/src/lib/context-overflow-verdict.ts +113 -0
  99. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  100. package/src/lib/desktop-cli-handoff.mjs +11 -1
  101. package/src/lib/empty-tool-catalog.ts +25 -3
  102. package/src/lib/error-destination.ts +47 -0
  103. package/src/lib/failure-detail.ts +66 -0
  104. package/src/lib/model-identity.ts +44 -0
  105. package/src/lib/private-sqlite-path.ts +124 -0
  106. package/src/lib/response-service-tier.ts +17 -0
  107. package/src/lib/retry-after.ts +3 -0
  108. package/src/lib/spend-ledger-owner.ts +43 -4
  109. package/src/lib/upstream-condition.ts +142 -0
  110. package/src/lib/upstream-retry.ts +14 -11
  111. package/src/lib/windows-owner-acl.ts +13 -6
  112. package/src/lib/windows-secret-acl.ts +2 -2
  113. package/src/link/remote-platform.ts +14 -0
  114. package/src/link/remote-windows.ts +51 -9
  115. package/src/link/ssh-argv.ts +63 -10
  116. package/src/messaging/mcp-queue-rpc.ts +102 -0
  117. package/src/messaging/mcp-queue-server.ts +42 -0
  118. package/src/messaging/mcp-queue-tools.ts +39 -0
  119. package/src/oauth/anthropic-identity.ts +2 -6
  120. package/src/oauth/generic-account-failover.ts +13 -11
  121. package/src/oauth/index.ts +41 -74
  122. package/src/oauth/oauth-errors.ts +67 -0
  123. package/src/oauth/store.ts +1 -1
  124. package/src/protocols/codecs/ollama.ts +197 -0
  125. package/src/protocols/encoders/adapter-events.ts +4 -0
  126. package/src/protocols/encoders/chat.ts +18 -10
  127. package/src/protocols/trace.ts +18 -0
  128. package/src/providers/anthropic-subscription.ts +25 -0
  129. package/src/providers/claude-cli-usage.ts +15 -67
  130. package/src/providers/fastwire.ts +3 -2
  131. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  132. package/src/providers/quota/anthropic-usage-windows.ts +65 -0
  133. package/src/providers/quota/vendor-probes-key.ts +60 -24
  134. package/src/providers/request-pacing.ts +3 -2
  135. package/src/responses/apply-patch-envelope.ts +45 -19
  136. package/src/responses/compaction-history-framing.ts +5 -1
  137. package/src/responses/freeform-wrapper-scan.ts +5 -3
  138. package/src/responses/parser-tools.ts +1 -0
  139. package/src/responses/progressive-freeform-input.ts +354 -45
  140. package/src/responses/schema.ts +5 -2
  141. package/src/routing/fallback-policy.ts +3 -1
  142. package/src/server/admission-model-scope.ts +17 -6
  143. package/src/server/admitted-http-turn.ts +56 -0
  144. package/src/server/audio-dictation.ts +3 -0
  145. package/src/server/audio-live.ts +8 -2
  146. package/src/server/audio-upstream.ts +2 -0
  147. package/src/server/auth-cors.ts +5 -0
  148. package/src/server/chat-completions.ts +45 -20
  149. package/src/server/chat-native-sse.ts +52 -7
  150. package/src/server/chat-native.ts +60 -35
  151. package/src/server/claude-bridge-pool-session.ts +59 -0
  152. package/src/server/claude-messages.ts +57 -27
  153. package/src/server/context-history.ts +14 -7
  154. package/src/server/images.ts +14 -5
  155. package/src/server/inbound-body-admission.ts +11 -4
  156. package/src/server/index/live-sideband.ts +16 -2
  157. package/src/server/index/ollama-routes.ts +89 -0
  158. package/src/server/index/serve-options.ts +22 -4
  159. package/src/server/index/websocket-handler.ts +5 -3
  160. package/src/server/index.ts +6 -36
  161. package/src/server/inference/client-encoder-delivery.ts +4 -2
  162. package/src/server/json-serialized-bytes.ts +44 -0
  163. package/src/server/live.ts +30 -5
  164. package/src/server/management/agent-settings-routes.ts +24 -21
  165. package/src/server/management/codex-cli-update-routes.ts +2 -1
  166. package/src/server/management/route-registry.ts +1 -1
  167. package/src/server/messages-native-scope.ts +2 -1
  168. package/src/server/messages-native-tool-guard.ts +1 -1
  169. package/src/server/messages-native.ts +12 -7
  170. package/src/server/messages-shared.ts +6 -2
  171. package/src/server/native-final-log.ts +93 -0
  172. package/src/server/ollama-inbound.ts +349 -0
  173. package/src/server/ollama-native-paths.ts +21 -0
  174. package/src/server/ollama-route-policy.ts +73 -0
  175. package/src/server/relay.ts +22 -3
  176. package/src/server/request-decompress.ts +4 -2
  177. package/src/server/request-log-failure-attribution.ts +22 -0
  178. package/src/server/request-log-failure-detail.ts +80 -0
  179. package/src/server/request-log-terminal-status.ts +4 -2
  180. package/src/server/request-log.ts +79 -42
  181. package/src/server/response-log-body.ts +6 -1
  182. package/src/server/responses/account-change-state.ts +17 -6
  183. package/src/server/responses/adapter-continuation.ts +9 -4
  184. package/src/server/responses/adapter-delivery.ts +5 -4
  185. package/src/server/responses/adapter-dispatch.ts +36 -30
  186. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  187. package/src/server/responses/codex-auth-error.ts +22 -17
  188. package/src/server/responses/codex-ws-exchange.ts +11 -8
  189. package/src/server/responses/codex-ws-metadata.ts +94 -21
  190. package/src/server/responses/codex-ws-request.ts +3 -1
  191. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  192. package/src/server/responses/compact.ts +89 -41
  193. package/src/server/responses/compaction-recovery.ts +4 -2
  194. package/src/server/responses/compaction-routing.ts +9 -4
  195. package/src/server/responses/core-auth.ts +32 -14
  196. package/src/server/responses/core-codex-account.ts +34 -12
  197. package/src/server/responses/core-combo-failure.ts +5 -1
  198. package/src/server/responses/core-combo-native.ts +2 -1
  199. package/src/server/responses/core-combo.ts +51 -33
  200. package/src/server/responses/core-errors.ts +22 -20
  201. package/src/server/responses/core-lifetime.ts +6 -3
  202. package/src/server/responses/core-normalize.ts +8 -1
  203. package/src/server/responses/core-options.ts +7 -0
  204. package/src/server/responses/core-pipeline.ts +4 -3
  205. package/src/server/responses/fetch-helpers.ts +7 -1
  206. package/src/server/responses/input-admission.ts +28 -2
  207. package/src/server/responses/native-injection.ts +1 -1
  208. package/src/server/responses/native-response-json.ts +13 -4
  209. package/src/server/responses/native-response-output.ts +1 -2
  210. package/src/server/responses/non-replayable-error.ts +2 -1
  211. package/src/server/responses/pacing-overload.ts +3 -2
  212. package/src/server/responses/passthrough-build-error.ts +36 -0
  213. package/src/server/responses/passthrough-delivery.ts +55 -14
  214. package/src/server/responses/passthrough-dispatch.ts +26 -39
  215. package/src/server/responses/passthrough-error.ts +9 -9
  216. package/src/server/responses/policy-fallback.ts +2 -1
  217. package/src/server/responses/request-prepare.ts +67 -48
  218. package/src/server/responses/request-sidecar-auth.ts +3 -1
  219. package/src/server/responses/request-transport.ts +35 -31
  220. package/src/server/responses/run-turn-execution.ts +6 -6
  221. package/src/server/responses/sidecar-execution.ts +16 -12
  222. package/src/server/responses/spend-storage-error.ts +2 -1
  223. package/src/server/responses/ws-upstream.ts +9 -0
  224. package/src/server/responses-custom-tool-repair.ts +14 -3
  225. package/src/server/responses-terminal-repair.ts +5 -2
  226. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  227. package/src/server/safe-response-headers.ts +162 -13
  228. package/src/server/search.ts +13 -4
  229. package/src/server/turn-state-handles.ts +164 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/server/ws-bridge.ts +5 -2
  232. package/src/service/ownership-mutation-lease.d.mts +11 -2
  233. package/src/service/ownership-mutation-lease.mjs +53 -11
  234. package/src/types/config.ts +2 -0
  235. package/src/update/index.ts +133 -25
  236. package/src/update/npm-install.d.mts +8 -0
  237. package/src/update/npm-install.mjs +20 -1
  238. package/src/update/orchestrated-admission.d.mts +4 -0
  239. package/src/update/orchestrated-admission.mjs +12 -0
  240. package/src/update/orchestrated-arguments.d.mts +12 -0
  241. package/src/update/orchestrated-arguments.mjs +64 -0
  242. package/src/update/orchestrated-child.d.mts +12 -0
  243. package/src/update/orchestrated-child.mjs +70 -0
  244. package/src/update/orchestrated-entry.ts +234 -0
  245. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  246. package/src/update/orchestrated-identity.ts +53 -0
  247. package/src/update/orchestrated-live-identity.ts +48 -0
  248. package/src/update/orchestrated-node-driver.mjs +99 -0
  249. package/src/update/orchestrated-outcome.d.mts +21 -0
  250. package/src/update/orchestrated-outcome.mjs +40 -0
  251. package/src/update/orchestrated-plan.ts +49 -0
  252. package/src/update/orchestrated-pnpm.d.mts +8 -0
  253. package/src/update/orchestrated-pnpm.mjs +33 -0
  254. package/src/update/orchestrated-session.d.mts +37 -0
  255. package/src/update/orchestrated-session.mjs +264 -0
  256. package/src/update/orchestrated-token.d.mts +10 -0
  257. package/src/update/orchestrated-token.mjs +21 -0
  258. package/src/update/orchestrated-token.ts +3 -0
  259. package/src/update/orchestrated-tree.d.mts +1 -0
  260. package/src/update/orchestrated-tree.mjs +14 -0
  261. package/src/update/pnpm-global-install.d.mts +6 -0
  262. package/src/update/pnpm-global-install.mjs +9 -2
  263. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  264. package/src/update/posix-install-supervisor.d.mts +10 -0
  265. package/src/update/posix-install-supervisor.mjs +88 -0
  266. package/src/update/sync-update-mutex.d.mts +10 -0
  267. package/src/update/sync-update-mutex.mjs +164 -0
  268. package/src/update/sync-update-mutex.ts +1 -0
  269. package/src/update/test-home-guard.mjs +33 -0
  270. package/src/update/transactional-install.mjs +2 -2
  271. package/src/usage/error-detail.ts +225 -0
  272. package/src/usage/log.ts +60 -27
  273. package/src/vision/describe.ts +4 -7
  274. package/src/web-search/executor.ts +4 -7
  275. package/src/web-search/loop.ts +31 -5
  276. package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
@@ -1,3 +1,4 @@
1
+ import { clientFacingModelText } from "../../lib/error-destination";
1
2
  import { createAnthropicThinkingRecovery } from "./anthropic-thinking-recovery";
2
3
  import { rotateAnthropicAccountOnResponseForInstance } from "../../oauth/anthropic-account-refusal";
3
4
  import type { ResponsesRequestContext } from "./core-options";
@@ -33,10 +34,10 @@ import {
33
34
  failoverAccountSnapshot,
34
35
  } from "../../oauth/generic-account-failover";
35
36
  import { classifyKiroRefusal } from "../../adapters/kiro-refusal";
36
- import { isNonReplayableResponse, SendBudgetExhaustedError } from "../../lib/upstream-retry";
37
+ import { isNonReplayableResponse, SendBudgetExhaustedError, errorDestinationLabel } from "../../lib/upstream-retry";
37
38
  import { isVerifiedModelNotInPlanResponse, markVerifiedModelNotInPlanResponse } from "../../lib/errors";
38
39
  import { unwrapUpstreamRetryEvidenceError } from "../../codex/auth-context";
39
- import { AdmissionModelDeniedError, admissionModelDeniedResponse } from "../admission-model-scope";
40
+ import { AdmissionModelDeniedError, admissionModelDeniedResponse, projectAdmissionModelDeniedLog } from "../admission-model-scope";
40
41
  import { noteKiroMonthlyRefusal, noteKiroServedSuccess } from "../../providers/kiro-usage";
41
42
  import { persistKiroAccountState } from "../../providers/kiro-account-state-disk";
42
43
  import { anthropicPoolCooldownResponse, readDisplaySafeErrorText } from "./core-errors";
@@ -48,7 +49,7 @@ import {
48
49
  } from "../../oauth/anthropic-routing";
49
50
  import { resolveWireProtocolOverride } from "../adapter-resolve";
50
51
  import { bindRouteReasoningReplayScope, adapterNeedsForcedContinuation, adapterNeedsToolCallContinuation } from "./core-replay";
51
- import { namespacedToolName } from "../../types";
52
+ import { namespacedToolName, toolChoiceToolPredicate } from "../../types";
52
53
  import { providerFetch } from "./fetch-helpers";
53
54
  import type { AttemptRecoveryKind } from "../../usage/log";
54
55
  import { recordAdapterReasoning, recordAdapterTier } from "../request-log";
@@ -248,7 +249,7 @@ export async function executeResponsesSidecars(
248
249
  if (!sidecarScopeDenial || response.ok) return undefined;
249
250
  void response.body?.cancel().catch(() => {});
250
251
  releaseSearchProbeLease();
251
- return admissionModelDeniedResponse(sidecarScopeDenial);
252
+ return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(sidecarScopeDenial, logCtx));
252
253
  };
253
254
  /** Admit a replacement credential, or leave the loop's original refusal authoritative. */
254
255
  const rotateSidecarProviderOn429 = async (
@@ -471,7 +472,7 @@ export async function executeResponsesSidecars(
471
472
  options.abortSignal ?? new AbortController().signal, { attempted: false },
472
473
  () => !sendBudgetState.sendBudgetExhausted()
473
474
  && !!sendBudgetState.adapterDispatchBudget
474
- && sendBudgetState.adapterDispatchBudget.spendEnforced !== true);
475
+ && sendBudgetState.adapterDispatchBudget.spendEnforced !== true, logCtx);
475
476
  const thinkingReceipt = (request: AdapterRequest, adapter: ProviderAdapter, recovery?: AttemptRecoveryKind) =>
476
477
  adapter.name !== "anthropic" ? {} : { onPhysicalDispatch: () => {
477
478
  if (recovery === "opaque-blob-rejection") {
@@ -480,7 +481,7 @@ export async function executeResponsesSidecars(
480
481
  });
481
482
  if (sendBudgetState.adapterDispatchBudget?.spendEnforced || !decision?.allowed) {
482
483
  if (decision?.allowed) decision.permit.release();
483
- throw new SendBudgetExhaustedError("sidecar thinking recovery");
484
+ throw new SendBudgetExhaustedError(errorDestinationLabel(request.url));
484
485
  }
485
486
  try { sendBudgetState.noteInitialDispatch(decision.permit); }
486
487
  finally { decision.permit.release(); }
@@ -579,7 +580,7 @@ export async function executeResponsesSidecars(
579
580
  ? clampImageMaxRounds(config.images?.maxRounds)
580
581
  : clampImageMaxRounds(config.images?.videoMaxRounds ?? 2),
581
582
  connectTimeoutMs: config.connectTimeoutMs ?? 200_000,
582
- stallTimeoutSec: config.stallTimeoutSec,
583
+ stallTimeoutSec: config.stallTimeoutSec, proxyErrorContext: logCtx,
583
584
  waitForRequestSlot: imageProviderFetch.waitForPacing,
584
585
  fetchImpl: imageProviderFetch.unpacedFetch ?? imageProviderFetch,
585
586
  fetchForRequest: (request, iterParsed, adapter, recovery) => {
@@ -633,7 +634,7 @@ export async function executeResponsesSidecars(
633
634
  if (imgScopeRefusal) return imgScopeRefusal;
634
635
  // A provider overflow on the first iteration answers as the main path's context failure (#7316).
635
636
  const imgResponse = options.comboAttempt ? imgLoopResponse : sidecarContextOverflowResponse(imgLoopResponse, {
636
- stream: parsed.stream, modelId: parsed._responseModelId ?? parsed.modelId, translatorBudget,
637
+ stream: parsed.stream, modelId: clientFacingModelText(options.clientModelLabel), translatorBudget,
637
638
  });
638
639
  if (imgResponse.body) {
639
640
  const imgTurnAc = new AbortController();
@@ -657,12 +658,15 @@ export async function executeResponsesSidecars(
657
658
  // Placed BEFORE the runTurn early-return for non-runTurn adapters so dual-tool turns dispatch
658
659
  // through web-search instead of being swallowed. runTurn adapters never enter this branch.
659
660
  if (canRunWebSearch && wsPlan) {
660
- const webSearchAdvisor = advisorPlan && !routedCompaction
661
+ const requestedTools = parsed.context.tools ?? [];
662
+ const advisorAllowed = advisorPlan
663
+ && toolChoiceToolPredicate(parsed.options.toolChoice, [...requestedTools, advisorPlan.tool])(advisorPlan.tool);
664
+ const webSearchAdvisor = advisorPlan && advisorAllowed && !routedCompaction
661
665
  && typeof advisorPlan.consult === "function" && typeof advisorPlan.formatUnavailable === "function"
662
666
  ? advisorPlan
663
667
  : undefined;
664
668
  parsed.context.tools = [
665
- ...(parsed.context.tools ?? []).filter(tool => !webSearchAdvisor || (!tool.advisor && tool.name !== ADVISOR_TOOL_NAME)),
669
+ ...requestedTools.filter(tool => !webSearchAdvisor || (!tool.advisor && tool.name !== ADVISOR_TOOL_NAME)),
666
670
  buildWebSearchTool(),
667
671
  ...(webSearchAdvisor ? [webSearchAdvisor.tool] : []),
668
672
  ];
@@ -734,7 +738,7 @@ export async function executeResponsesSidecars(
734
738
  beforeSidecarDispatch: wsPlan.forwardSidecar?.beforeDispatch,
735
739
  connectTimeoutMs: config.connectTimeoutMs ?? 200_000,
736
740
  routedModelStallTimeoutMs: wsPlan.routedModelStallTimeoutMs,
737
- stallTimeoutSec: wsPlan.stallTimeoutSec,
741
+ stallTimeoutSec: wsPlan.stallTimeoutSec, proxyErrorContext: logCtx,
738
742
  streamRoutedModelOutput: wsPlan.streamRoutedModelOutput,
739
743
  on429: rotateSidecarProviderOn429,
740
744
  onRotatedUsage: billRotatedUsage,
@@ -770,7 +774,7 @@ export async function executeResponsesSidecars(
770
774
  const wsResponse = poolUsageLimit ? anthropicPoolCooldownResponse(poolUsageLimit, { logCtx })
771
775
  : options.comboAttempt ? loopResponse
772
776
  : sidecarContextOverflowResponse(loopResponse, {
773
- stream: parsed.stream, modelId: parsed._responseModelId ?? parsed.modelId, translatorBudget,
777
+ stream: parsed.stream, modelId: clientFacingModelText(options.clientModelLabel), translatorBudget,
774
778
  });
775
779
  // Register the sidecar stream as an active turn so drainAndShutdown waits for (or aborts)
776
780
  // in-flight web-search turns instead of skipping them during graceful shutdown.
@@ -1,3 +1,4 @@
1
+ import { markProxyError } from "../../lib/client-error-body";
1
2
  import { formatErrorResponse } from "../../bridge";
2
3
  import { SPEND_LEDGER_STORAGE_UNAVAILABLE_CODE } from "../../lib/errors";
3
4
  import { markLocalRequestLogRefusal, type RequestLogContext } from "../request-log";
@@ -29,5 +30,5 @@ export function mapSpendLedgerStorageError(error: unknown, logCtx?: StorageRefus
29
30
 
30
31
  export function spendLedgerStorageErrorResponse(error: unknown, logCtx?: StorageRefusalLog): Response | undefined {
31
32
  const refusal = mapSpendLedgerStorageError(error, logCtx);
32
- return refusal && formatErrorResponse(refusal.status, refusal.code, refusal.message);
33
+ return refusal && markProxyError(formatErrorResponse(refusal.status, refusal.code, refusal.message));
33
34
  }
@@ -21,6 +21,7 @@ import { resolveProxyRoute, socks5ProxyFromEnv } from "../../lib/proxy-env";
21
21
  import type { CodexWsQuotaObserver } from "./codex-ws-metadata";
22
22
  import { CODEX_RESPONSES_HTTP_URL, CODEX_RESPONSES_WS_URL, CODEX_WS_FRAME_HEADERS, prepareCodexHttpInit, prepareCodexWsRequest } from "./codex-ws-request";
23
23
  import { codexWsExchange } from "./codex-ws-exchange";
24
+ import { TURN_STATE_BINDING_INIT } from "../turn-state-handles";
24
25
  import { CodexWsSession } from "./codex-ws-session";
25
26
  import { codexWsPool, codexWsReuseIdentity } from "./codex-ws-pool";
26
27
  import { codexWsCreateFrameExceedsLimit, type CodexWsPreOutputRefusalHold } from "./codex-ws-wire";
@@ -252,5 +253,13 @@ export async function codexWsUpstreamFetch(
252
253
  beforeContinuation, onPhysicalDispatch,
253
254
  preOutputRefusalHold,
254
255
  bunVersion: typeof runtime === "string" ? runtime : runtime.version,
256
+ metadataContext: codexWsMetadataContext(init, prepared.model),
255
257
  });
256
258
  }
259
+
260
+ /** The binding the provider fetch attached to this send, and the requested model, for relayed metadata. */
261
+ function codexWsMetadataContext(init: RequestInit, model: string | undefined): { turnStateBinding?: string; knownModels: string[]; provider: string } {
262
+ const binding = (init as Record<symbol, unknown>)[TURN_STATE_BINDING_INIT];
263
+ // This upstream is the ChatGPT Codex backend, so its bundled model catalog also counts as known.
264
+ return { ...(typeof binding === "string" ? { turnStateBinding: binding } : {}), knownModels: model ? [model] : [], provider: "openai-codex" };
265
+ }
@@ -6,7 +6,7 @@ import {
6
6
  } from "../responses/apply-patch-envelope";
7
7
  import { compileCodeModeHelperInput, resolveCodeModeHelperName } from "../responses/code-mode-helper-compat";
8
8
  import { mayBecomeCodeModeShellInput } from "../responses/code-mode-shell-input";
9
- import { progressiveFreeformInput } from "../responses/progressive-freeform-input";
9
+ import { ProgressiveFreeformInputReader } from "../responses/progressive-freeform-input";
10
10
  import { declaresCodeModeExec } from "../types/tools";
11
11
  import {
12
12
  customToolItemId,
@@ -41,9 +41,12 @@ function replaceSseEventName(block: string, type: string): string {
41
41
 
42
42
  type OpenCustomCall = {
43
43
  argumentsText: string;
44
+ argumentsTail: string;
44
45
  emittedInput: string;
45
46
  canonicalPatchProgress: boolean;
46
47
  retainedBytes: number;
48
+ // Resumes across deltas so the growing arguments are decoded once rather than once per delta.
49
+ freeformReader?: ProgressiveFreeformInputReader;
47
50
  };
48
51
 
49
52
  export class RoutedCustomToolProgressError extends Error {
@@ -77,6 +80,7 @@ export function createRoutedCustomToolRestoreBlockRewrite(
77
80
 
78
81
  const emptyOpenCall = (): OpenCustomCall => ({
79
82
  argumentsText: "",
83
+ argumentsTail: "",
80
84
  emittedInput: "",
81
85
  canonicalPatchProgress: false,
82
86
  retainedBytes: 0,
@@ -282,6 +286,7 @@ export function createRoutedCustomToolRestoreBlockRewrite(
282
286
  const deltaBytes = Buffer.byteLength(delta, "utf8");
283
287
  if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: "retained_collectors" });
284
288
  open.argumentsText += delta;
289
+ open.argumentsTail = (open.argumentsTail + delta).slice(-64);
285
290
  open.retainedBytes += deltaBytes;
286
291
  openCalls.set(upstreamItemId, open);
287
292
  if (customExecItemNames.get(upstreamItemId) !== "exec"
@@ -341,6 +346,7 @@ export function createRoutedCustomToolRestoreBlockRewrite(
341
346
  const deltaBytes = Buffer.byteLength(delta, "utf8");
342
347
  if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: "retained_collectors" });
343
348
  open.argumentsText += delta;
349
+ open.argumentsTail = (open.argumentsTail + delta).slice(-64);
344
350
  open.retainedBytes += deltaBytes;
345
351
  openCalls.set(upstreamItemId, open);
346
352
  // A helper alias will become JavaScript at completion, never raw patch/JSON.
@@ -348,7 +354,8 @@ export function createRoutedCustomToolRestoreBlockRewrite(
348
354
  const itemName = itemNames.get(upstreamItemId);
349
355
  const ownsFreeformGrammar = itemName?.namespace === undefined
350
356
  || itemName?.namespace === "functions";
351
- const fullInput = progressiveFreeformInput(
357
+ open.freeformReader ??= new ProgressiveFreeformInputReader();
358
+ const fullInput = open.freeformReader.update(
352
359
  open.argumentsText,
353
360
  ownsFreeformGrammar ? itemName?.name ?? "" : "",
354
361
  );
@@ -374,7 +381,11 @@ export function createRoutedCustomToolRestoreBlockRewrite(
374
381
  if (mayCompile && mayBecomePatchEnvelope(fullInput)) return [];
375
382
  let streamInput = fullInput;
376
383
  if (mayNormalize && mayBecomePatchEnvelope(fullInput)) {
377
- const stablePrefix = stableCanonicalPatchPrefix(fullInput);
384
+ const stablePrefix = stableCanonicalPatchPrefix(
385
+ fullInput,
386
+ fullInput === open.argumentsText ? open.argumentsTail : fullInput.slice(-64),
387
+ open.canonicalPatchProgress,
388
+ );
378
389
  if (stablePrefix === null) return [];
379
390
  streamInput = stablePrefix;
380
391
  if (stablePrefix.length > 0) open.canonicalPatchProgress = true;
@@ -1,3 +1,4 @@
1
+ import { rememberProxyIncomplete, carryProxyIncompleteContext } from "../lib/client-error-body";
1
2
  import type { TranslatorBudget } from "../lib/translator-budget";
2
3
  import type { ResponsesTerminalRepairPolicy } from "../providers/registry";
3
4
  import { nextSseBlock, sseDataPayload } from "./sse-payload-rewrite";
@@ -80,6 +81,7 @@ export function relayResponsesSseWithTerminalRepair(
80
81
  policy: ResponsesTerminalRepairPolicy,
81
82
  budget: TranslatorBudget,
82
83
  scheduler: ResponsesTerminalRepairScheduler = systemScheduler,
84
+ proxyErrorContext: object = {},
83
85
  ): ReadableStream<Uint8Array> {
84
86
  const reader = body.getReader();
85
87
  const decoder = new TextDecoder();
@@ -191,6 +193,7 @@ export function relayResponsesSseWithTerminalRepair(
191
193
  ? { incomplete_details: { reason: "missing_terminal_event" } }
192
194
  : {}),
193
195
  };
196
+ if (kind === "incomplete") rememberProxyIncomplete(proxyErrorContext, "missing_terminal_event");
194
197
  const type = `response.${kind}`;
195
198
  return encoder.encode(`event: ${type}\ndata: ${JSON.stringify({
196
199
  type,
@@ -351,7 +354,7 @@ export function relayResponsesSseWithTerminalRepair(
351
354
  }
352
355
  };
353
356
 
354
- return new ReadableStream<Uint8Array>({
357
+ return carryProxyIncompleteContext(proxyErrorContext, new ReadableStream<Uint8Array>({
355
358
  start(controller) {
356
359
  controllerRef = controller;
357
360
  if (upstream.signal.aborted) {
@@ -372,5 +375,5 @@ export function relayResponsesSseWithTerminalRepair(
372
375
  upstream.abort(reason);
373
376
  return reader.cancel(reason);
374
377
  },
375
- });
378
+ }));
376
379
  }
@@ -1,3 +1,4 @@
1
+ import { UNDECLARED_TOOL_CALL_MESSAGE } from "../lib/client-error-body";
1
2
  import { UNDECLARED_TOOL_CALL_ERROR_CODE } from "../lib/errors";
2
3
  import { hasItemProvenance, isHistoricalItem } from "../responses/item-provenance";
3
4
  import {
@@ -13,6 +14,7 @@ import {
13
14
  normalizeDeclaredToolName,
14
15
  } from "../types";
15
16
  import { replaceSseDataPayload, sseDataPayload, type SseBlockRewrite } from "./sse-payload-rewrite";
17
+ import { TOOL_SEARCH_FUNCTION_NAME } from "../responses/tool-search-compat";
16
18
 
17
19
  /** Item types the client executes through a request-declared wire name. */
18
20
  export const CLIENT_EXECUTED_CALL_TYPES: ReadonlySet<string> = new Set([
@@ -77,9 +79,6 @@ const NAMELESS_TOOL_SPEC_TYPES = new Set([
77
79
  "x_search",
78
80
  ]);
79
81
 
80
- /** An upstream-supplied name reaches the error message; keep it bounded. */
81
- const MAX_REPORTED_NAME_CHARS = 100;
82
-
83
82
  export { UNDECLARED_TOOL_CALL_ERROR_CODE };
84
83
 
85
84
  function isPlainObject(value: unknown): value is Record<string, unknown> {
@@ -91,6 +90,7 @@ function addWireToolName(
91
90
  tool: unknown,
92
91
  namespace?: string,
93
92
  ambiguousDottedAliases?: ReadonlySet<string>,
93
+ canonicalOnly = false,
94
94
  ): void {
95
95
  if (!isPlainObject(tool)) return;
96
96
  const name = wireToolInnerName(tool);
@@ -103,6 +103,7 @@ function addWireToolName(
103
103
  return;
104
104
  }
105
105
  names.add(namespacedToolName(namespace, name));
106
+ if (canonicalOnly) return;
106
107
  // Some routed providers echo the flattened wire name with a dot (`ns.name`, observed with
107
108
  // muse-spark via opencode-go) instead of `ns__name`. It is the same tool identity, so register
108
109
  // the dotted spelling too, mirroring `toolChoiceAliases` (#3402) -- but only while that
@@ -150,16 +151,17 @@ function addWireToolSpecs(
150
151
  names: Set<string>,
151
152
  specs: unknown,
152
153
  ambiguousDottedAliases?: ReadonlySet<string>,
154
+ canonicalOnly = false,
153
155
  ): void {
154
156
  if (!Array.isArray(specs)) return;
155
157
  for (const spec of specs) {
156
158
  if (!isPlainObject(spec)) continue;
157
159
  if (spec.type === "namespace" && Array.isArray(spec.tools)) {
158
160
  const namespace = typeof spec.name === "string" ? spec.name : undefined;
159
- for (const inner of spec.tools) addWireToolName(names, inner, namespace, ambiguousDottedAliases);
161
+ for (const inner of spec.tools) addWireToolName(names, inner, namespace, ambiguousDottedAliases, canonicalOnly);
160
162
  continue;
161
163
  }
162
- addWireToolName(names, spec, undefined, ambiguousDottedAliases);
164
+ addWireToolName(names, spec, undefined, ambiguousDottedAliases, canonicalOnly);
163
165
  }
164
166
  }
165
167
 
@@ -171,7 +173,7 @@ function addWireToolSpecs(
171
173
  * inside `input`, routed custom-tool rewrites) that the internal list flattens or renames, and
172
174
  * only the wire names can be compared against what the provider echoes back.
173
175
  */
174
- export function collectDeclaredWireToolNames(body: unknown): Set<string> {
176
+ export function collectDeclaredWireToolNames(body: unknown, options?: { canonicalOnly?: boolean }): Set<string> {
175
177
  const names = new Set<string>();
176
178
  if (!isPlainObject(body)) return names;
177
179
  const specGroups: unknown[] = [body.tools];
@@ -184,7 +186,29 @@ export function collectDeclaredWireToolNames(body: unknown): Set<string> {
184
186
  }
185
187
  }
186
188
  const ambiguousDottedAliases = collectAmbiguousDottedAliases(specGroups);
187
- for (const specs of specGroups) addWireToolSpecs(names, specs, ambiguousDottedAliases);
189
+ for (const specs of specGroups) addWireToolSpecs(names, specs, ambiguousDottedAliases, options?.canonicalOnly);
190
+ return names;
191
+ }
192
+
193
+ /**
194
+ * Function names that translated adapters give to nameless hosted declarations in this catalog.
195
+ * The parser exposes a declared `{type:"tool_search"}` to Chat-style providers as the function
196
+ * `tool_search`, so only a declaration present in this (current-turn) body authorizes that name.
197
+ */
198
+ export function collectTranslatedHostedToolNames(body: unknown): Set<string> {
199
+ const names = new Set<string>();
200
+ if (!isPlainObject(body)) return names;
201
+ const specGroups: unknown[] = [body.tools];
202
+ if (Array.isArray(body.input)) {
203
+ for (const item of body.input) {
204
+ if (isPlainObject(item) && item.type === "additional_tools") specGroups.push(item.tools);
205
+ }
206
+ }
207
+ for (const specs of specGroups) {
208
+ if (Array.isArray(specs) && specs.some(spec => isPlainObject(spec) && spec.type === "tool_search")) {
209
+ names.add(TOOL_SEARCH_FUNCTION_NAME);
210
+ }
211
+ }
188
212
  return names;
189
213
  }
190
214
 
@@ -519,12 +543,10 @@ export function undeclaredToolCallNameInResponse(
519
543
  /**
520
544
  * Formats an error message indicating that a routed provider emitted an undeclared tool call.
521
545
  *
522
- * @param name - The undeclared tool name emitted by the provider.
523
546
  * @returns A formatted error message string.
524
547
  */
525
- export function undeclaredToolCallMessage(name: string): string {
526
- const reported = name.slice(0, MAX_REPORTED_NAME_CHARS);
527
- return `routed provider emitted undeclared client tool "${reported}"; only request-declared tools may be called`;
548
+ export function undeclaredToolCallMessage(): string {
549
+ return UNDECLARED_TOOL_CALL_MESSAGE;
528
550
  }
529
551
 
530
552
  /**
@@ -694,11 +716,11 @@ export function normalizeDefaultNamespaceInJson(
694
716
  }
695
717
  }
696
718
 
697
- function failedBlocks(name: string, newline: string): readonly string[] {
719
+ function failedBlocks(newline: string): readonly string[] {
698
720
  const failure = {
699
721
  type: "upstream_error",
700
722
  code: UNDECLARED_TOOL_CALL_ERROR_CODE,
701
- message: undeclaredToolCallMessage(name),
723
+ message: undeclaredToolCallMessage(),
702
724
  };
703
725
  const payload = JSON.stringify({
704
726
  type: "response.failed",
@@ -716,7 +738,7 @@ function failedBlocks(name: string, newline: string): readonly string[] {
716
738
  * it has no top-level handler for — `apply_patch`, which under code mode exists only as a nested
717
739
  * `tools.apply_patch(...)` helper inside `exec` — and the turn surfaced as a bare `aborted` with
718
740
  * no output and no explanation. Replacing the offending event with an explicit `response.failed`
719
- * turns that silent dead end into a compatibility error naming the tool.
741
+ * turns that silent dead end into a compatibility error describing the request catalog restriction.
720
742
  *
721
743
  * Everything after the trip is dropped so a later `response.completed` cannot contradict the
722
744
  * terminal already sent. Non-JSON and non-item blocks pass through untouched.
@@ -734,7 +756,7 @@ export function createUndeclaredToolCallGuardBlockRewrite(
734
756
  providerExecutedCallTypes: ProviderExecutedCallTypes = EMPTY_PROVIDER_EXECUTED_CALL_TYPES,
735
757
  declaredBare?: ReadonlySet<string>,
736
758
  declaredCustom?: ReadonlySet<string>,
737
- options?: { refuseUndeclared?: boolean },
759
+ options?: { refuseUndeclared?: boolean; onRefusal?: (message: string) => void },
738
760
  ): SseBlockRewrite {
739
761
  // Deferred-catalog wires (Chat/Anthropic) keep the default-namespace normalization — the
740
762
  // client can only resolve the bare name it declared — while the refusal itself stays off.
@@ -754,7 +776,8 @@ export function createUndeclaredToolCallGuardBlockRewrite(
754
776
  const name = undeclaredToolCallName(parsed, declared, declaredNamelessClientCallTypes, providerExecutedCallTypes, declaredBare, declaredCustom);
755
777
  if (name !== undefined) {
756
778
  tripped = true;
757
- return failedBlocks(name, block.includes("\r\n") ? "\r\n" : "\n");
779
+ options?.onRefusal?.(undeclaredToolCallMessage());
780
+ return failedBlocks(block.includes("\r\n") ? "\r\n" : "\n");
758
781
  }
759
782
  }
760
783
  const normalized = normalizeDefaultNamespaceInPayload(parsed, declared, declaredBare);
@@ -1,23 +1,172 @@
1
- const SAFE_RESPONSE_HEADER_EXACT = new Set([
2
- "retry-after", "x-request-id", "openai-request-id", "x-codex-turn-state",
3
- "openai-model", "x-models-etag", "x-reasoning-included",
4
- "x-codex-credits-has-credits", "x-codex-credits-unlimited", "x-codex-credits-balance",
5
- "x-codex-promo-message", "x-codex-safety-buffering-enabled", "x-codex-safety-buffering-faster-model",
1
+ import { formatClientRetryAfter } from "../lib/client-retry-after";
2
+ import { knownModelIdentity } from "../lib/model-identity";
3
+ import { isLiveTurnStateHandle, issueTurnStateHandle } from "./turn-state-handles";
4
+
5
+ /**
6
+ * Upstream response headers a client may receive as response metadata (WebSocket frames, the
7
+ * WS-to-HTTP projection). Each name is listed explicitly and each value is validated or rebuilt
8
+ * against its contract; a value that does not fit is dropped. No value is copied: numbers and
9
+ * booleans are reformatted, a model header is kept only as a model id the proxy already knows for
10
+ * the request, and the turn-state token is replaced by a handle bound to the request. Request ids,
11
+ * the models etag and quota limit labels are not relayed.
12
+ */
13
+ export type ResponseMetadataContext = {
14
+ /** Binding of the send that produced these headers; without one, a turn-state token is dropped. */
15
+ turnStateBinding?: string;
16
+ /** Model ids the request already names (requested and routed); the bundled catalog also counts. */
17
+ knownModels?: readonly string[];
18
+ /** Provider (or metadata vendor) whose bundled model catalog also counts as known. */
19
+ provider?: string;
20
+ };
21
+ type Normalize = (value: string, context: ResponseMetadataContext) => string | undefined;
22
+
23
+ const OPAQUE_TOKEN = /^[A-Za-z0-9._~+/=:-]{1,8192}$/;
24
+ const NUMBER = /^\d{1,15}(?:\.\d{1,6})?$/;
25
+
26
+ function bool(value: string): string | undefined {
27
+ const folded = value.trim().toLowerCase();
28
+ return folded === "true" || folded === "false" ? folded : undefined;
29
+ }
30
+
31
+ function parseNonNegative(value: string): number | undefined {
32
+ const trimmed = value.trim();
33
+ if (!NUMBER.test(trimmed)) return undefined;
34
+ const number = Number(trimmed);
35
+ return Number.isFinite(number) ? number : undefined;
36
+ }
37
+
38
+ /** A non-negative decimal rebuilt by this proxy (so "1e3", signs and padding never pass through). */
39
+ function decimal(max: number): Normalize {
40
+ return value => {
41
+ const number = parseNonNegative(value);
42
+ return number !== undefined && number <= max ? String(number) : undefined;
43
+ };
44
+ }
45
+
46
+ /** A non-negative integer formatted by this proxy: fractions round down, large values clamp to max. */
47
+ function count(max: number): Normalize {
48
+ return value => {
49
+ const number = parseNonNegative(value);
50
+ return number === undefined ? undefined : String(Math.min(Math.floor(number), max));
51
+ };
52
+ }
53
+
54
+ /** A non-negative integer exact to the contract (an epoch or window length); anything else drops. */
55
+ function integer(max: number): Normalize {
56
+ return value => {
57
+ const trimmed = value.trim();
58
+ if (!/^\d{1,15}$/.test(trimmed)) return undefined;
59
+ const number = Number(trimmed);
60
+ return number <= max ? String(number) : undefined;
61
+ };
62
+ }
63
+
64
+ const DURATION_PART = /(\d{1,9}(?:\.\d{1,6})?)(h|ms|m|s)/gy;
65
+ const DURATION_UNIT_MS = new Map<string, number>([["h", 3_600_000], ["m", 60_000], ["s", 1_000], ["ms", 1]]);
66
+ const MAX_RESET_MS = 8 * 24 * 60 * 60 * 1000;
67
+
68
+ /**
69
+ * A rate-limit reset: plain seconds, or a Go-style duration ("6m0s", "20ms"). Both are rebuilt from
70
+ * whole units — seconds round up, sub-second durations become whole milliseconds — and clamp to 8 days.
71
+ */
72
+ function resetDuration(value: string): string | undefined {
73
+ const trimmed = value.trim();
74
+ const seconds = parseNonNegative(trimmed);
75
+ if (seconds !== undefined) return String(Math.min(Math.ceil(seconds), MAX_RESET_MS / 1000));
76
+ if (!trimmed || trimmed.length > 64) return undefined;
77
+ let ms = 0;
78
+ let offset = 0;
79
+ DURATION_PART.lastIndex = 0;
80
+ for (let match = DURATION_PART.exec(trimmed); match; match = DURATION_PART.exec(trimmed)) {
81
+ ms += Number(match[1]) * DURATION_UNIT_MS.get(match[2]!)!;
82
+ offset = DURATION_PART.lastIndex;
83
+ }
84
+ if (offset === 0 || offset !== trimmed.length || !Number.isFinite(ms)) return undefined;
85
+ const clamped = Math.min(ms, MAX_RESET_MS);
86
+ if (clamped < 1000) return `${Math.ceil(clamped)}ms`;
87
+ const whole = Math.ceil(clamped / 1000);
88
+ const hours = Math.floor(whole / 3600);
89
+ const minutes = Math.floor((whole % 3600) / 60);
90
+ const secs = whole % 60;
91
+ return `${hours ? `${hours}h` : ""}${hours || minutes ? `${minutes}m` : ""}${secs}s`;
92
+ }
93
+
94
+ const COUNT = count(1e12);
95
+
96
+ // A Map, so a header named after an Object.prototype member ("constructor", "__proto__",
97
+ // "toString") can never resolve to an inherited value.
98
+ const EXACT: ReadonlyMap<string, Normalize> = new Map<string, Normalize>([
99
+ ["retry-after", value => formatClientRetryAfter(value)],
100
+ // Codex echoes the turn-state token on later requests of the turn; it receives a handle bound to
101
+ // this send, which src/server/turn-state-handles.ts maps back only for a send with the same binding.
102
+ ["x-codex-turn-state", (value, context) => !OPAQUE_TOKEN.test(value) ? undefined
103
+ : isLiveTurnStateHandle(value) ? value
104
+ : context.turnStateBinding ? issueTurnStateHandle(value, context.turnStateBinding) : undefined],
105
+ ["openai-model", (value, context) => knownModelIdentity(value, context.knownModels, context.provider)],
106
+ ["x-codex-safety-buffering-faster-model", (value, context) => knownModelIdentity(value, context.knownModels, context.provider)],
107
+ ["x-reasoning-included", bool],
108
+ ["x-codex-credits-has-credits", bool],
109
+ ["x-codex-credits-unlimited", bool],
110
+ ["x-codex-credits-balance", decimal(1e12)],
111
+ ["x-codex-safety-buffering-enabled", bool],
112
+ ["x-ratelimit-limit", COUNT],
113
+ ["x-ratelimit-remaining", COUNT],
114
+ ["x-ratelimit-reset", resetDuration],
115
+ ["x-ratelimit-limit-requests", COUNT],
116
+ ["x-ratelimit-limit-tokens", COUNT],
117
+ ["x-ratelimit-remaining-requests", COUNT],
118
+ ["x-ratelimit-remaining-tokens", COUNT],
119
+ ["x-ratelimit-reset-requests", resetDuration],
120
+ ["x-ratelimit-reset-tokens", resetDuration],
121
+ ["x-ratelimit-limit-req-minute", COUNT],
122
+ ["x-ratelimit-remaining-req-minute", COUNT],
123
+ ["x-ratelimit-limit-tokens-minute", COUNT],
124
+ ["x-ratelimit-remaining-tokens-minute", COUNT],
125
+ ["x-ratelimit-limit-tokens-month", COUNT],
126
+ ["x-ratelimit-remaining-tokens-month", COUNT],
127
+ ["x-ratelimit-tokens-query-cost", COUNT],
6
128
  ]);
7
129
 
8
- /** Response metadata may carry only the same non-credential headers as native WS errors. */
130
+ /**
131
+ * Codex quota limit families this proxy relays: the ordinary windows (`x-codex-primary-...`) and the
132
+ * metered `bengalfox` family (`x-codex-bengalfox-primary-...`, native `codex_bengalfox`). A header
133
+ * name is upstream text too, so any other family is dropped rather than echoed.
134
+ */
135
+ export const CODEX_QUOTA_FAMILIES = ["bengalfox"] as const;
136
+ const QUOTA_WINDOW = new RegExp(`^x-codex(?:-(?:${CODEX_QUOTA_FAMILIES.join("|")}))?-(?:primary|secondary|tertiary)-(used-percent|window-minutes|reset-at)$`);
137
+ const QUOTA_VALUE: ReadonlyMap<string, Normalize> = new Map<string, Normalize>([
138
+ ["used-percent", decimal(100)],
139
+ ["window-minutes", integer(1e7)],
140
+ ["reset-at", integer(1e11)],
141
+ ]);
142
+
143
+ function normalizer(lower: string): Normalize | undefined {
144
+ if (lower.length > 96) return undefined;
145
+ const exact = EXACT.get(lower);
146
+ if (exact) return exact;
147
+ const window = QUOTA_WINDOW.exec(lower);
148
+ if (window) return QUOTA_VALUE.get(window[1]!);
149
+ return undefined;
150
+ }
151
+
152
+ /** True for a header name this proxy may relay as response metadata. */
9
153
  export function isSafeResponseHeader(name: string): boolean {
10
- const lower = name.toLowerCase();
11
- return SAFE_RESPONSE_HEADER_EXACT.has(lower)
12
- || lower.startsWith("x-ratelimit-")
13
- || /^x-codex(?:-[a-z0-9-]+)?-(primary|secondary|tertiary)-(used-percent|window-minutes|reset-at)$/.test(lower)
14
- || /^x-codex(?:-[a-z0-9-]+)?-limit-name$/.test(lower);
154
+ return typeof name === "string" && normalizer(name.toLowerCase()) !== undefined;
155
+ }
156
+
157
+ /** The value this proxy relays for an allowlisted header, rebuilt or validated; undefined drops it. */
158
+ export function normalizeSafeResponseHeader(name: string, value: string, context: ResponseMetadataContext = {}): string | undefined {
159
+ if (typeof name !== "string" || typeof value !== "string") return undefined;
160
+ const normalize = normalizer(name.toLowerCase());
161
+ const normalized = normalize?.(value, context);
162
+ return typeof normalized === "string" ? normalized : undefined;
15
163
  }
16
164
 
17
- export function safeResponseHeaders(headers: Headers): Record<string, string> {
165
+ export function safeResponseHeaders(headers: Headers, context: ResponseMetadataContext = {}): Record<string, string> {
18
166
  const out: Record<string, string> = {};
19
167
  for (const [name, value] of headers) {
20
- if (isSafeResponseHeader(name)) out[name.toLowerCase()] = value;
168
+ const normalized = normalizeSafeResponseHeader(name, value, context);
169
+ if (normalized !== undefined) out[name.toLowerCase()] = normalized;
21
170
  }
22
171
  return out;
23
172
  }
@@ -1,3 +1,5 @@
1
+ import { CodexInstallationIdUnavailableError } from "../codex/installation-id";
2
+ import { isolateCodexPoolClientMetadata, mergeCodexSelectedHeaders } from "../codex/forward-transport-headers";
1
3
  /**
2
4
  * /v1/alpha/search relay.
3
5
  *
@@ -159,6 +161,7 @@ export async function handleSearch(
159
161
  ? `${upstream.providerName}-${accountNamespace}`
160
162
  : formatCodexProviderForLog(upstream.providerName, codexLogAccountId(upstream.authContext), config);
161
163
  } catch (err) {
164
+ if (err instanceof CodexInstallationIdUnavailableError) return formatErrorResponse(503, "server_busy", err.message);
162
165
  if (err instanceof CodexAccountCooldownError) {
163
166
  return cooldownErrorResponse(err, Date.now(), accountNamespace);
164
167
  }
@@ -194,9 +197,9 @@ export async function handleSearch(
194
197
  }
195
198
  }
196
199
 
197
- const headers: Record<string, string> = { "content-type": "application/json" };
198
- if (upstream.provider.headers) Object.assign(headers, upstream.provider.headers);
199
- for (const [name, value] of upstream.headers) headers[name] = value;
200
+ const headers = mergeCodexSelectedHeaders(
201
+ { "content-type": "application/json", ...upstream.provider.headers }, upstream.headers,
202
+ );
200
203
  const url = `${upstream.provider.baseUrl}/alpha/search`;
201
204
  const timeoutMs = config.search?.timeoutMs ?? SEARCH_UPSTREAM_TIMEOUT_MS;
202
205
  const linkedSignal = signalWithTimeout(timeoutMs, req.signal);
@@ -207,7 +210,9 @@ export async function handleSearch(
207
210
  upstreamResponse = await fetch(url, {
208
211
  method: "POST",
209
212
  headers,
210
- body: JSON.stringify(relayBody),
213
+ body: JSON.stringify(isolateCodexPoolClientMetadata(
214
+ relayBody, upstream.authContext.kind === "pool" ? upstream.authContext.chatgptAccountId : undefined,
215
+ )),
211
216
  signal: linkedSignal.signal,
212
217
  // Credential-bearing: do not follow a cross-origin 3xx. Bun strips `Authorization`
213
218
  // across origins but forwards nonstandard headers such as `chatgpt-account-id`,
@@ -232,6 +237,10 @@ export async function handleSearch(
232
237
  if (contentType) relayHeaders["content-type"] = contentType;
233
238
  return new Response(observed.bytes, { status: upstreamResponse.status, headers: relayHeaders });
234
239
  } catch (err) {
240
+ if (err instanceof CodexInstallationIdUnavailableError) {
241
+ upstream.releaseProbeLease?.();
242
+ return formatErrorResponse(503, "server_busy", err.message);
243
+ }
235
244
  if (req.signal.aborted) {
236
245
  return formatErrorResponse(499, "client_closed_request", "search request canceled by client");
237
246
  }