@bitkyc08/opencodex 2.100.3 → 2.100.5-preview.20261118.1

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 (249) hide show
  1. package/AGENTS_INSTALL.md +23 -1
  2. package/bin/ocx.mjs +8 -1
  3. package/gui/dist/assets/{App-Dnb6VMsP.js → App-BiOGtxDS.js} +21 -20
  4. package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-BwsMejUO.js} +1 -1
  5. package/gui/dist/assets/brand-mark-BY1dgACL.js +1 -0
  6. package/gui/dist/assets/{index-DCdXsMyZ.js → index-CwHSKMdG.js} +46 -13
  7. package/gui/dist/assets/index-DJxM-imn.css +2 -0
  8. package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bds9Hb_7.js} +1 -1
  9. package/gui/dist/classic/assets/{App-DA-scMPq.js → App-CGLOiqQL.js} +20 -19
  10. package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-Da4r2O70.js} +1 -1
  11. package/gui/dist/classic/assets/{index-BqOaGLf5.js → index-CvoKXKL9.js} +46 -13
  12. package/gui/dist/classic/assets/quota-summary-DvqzfCmr.js +1 -0
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/native/ocx-child/src/cli.rs +5 -3
  16. package/native/ocx-child/src/codex_home.rs +1 -0
  17. package/native/ocx-child/src/link_ws.rs +24 -19
  18. package/native/ocx-child/src/link_ws_frame.rs +136 -50
  19. package/package.json +3 -3
  20. package/src/adapters/anthropic/per-message-effort.ts +296 -0
  21. package/src/adapters/anthropic-input-schema.ts +270 -0
  22. package/src/adapters/anthropic.ts +4 -63
  23. package/src/adapters/claude-cli/adapter.ts +1 -0
  24. package/src/adapters/command-code-tool-text.ts +9 -1
  25. package/src/adapters/command-code.ts +18 -2
  26. package/src/adapters/devin/cloud-direct/chat.ts +95 -14
  27. package/src/adapters/devin/live-models.ts +11 -1
  28. package/src/adapters/google-errors.ts +14 -2
  29. package/src/adapters/kiro/reasoning.ts +3 -0
  30. package/src/adapters/kiro-tools.ts +14 -9
  31. package/src/adapters/openai-responses/passthrough.ts +3 -1
  32. package/src/adapters/openai-responses/request-strips.ts +1 -0
  33. package/src/adapters/qoder/adapter.ts +9 -1
  34. package/src/adapters/tool-catalog-nudge.ts +1 -1
  35. package/src/adapters/zed.ts +4 -2
  36. package/src/claude/chat-tool-dispatch.ts +4 -1
  37. package/src/claude/desktop-remote-store.ts +60 -10
  38. package/src/cli/account-api.ts +4 -0
  39. package/src/cli/account-auth.ts +30 -2
  40. package/src/cli/account-extended.ts +33 -2
  41. package/src/cli/capabilities-access-remote.ts +3 -3
  42. package/src/cli/capabilities-accounts.ts +3 -3
  43. package/src/cli/capabilities-base.ts +11 -6
  44. package/src/cli/capabilities-observe-system.ts +2 -2
  45. package/src/cli/claude.ts +3 -3
  46. package/src/cli/disconnect-runtime.ts +16 -6
  47. package/src/cli/dispatch.ts +7 -1
  48. package/src/cli/index.ts +2 -2
  49. package/src/cli/link-apply-restart.ts +4 -2
  50. package/src/cli/link-routes.ts +4 -1
  51. package/src/cli/link.ts +5 -4
  52. package/src/cli/logout-command.ts +23 -4
  53. package/src/cli/preflight-exemptions.ts +3 -0
  54. package/src/cli/provider.ts +3 -2
  55. package/src/cli/registry.ts +5 -2
  56. package/src/cli/resolve.ts +23 -8
  57. package/src/cli/restart-failure.ts +11 -1
  58. package/src/cli/runtime-api.ts +4 -0
  59. package/src/cli/status.ts +4 -1
  60. package/src/cli/system-command.ts +1 -1
  61. package/src/cli/system-restart-client.ts +9 -3
  62. package/src/cli/system-settings-parity.ts +2 -1
  63. package/src/client/connect.ts +73 -11
  64. package/src/client/desktop-refusal.ts +38 -0
  65. package/src/client/lifecycle-lock.ts +29 -4
  66. package/src/client/runtime-restart.ts +27 -15
  67. package/src/client/runtime.ts +4 -2
  68. package/src/client/state.ts +14 -0
  69. package/src/clients/config-export.ts +12 -7
  70. package/src/codex/account-lifecycle.ts +3 -1
  71. package/src/codex/account-pause.ts +4 -0
  72. package/src/codex/account-runtime-state.ts +4 -0
  73. package/src/codex/auth-api/main-account-probe.ts +3 -1
  74. package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
  75. package/src/codex/auth-context.ts +40 -2
  76. package/src/codex/catalog/build-entries.ts +10 -0
  77. package/src/codex/catalog/derive-entry.ts +7 -0
  78. package/src/codex/catalog/metadata.ts +8 -0
  79. package/src/codex/catalog/native-models.ts +16 -6
  80. package/src/codex/catalog/pinned-models.ts +1 -0
  81. package/src/codex/catalog/provider-models.ts +5 -5
  82. package/src/codex/catalog/reserve-warn.ts +7 -5
  83. package/src/codex/catalog/reserve.ts +4 -3
  84. package/src/codex/catalog/retained-sync.ts +2 -0
  85. package/src/codex/catalog/routed-defaults.ts +35 -0
  86. package/src/codex/catalog-auto-refresh.ts +13 -2
  87. package/src/codex/config-drift-heal.ts +40 -12
  88. package/src/codex/config-write-lock.ts +39 -1
  89. package/src/codex/convergence.ts +2 -0
  90. package/src/codex/data/roster-pinned-models.json +346 -1
  91. package/src/codex/inject/config-write-section.ts +39 -1
  92. package/src/codex/inject/plan.ts +10 -8
  93. package/src/codex/inject/remove.ts +21 -19
  94. package/src/codex/inject/restore.ts +5 -1
  95. package/src/codex/inject-coordination.ts +58 -7
  96. package/src/codex/inject.ts +10 -12
  97. package/src/codex/journal-config-restore.ts +42 -0
  98. package/src/codex/journal.ts +62 -8
  99. package/src/codex/loopback-target.ts +22 -8
  100. package/src/codex/main-account.ts +94 -30
  101. package/src/codex/native-main-auth-file.ts +14 -0
  102. package/src/codex/native-main-credentials.ts +276 -0
  103. package/src/codex/native-main-owner.ts +3 -0
  104. package/src/codex/native-main-refresh-mode.ts +14 -1
  105. package/src/codex/quota.ts +63 -14
  106. package/src/combos/failover.ts +195 -1
  107. package/src/combos/index.ts +5 -0
  108. package/src/combos/resolve.ts +115 -19
  109. package/src/config/diagnostics.ts +3 -0
  110. package/src/config/live-reconcile.ts +6 -3
  111. package/src/config/load-degrade.ts +2 -0
  112. package/src/config/persisted-mutation.ts +2 -2
  113. package/src/config/persisted-projections.ts +18 -0
  114. package/src/config/process-state.ts +4 -3
  115. package/src/config/reserve-capability.ts +96 -0
  116. package/src/config/schema/config-schema.ts +6 -0
  117. package/src/config/schema/leaf-validators.ts +2 -0
  118. package/src/config/schema/routed-catalog-defaults.ts +49 -0
  119. package/src/config/subagent-models.ts +20 -12
  120. package/src/config.ts +7 -7
  121. package/src/desktop-update/acquire.ts +202 -0
  122. package/src/desktop-update/cli.ts +168 -0
  123. package/src/desktop-update/drain.ts +40 -0
  124. package/src/desktop-update/headless.ts +285 -0
  125. package/src/desktop-update/image.ts +85 -0
  126. package/src/desktop-update/install.ts +53 -0
  127. package/src/desktop-update/msi.ts +72 -0
  128. package/src/desktop-update/release.ts +128 -0
  129. package/src/desktop-update/runtime.ts +155 -0
  130. package/src/desktop-update/staging.ts +118 -0
  131. package/src/desktop-update/trust.ts +45 -0
  132. package/src/generated/compatibility-version.json +327 -195
  133. package/src/generated/model-metadata.ts +3 -3
  134. package/src/images/fulfill-video.ts +3 -3
  135. package/src/images/loop.ts +6 -2
  136. package/src/images/plan.ts +147 -11
  137. package/src/images/types.ts +13 -4
  138. package/src/images/xai-video-client.ts +72 -10
  139. package/src/lib/client-error-body.ts +6 -0
  140. package/src/lib/developer-role-rejection.ts +15 -0
  141. package/src/lib/gcp-adc.ts +48 -4
  142. package/src/lib/offline-resend.ts +150 -0
  143. package/src/lib/paced-stream.ts +3 -3
  144. package/src/lib/provider-outbound.ts +17 -6
  145. package/src/lib/request-failure-model.ts +2 -0
  146. package/src/lib/response-body-inactivity.ts +23 -1
  147. package/src/lib/upstream-retry.ts +39 -6
  148. package/src/link/explicit-route.ts +4 -4
  149. package/src/link/remote-windows.ts +79 -31
  150. package/src/link/residual-recovery.ts +20 -8
  151. package/src/messaging/budget.ts +23 -5
  152. package/src/messaging/remote-ports.ts +22 -10
  153. package/src/messaging/rpc.ts +4 -4
  154. package/src/oauth/antigravity-risk.ts +126 -0
  155. package/src/oauth/credential-siblings.ts +32 -0
  156. package/src/oauth/generic-account-failover.ts +113 -30
  157. package/src/oauth/generic-session-affinity.ts +10 -3
  158. package/src/oauth/index.ts +22 -14
  159. package/src/oauth/login-cli.ts +35 -1
  160. package/src/oauth/pool-kernel.ts +3 -3
  161. package/src/oauth/store.ts +38 -7
  162. package/src/providers/anthropic-billing-refusal.ts +27 -3
  163. package/src/providers/anthropic-reset-grants.ts +4 -0
  164. package/src/providers/claude-cli-usage.ts +2 -0
  165. package/src/providers/codebuddy-models.ts +11 -0
  166. package/src/providers/google-vertex-model-discovery.ts +49 -15
  167. package/src/providers/kiro-models.ts +5 -0
  168. package/src/providers/model-rename-fields.ts +2 -0
  169. package/src/providers/quota/workbuddy.ts +6 -2
  170. package/src/providers/registry/entries-core.ts +9 -3
  171. package/src/providers/registry/entries-extended.ts +20 -9
  172. package/src/providers/registry/model-seeds.ts +4 -1
  173. package/src/providers/stale-context-window-migration.ts +2 -0
  174. package/src/providers/workbuddy-credit-balance.ts +125 -16
  175. package/src/responses/citation-markers.ts +26 -23
  176. package/src/responses/effort-history.ts +732 -0
  177. package/src/routing/history/integrity.ts +41 -4
  178. package/src/server/auth-cors.ts +13 -3
  179. package/src/server/codex-model-list.ts +2 -1
  180. package/src/server/direct-local-http.ts +26 -3
  181. package/src/server/index/link-listener.ts +20 -14
  182. package/src/server/index/serve-options.ts +1 -0
  183. package/src/server/index.ts +3 -2
  184. package/src/server/link-turn.ts +17 -5
  185. package/src/server/management/config-routes.ts +39 -3
  186. package/src/server/management/link-child-preflight.ts +1 -1
  187. package/src/server/management/link-enrollment.ts +3 -3
  188. package/src/server/management/link-route-edit.ts +20 -1
  189. package/src/server/management/link-route-request.ts +11 -5
  190. package/src/server/management/oauth-account-routes.ts +43 -13
  191. package/src/server/management/provider-credential-release.ts +44 -0
  192. package/src/server/management/provider-overwrite-carry.ts +3 -0
  193. package/src/server/management/provider-routes.ts +12 -12
  194. package/src/server/management/static-catalog-probe.ts +33 -0
  195. package/src/server/management/usage-aggregate-cache.ts +6 -3
  196. package/src/server/messages-native.ts +16 -2
  197. package/src/server/proxy-liveness.ts +54 -9
  198. package/src/server/relay.ts +6 -1
  199. package/src/server/request-log-conversation.ts +8 -4
  200. package/src/server/request-log-failure-detail.ts +26 -9
  201. package/src/server/request-log.ts +5 -1
  202. package/src/server/reserve-capability-startup.ts +32 -0
  203. package/src/server/responses/adapter-continuation.ts +59 -25
  204. package/src/server/responses/adapter-delivery.ts +2 -0
  205. package/src/server/responses/adapter-dispatch.ts +39 -18
  206. package/src/server/responses/antigravity-fault-rotation.ts +24 -0
  207. package/src/server/responses/antigravity-validation-refusal.ts +43 -6
  208. package/src/server/responses/codex-tool-catalog.ts +47 -10
  209. package/src/server/responses/combo-selection-keepalive.ts +254 -0
  210. package/src/server/responses/combo-session-recall.ts +26 -1
  211. package/src/server/responses/combo-stream-preflight.ts +35 -26
  212. package/src/server/responses/core-combo-failure.ts +6 -0
  213. package/src/server/responses/core-combo-native.ts +2 -1
  214. package/src/server/responses/core-combo.ts +67 -28
  215. package/src/server/responses/core-errors.ts +9 -6
  216. package/src/server/responses/core-options.ts +10 -0
  217. package/src/server/responses/core.ts +21 -0
  218. package/src/server/responses/estimated-usage.ts +115 -0
  219. package/src/server/responses/input-admission.ts +41 -3
  220. package/src/server/responses/jev-model-invoke.ts +7 -2
  221. package/src/server/responses/passthrough-completion.ts +6 -3
  222. package/src/server/responses/passthrough-delivery.ts +47 -8
  223. package/src/server/responses/passthrough-dispatch.ts +3 -0
  224. package/src/server/responses/request-prepare.ts +9 -5
  225. package/src/server/responses/request-send-budget.ts +1 -1
  226. package/src/server/responses/request-transport.ts +10 -2
  227. package/src/server/responses/sidecar-execution.ts +11 -4
  228. package/src/service/desktop-supervision.d.mts +2 -0
  229. package/src/service/desktop-supervision.mjs +5 -0
  230. package/src/service/windows-checked-stop-live.ts +28 -5
  231. package/src/stall-timeout.ts +11 -0
  232. package/src/types/config.ts +15 -92
  233. package/src/types/provider.ts +13 -0
  234. package/src/types/request.ts +23 -3
  235. package/src/types/routed-catalog-defaults.ts +17 -0
  236. package/src/types/routing-profile.ts +90 -0
  237. package/src/types.ts +1 -0
  238. package/src/update/index.ts +1 -1
  239. package/src/usage/expected-prices.ts +35 -0
  240. package/src/usage/ledger-scanner.ts +44 -10
  241. package/src/usage/log.ts +14 -4
  242. package/src/usage/telemetry-contract.ts +1 -0
  243. package/src/web-search/loop.ts +20 -2
  244. package/src/web-search/parse.ts +2 -12
  245. package/src/web-search/passthrough-bridge.ts +7 -0
  246. package/src/web-search/sources.ts +13 -0
  247. package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
  248. package/gui/dist/assets/index-DQtCRNAw.css +0 -2
  249. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
@@ -2,8 +2,8 @@ import type { AdapterRequest } from "../../adapters/base";
2
2
  import { formatErrorResponse } from "../../bridge";
3
3
  import type { MainQuotaDispatch } from "../../codex/main-account-cache";
4
4
  import { isLocalUpstream } from "../../lib/local-upstream";
5
- import { guardResponseBodyInactivity } from "../../lib/response-body-inactivity";
6
- import { resolveStallTimeoutMs } from "../../stall-timeout";
5
+ import { guardResponseBodyInactivity, markResponseBodyInactivityGuarded } from "../../lib/response-body-inactivity";
6
+ import { explicitStallTimeoutMs, resolveStallTimeoutMs } from "../../stall-timeout";
7
7
  import type { OcxConfig } from "../../types";
8
8
  import { recordKeyWireAttemptUsage, usageFromResponsesPayload, type RequestLogContext } from "../request-log";
9
9
  import { selectProtocolSafeResetResponse, type ProtocolSafeResetRecovery } from "./combo-stream-preflight";
@@ -79,8 +79,10 @@ export function selectPassthroughResetResponse(
79
79
  const openGateway = options.request.url === "https://apis.opengateway.ai/v1/responses"
80
80
  && response.status === 200 && response.body !== null;
81
81
  const stallMs = resolveStallTimeoutMs(options.config.stallTimeoutSec, { localUpstream: isLocalUpstream(options.request.url) });
82
+ // The same budget, but reported as a stall only when the operator set it explicitly (#8206).
83
+ const explicitBudget = explicitStallTimeoutMs(options.config.stallTimeoutSec) > 0;
82
84
  const protect = (source: Response): Response =>
83
- carryResponseToolOwnership(source, guardResponseBodyInactivity(source, options.signal, stallMs).response);
85
+ carryResponseToolOwnership(source, guardResponseBodyInactivity(source, options.signal, stallMs, { explicitBudget }).response);
84
86
  const quotaOwner = (): MainQuotaDispatch | undefined =>
85
87
  admission.authCtx.kind === "main" ? admission.authCtx.mainQuotaDispatch : undefined;
86
88
  const originalOwner = quotaOwner();
@@ -101,6 +103,7 @@ export function selectPassthroughResetResponse(
101
103
  signal: options.signal,
102
104
  maxSelectionMs: stallMs > 0 ? stallMs : undefined,
103
105
  onCommit: (published, owner) => {
106
+ if (stallMs > 0) markResponseBodyInactivityGuarded(published);
104
107
  if (openGateway) guardedResetResponses.set(published, heldSince);
105
108
  if (options.delivery === "buffered-json") bufferedSelectionStarts.set(published, selectionStartedAt);
106
109
  bindPublishedMainQuotaDispatch(published, owner === "replacement" ? replacementOwner : originalOwner);
@@ -163,7 +163,12 @@ import { registerTurn, unregisterTurn, trackStreamLifetime } from "../lifecycle"
163
163
  import { relaySseEagerBounded } from "../relay-eager";
164
164
  import { readBoundedResponseBody } from "../../lib/bounded-body";
165
165
  import { idleDeadline } from "../../lib/abort";
166
- import { resolveStallTimeoutMs } from "../../stall-timeout";
166
+ import { explicitStallTimeoutMs, resolveStallTimeoutMs } from "../../stall-timeout";
167
+ import { guardResponseBodyInactivity, isResponseBodyInactivityGuarded } from "../../lib/response-body-inactivity";
168
+ import {
169
+ createEstimatedUsagePayloadRewrite, ESTIMATED_USAGE_HEADER, estimatedUsageJson, estimatesMissingUsage,
170
+ } from "./estimated-usage";
171
+ import { estimateInputTokens } from "./input-admission";
167
172
  import { formatErrorResponse } from "../../bridge";
168
173
  import {
169
174
  httpStatusFromTerminalError,
@@ -470,6 +475,11 @@ export async function deliverPassthroughResponse(
470
475
  } = nativeExchange;
471
476
  const { commitReasoningReplayServingRoute, recordTerminalOutcomes } = responseEffects;
472
477
  const { parsed, subagentQuotaFailureModel, clientRequestedStream, translatorBudget } = requestState;
478
+ // #7427: opt-in estimated usage for a provider that omits it. Client-facing only; the request log,
479
+ // spend and quota read the provider's original body.
480
+ const estimateUsage = estimatesMissingUsage(route.provider, options);
481
+ let usageInputEstimate: number | undefined;
482
+ const inputEstimate = (): number => usageInputEstimate ??= estimateInputTokens(parsed, route.modelId, route.provider);
473
483
  const { openAiSidecar } = sidecarState;
474
484
  const { requestBindings } = transportState;
475
485
 
@@ -741,18 +751,26 @@ export async function deliverPassthroughResponse(
741
751
  });
742
752
  // Capture the binding that actually served the first leg, after its permitted reselection.
743
753
  const webSearchBridgeBinding = requestBindings.get(nativeExchange.request);
754
+ // #8206: an explicit stallTimeoutSec bounds silence on the native upstream body for every
755
+ // streaming relay. Unset keeps this relay without a clock; the canonical JSON fold keeps
756
+ // its own deadlines, and reset selection already guarded the bodies it published.
757
+ const nativeSseStallMs = canonicalBufferedJson || isResponseBodyInactivityGuarded(upstreamResponse)
758
+ ? 0 : explicitStallTimeoutMs(config.stallTimeoutSec);
759
+ const nativeSseBody = nativeSseStallMs > 0
760
+ ? guardResponseBodyInactivity(upstreamResponse, upstream.signal, nativeSseStallMs, { explicitBudget: true }).response.body!
761
+ : upstreamResponse.body;
744
762
  // Repair must observe the raw first leg before the bridge suppresses an intercepted search
745
763
  // lifecycle. Otherwise a provider that leaves that complete call open never arms repair's
746
764
  // grace timer, so the bridge cannot execute the search or begin its continuation.
747
765
  let passthroughSseBody = terminalRepairPolicy
748
766
  ? relayResponsesSseWithTerminalRepair(
749
- upstreamResponse.body,
767
+ nativeSseBody,
750
768
  upstream,
751
769
  terminalRepairPolicy,
752
770
  translatorBudget,
753
771
  options.responsesTerminalRepairScheduler, logCtx,
754
772
  )
755
- : upstreamResponse.body;
773
+ : nativeSseBody;
756
774
  passthroughSseBody = webSearchBridgePlan
757
775
  ? createPassthroughWebSearchBridgeStream({
758
776
  plan: webSearchBridgePlan,
@@ -784,17 +802,24 @@ export async function deliverPassthroughResponse(
784
802
  );
785
803
  // The same provider can leave a complete continuation open without a terminal, which
786
804
  // stalls the bridge's decide loop exactly like the first leg — so every leg gets the
787
- // same repair, not only the intercepted first one.
788
- if (!terminalRepairPolicy || !continuation.ok || !continuation.body) return continuation;
805
+ // same repair and the same explicit silence clock, not only the intercepted first one.
806
+ if (!continuation.ok || !continuation.body) return continuation;
807
+ // A continuation is a fresh upstream body: guard it from the explicit budget even when
808
+ // reset selection already guarded the first leg (and so left nativeSseStallMs at 0).
809
+ const continuationStallMs = explicitStallTimeoutMs(config.stallTimeoutSec);
810
+ const guardedContinuation = continuationStallMs > 0
811
+ ? guardResponseBodyInactivity(continuation, upstream.signal, continuationStallMs, { explicitBudget: true }).response
812
+ : continuation;
813
+ if (!terminalRepairPolicy) return guardedContinuation;
789
814
  return new Response(
790
815
  relayResponsesSseWithTerminalRepair(
791
- continuation.body,
816
+ guardedContinuation.body!,
792
817
  upstream,
793
818
  terminalRepairPolicy,
794
819
  translatorBudget,
795
820
  options.responsesTerminalRepairScheduler, logCtx,
796
821
  ),
797
- continuation,
822
+ guardedContinuation,
798
823
  );
799
824
  },
800
825
  execute: createPassthroughWebSearchBridgeExecutor(webSearchBridgePlan, {
@@ -981,7 +1006,12 @@ export async function deliverPassthroughResponse(
981
1006
  (!canonicalBufferedJson || !options.comboAttempt) && isLocalCodexImageClient(req.headers, options.admission?.kind, options.inboundWire)
982
1007
  ? createHostedImageDisplayRewrite()
983
1008
  : undefined,
1009
+ // Last, so it sees the response the client receives; never on the canonical JSON fold.
1010
+ estimateUsage && !canonicalBufferedJson
1011
+ ? payloadRewriteAsBlockRewrite(createEstimatedUsagePayloadRewrite(inputEstimate, route.modelId))
1012
+ : undefined,
984
1013
  ].filter((rewrite): rewrite is NonNullable<typeof rewrite> => rewrite !== undefined);
1014
+ if (estimateUsage && !canonicalBufferedJson) headers.set(ESTIMATED_USAGE_HEADER, "when-missing");
985
1015
  const clientBlockRewrite = blockRewrites.length > 0
986
1016
  ? composeSseBlockRewrites(...blockRewrites)
987
1017
  : undefined;
@@ -1209,7 +1239,7 @@ export async function deliverPassthroughResponse(
1209
1239
  }
1210
1240
 
1211
1241
  const relayPlatform = relayPlatformForTests ?? process.platform;
1212
- // A Remote Link turn while the link WebSocket feature is on reads its upstream only as its client drains (#8601);
1242
+ // Every relayed Remote Link turn reads its upstream only as its client drains (#8601), feature switch or not;
1213
1243
  // every other request keeps the relays' read-ahead below. Its chunks travel in slices, and the paced mark makes the
1214
1244
  // tee, the eager relay and every stage after them read one slice at a time as the client asks (src/lib/paced-stream.ts).
1215
1245
  if (linkTurnPacesReads(logCtx)) passthroughSseBody = markPacedStream(sliceChunks(passthroughSseBody, LINK_PACED_SLICE_BYTES));
@@ -1507,6 +1537,15 @@ export async function deliverPassthroughResponse(
1507
1537
  throw error;
1508
1538
  } finally { imageDisplay.dispose?.(); }
1509
1539
  }
1540
+ if (estimateUsage && upstreamResponse.ok) {
1541
+ const estimated = estimatedUsageJson(clientJson, inputEstimate(), route.modelId);
1542
+ if (estimated !== undefined) {
1543
+ clientJson = estimated;
1544
+ headers.set(ESTIMATED_USAGE_HEADER, "true");
1545
+ // The request-log finalizer parses the delivered body again; keep the estimate out of it.
1546
+ logCtx.usageEstimatedForClient = true;
1547
+ }
1548
+ }
1510
1549
  // #875: the transport-neutral reliability policy forced a bounded JSON
1511
1550
  // upstream for a client that asked for SSE. Reframe the completed JSON
1512
1551
  // as the canonical terminal SSE sequence (created → output_item.done →
@@ -139,6 +139,7 @@ import { classifyTransportFailureKind, transportErrorCode } from "../../lib/upst
139
139
  import { captureAccountAutoPauseAttempt, wasAccountAutoPaused, wasPermanentAccountRefusal } from "../../oauth/account-auto-pause";
140
140
  import { codexFailureWindowOutcomeMeta, recordCodexUpstreamOutcome } from "../../codex/routing";
141
141
  import { describeUpstreamConnectFailure } from "./upstream-error";
142
+ import { createProviderOfflineResendWait } from "../../lib/offline-resend";
142
143
  import type { OpaqueBlobRecoveryGuard } from "./core-opaque-recovery";
143
144
  import {
144
145
  rateLimitRetryPolicyFor,
@@ -1047,6 +1048,8 @@ export async function preparePassthroughExchange(
1047
1048
  // by `onPhysicalDispatch`; a reporter as well would count them twice.
1048
1049
  ...(receiptMode ? {} : { onSendsConsumed: initialAccounting.report }),
1049
1050
  claimAmbiguousResend: claimPreHeaderResend,
1051
+ // A combo fails over to another member instead of waiting once per target.
1052
+ offlineWait: options.comboAttempt ? undefined : createProviderOfflineResendWait(route.providerName, route.provider, request.url, config.offlineResendWaitSec),
1050
1053
  },
1051
1054
  );
1052
1055
  } catch (err) {
@@ -27,7 +27,7 @@ import {
27
27
  unreadableEncryptedAgentTaskResponse,
28
28
  } from "./core-errors";
29
29
  import { parseSyntheticRowId } from "../fast-row";
30
- import { resolveComboId, comboIdFromRawBody, comboExclusionReasons, NoAvailableComboTargetsError, pickComboTarget } from "../../combos";
30
+ import { resolveComboId, comboIdFromRawBody, comboExclusion, NoAvailableComboTargetsError, pickComboTarget } from "../../combos";
31
31
  import { INTERCEPT_TARGET_UNAVAILABLE_CODE, interceptTargetUnavailableResponse, resolveChosenTarget, resolveShadowCallTarget } from "./shadow-target-availability";
32
32
  import {
33
33
  MEMORY_MODEL_TARGET_UNAVAILABLE_CODE,
@@ -190,6 +190,7 @@ import {
190
190
 
191
191
  import { redactHostedImageDisplayPaths } from "../responses-hosted-image-display";
192
192
  import { eagerCodexToolCatalogSurface, warnEagerCodexToolCatalog } from "./codex-tool-catalog";
193
+ import { codexTurnStartsNewHistory } from "../../adapters/anthropic/per-message-effort";
193
194
 
194
195
  /** Policy-routing evidence. The direct lane's settings-only body has no conversation to scan. */
195
196
  function routeEvidence(options: Pick<HandleResponsesOptions, "directRequest">, parsed: OcxParsedRequest): PolicyRequestEvidence {
@@ -553,6 +554,8 @@ export async function prepareResponsesRequest(
553
554
  parsed._anthropicInbound = true;
554
555
  if (parsed.options.textFormat?.type === "json_schema") parsed._structuredOutputConformance = true;
555
556
  }
557
+ // Codex's own "new" turn metadata, for the experimental Anthropic perMessageEffort option (#6895).
558
+ parsed._codexNewHistory = codexTurnStartsNewHistory(body, req.headers, options.inboundTransport);
556
559
  parsed._promptCacheKeyIsSharedCohort = options.promptCacheKeyIsSharedCohort;
557
560
  // The body may have been rebuilt since the inbound observation (previous-response
558
561
  // expansion); alias the parsed raw body to the same draft so the outbound
@@ -736,7 +739,7 @@ export async function prepareResponsesRequest(
736
739
  });
737
740
  if (!pick) {
738
741
  throw new NoAvailableComboTargetsError(candidate.combo.comboId,
739
- comboExclusionReasons(config, candidate.combo.comboId, target => !target.metered));
742
+ comboExclusion(config, candidate.combo.comboId, target => !target.metered));
740
743
  }
741
744
  const routed = routeConcreteModel(config, `${pick.target.provider}/${pick.target.model}`);
742
745
  candidate = { ...routed, combo: pick, routeKind: "combo", routeReason: routed.routeReason === "blocked-model-redirect" ? "blocked-model-redirect" : "combo-pick" };
@@ -903,7 +906,7 @@ export async function prepareResponsesRequest(
903
906
  if (policyRefusal) return policyRefusal;
904
907
  if (err instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(err, logCtx));
905
908
  if (err instanceof NoAvailableComboTargetsError) {
906
- return comboUnavailable(err.comboId, undefined, err.reasons);
909
+ return comboUnavailable(err.comboId, undefined, err.exclusion);
907
910
  }
908
911
  if (err instanceof NoEligiblePolicyCandidateError) {
909
912
  // Persist the evaluation trace (per-candidate exclusions + the
@@ -1123,7 +1126,7 @@ export async function prepareResponsesRequest(
1123
1126
  if (policyRefusal) return policyRefusal;
1124
1127
  if (err instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(err, logCtx));
1125
1128
  if (err instanceof NoAvailableComboTargetsError) {
1126
- return comboUnavailable(err.comboId, undefined, err.reasons);
1129
+ return comboUnavailable(err.comboId, undefined, err.exclusion);
1127
1130
  }
1128
1131
  if (err instanceof NoEligiblePolicyCandidateError) {
1129
1132
  logCtx.routeDecision = err.trace;
@@ -1199,6 +1202,7 @@ export async function prepareResponsesRequest(
1199
1202
  "_reasoningReplayScope",
1200
1203
  "_nativeReasoningRetention",
1201
1204
  "_cursorIsolateConversation",
1205
+ "_codexNewHistory",
1202
1206
  ];
1203
1207
  for (const key of kept) {
1204
1208
  if (parsed[key] !== undefined) {
@@ -1347,7 +1351,7 @@ export async function prepareResponsesRequest(
1347
1351
  if (policyRefusal) return policyRefusal;
1348
1352
  if (err instanceof AdmissionModelDeniedError) return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(err, logCtx));
1349
1353
  if (err instanceof NoAvailableComboTargetsError) {
1350
- return comboUnavailable(err.comboId, undefined, err.reasons);
1354
+ return comboUnavailable(err.comboId, undefined, err.exclusion);
1351
1355
  }
1352
1356
  if (err instanceof NoEligiblePolicyCandidateError) {
1353
1357
  logCtx.routeDecision = err.trace;
@@ -321,7 +321,7 @@ export function createResponsesSendBudget(
321
321
  /**
322
322
  * One credential hop of this logical request, admitted by the INTERSECTION of two bounds.
323
323
  *
324
- * The snapshotted generic OAuth roster cap and `ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST`
324
+ * The snapshotted generic OAuth and Anthropic roster caps
325
325
  * bound rotation within one credential roster. What neither
326
326
  * can see is everything else this request already sent, so three hops layered on a spent
327
327
  * budget still reached upstream three more times. A hop now happens only when its own layer
@@ -36,6 +36,7 @@ import type { AnthropicAccountSelectionReason } from "../../oauth/anthropic-rout
36
36
  import { resolveAnthropicModelRouteForInstance, routeCandidates, type AnthropicRouteDecision } from "../../oauth/anthropic-model-routes";
37
37
  import {
38
38
  anthropicRoutingFor,
39
+ ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST,
39
40
  AnthropicAccountCooldownError,
40
41
  formatAnthropicProviderForLog,
41
42
  } from "../../oauth/anthropic-routing";
@@ -1425,10 +1426,17 @@ export async function prepareResponsesTransport(
1425
1426
  ]).size : 0;
1426
1427
  const fundedAccounts = Math.min(genericRosterSize, GENERIC_OAUTH_MAX_ACCOUNTS_PER_REQUEST);
1427
1428
  const genericFailoverLimit = Math.max(GENERIC_OAUTH_MAX_FAILOVERS_PER_REQUEST, fundedAccounts - 1);
1428
- if (fundingAccountId) expandInferenceOAuthSendBudget(options.sendBudget, fundedAccounts);
1429
+ const anthropicRosterSize = anthropicRouting && anthropicPoolAccountId ? new Set([
1430
+ anthropicPoolAccountId,
1431
+ ...anthropicRouting.getEligibleAnthropicAccounts(Date.now(), route.modelId),
1432
+ ]).size : 0;
1433
+ const anthropicFundedAccounts = Math.min(anthropicRosterSize, GENERIC_OAUTH_MAX_ACCOUNTS_PER_REQUEST);
1434
+ const anthropicFailoverLimit = Math.max(ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST, anthropicFundedAccounts - 1);
1435
+ if (fundingAccountId || anthropicPoolAccountId)
1436
+ expandInferenceOAuthSendBudget(options.sendBudget, Math.max(fundedAccounts, anthropicFundedAccounts));
1429
1437
 
1430
1438
  return {
1431
- genericFailoverLimit,
1439
+ genericFailoverLimit, anthropicFailoverLimit,
1432
1440
  isOAuth401ReplayProvider,
1433
1441
  get sentOAuthSnapshot(): OAuthAccessSnapshot | undefined {
1434
1442
  return sentOAuthSnapshot;
@@ -44,8 +44,8 @@ import { noteKiroMonthlyRefusal, noteKiroServedSuccess } from "../../providers/k
44
44
  import { persistKiroAccountState } from "../../providers/kiro-account-state-disk";
45
45
  import { anthropicPoolCooldownResponse, readDisplaySafeErrorText } from "./core-errors";
46
46
  import { sidecarContextOverflowResponse } from "./context-overflow";
47
+ import { emptyCompletionRetryEnabled } from "./empty-completion-guard";
47
48
  import {
48
- ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST,
49
49
  anthropicRoutingFor,
50
50
  formatAnthropicProviderForLog,
51
51
  } from "../../oauth/anthropic-routing";
@@ -62,6 +62,7 @@ import { trackStreamLifetime } from "../lifecycle";
62
62
  import { isAntigravityRawValidationRefusal } from "./antigravity-validation-refusal";
63
63
  import { createSidecarSendBudget } from "./sidecar-send-budget";
64
64
  import { stripReplayedSearchPairs } from "../../web-search/sidecar-search-replay";
65
+ import { settleAnthropicPerMessageEffort, shareAnthropicPerMessageEffortTurn } from "../../adapters/anthropic/per-message-effort";
65
66
 
66
67
  /** One responsibility of the Responses request pipeline; state owners are explicit. */
67
68
  export async function executeResponsesSidecars(
@@ -85,7 +86,7 @@ export async function executeResponsesSidecars(
85
86
  | "adapter"
86
87
  | "genericFailoverAccountId"
87
88
  | "genericFailovers"
88
- | "genericFailoverLimit"
89
+ | "genericFailoverLimit" | "anthropicFailoverLimit"
89
90
  | "replayOAuthCredentialSnapshot"
90
91
  | "applyFailoverSnapshot"
91
92
  | "anthropicInstance"
@@ -109,7 +110,7 @@ export async function executeResponsesSidecars(
109
110
  | "notifyResponseComplete"
110
111
  | "cancelResponseCompletion"
111
112
  >,
112
- sendBudgetState: Pick<ResponsesSendBudget, "sendBudgetExhausted" | "reserveCredentialHop" | "refundableAdapterDispatchBudget" | "adapterDispatchBudget" | "noteInitialDispatch" | "noteAdapterPhysicalSend" | "noteAdapterRecoveryWithheld" | "pendingHopPermit" | "dispatchSidecarSend">,
113
+ sendBudgetState: Pick<ResponsesSendBudget, "initialSendAllowance" | "sendBudgetExhausted" | "reserveCredentialHop" | "refundableAdapterDispatchBudget" | "adapterDispatchBudget" | "noteInitialDispatch" | "noteAdapterPhysicalSend" | "noteAdapterRecoveryWithheld" | "pendingHopPermit" | "dispatchSidecarSend">,
113
114
  ) {
114
115
  const { config, options, logCtx } = requestContext;
115
116
  const antigravityPoolActivated = requestState.route.providerName === "google-antigravity"
@@ -238,6 +239,8 @@ export async function executeResponsesSidecars(
238
239
  // Replayed search pairs call the synthetic web_search tool only the sidecar declares (#7269).
239
240
  if (!wsPlan) stripReplayedSearchPairs(parsed);
240
241
  const vidPlan = !routedCompaction ? await planVideoBridge(config, parsed, route.provider) : undefined;
242
+ // Hosted loops rebuild per iteration from spread copies; they share one per-message effort turn (#6895).
243
+ if (wsPlan || imgPlan || vidPlan) shareAnthropicPerMessageEffortTurn(parsed);
241
244
  const canRunWebSearch = !!wsPlan && !transportState.adapter.runTurn;
242
245
  let sidecarOutputStarted = false;
243
246
  const sidecarHasCommittedOutput = () => sidecarOutputStarted
@@ -419,7 +422,7 @@ export async function executeResponsesSidecars(
419
422
  config, accountId: transportState.anthropicPoolAccountId, sessionKey: anthropicSessionKey,
420
423
  model: route.modelId, requestKey: transportState, decision: transportState.anthropicRouteDecision, currentDecision: currentAnthropicRouteDecision, signal: options.abortSignal,
421
424
  allow429Recovery: !sidecarHasCommittedOutput(), allowAccountRefusal: !sidecarHasCommittedOutput(),
422
- canRetry: hop.allowed && transportState.anthropicPoolFailovers < ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST,
425
+ canRetry: hop.allowed && transportState.anthropicPoolFailovers < transportState.anthropicFailoverLimit,
423
426
  });
424
427
  if (!nextAccountId) {
425
428
  hop.permit?.release();
@@ -500,6 +503,7 @@ export async function executeResponsesSidecars(
500
503
  if (existing) existing();
501
504
  else {
502
505
  const prepaid = sendBudgetState.pendingHopPermit;
506
+ if (anthropicInstance && !prepaid && sendBudgetState.initialSendAllowance(1) === 0) throw new SendBudgetExhaustedError();
503
507
  sendBudgetState.pendingHopPermit = undefined;
504
508
  sendBudgetState.noteInitialDispatch(prepaid);
505
509
  }
@@ -624,6 +628,7 @@ export async function executeResponsesSidecars(
624
628
  escapeMemoryCitationTags: inboundWire !== "chat" && inboundWire !== "anthropic",
625
629
  onCompletedResponse: (response, providerState) => {
626
630
  if (!options.abortSignal?.aborted) thinkingRecovery.rememberSuccess(response);
631
+ settleAnthropicPerMessageEffort(parsed, response, transportState.adapter.name);
627
632
  const served = transportState.replayOAuthCredentialSnapshot;
628
633
  if (route.providerName === "kiro" && response.status === "completed" && served
629
634
  && noteKiroServedSuccess(served.accountId, served.generation)) persistKiroAccountState();
@@ -697,6 +702,7 @@ export async function executeResponsesSidecars(
697
702
  ...sidecarBudget.fetchOptions(transportState.adapter),
698
703
  })(input, init)) as typeof globalThis.fetch;
699
704
  const loopResponse = await runWithWebSearch({
705
+ emptyCompletionRetry: emptyCompletionRetryEnabled(config) && !options.comboAttempt && !routedCompaction,
700
706
  dispatchSidecarSend: sendBudgetState.dispatchSidecarSend,
701
707
  parsed, adapter: transportState.adapter,
702
708
  ...(webSearchAdvisor ? { advisor: createAdvisorSidecarStep(webSearchAdvisor as Parameters<typeof createAdvisorSidecarStep>[0]) } : {}),
@@ -766,6 +772,7 @@ export async function executeResponsesSidecars(
766
772
  retryOn429Policy: route.providerName === "kiro" && isGenericOAuthFailoverEnabled(config, "kiro")
767
773
  ? null : rateLimitRetryPolicyFor(route.provider),
768
774
  onCompletedResponse: response => {
775
+ settleAnthropicPerMessageEffort(parsed, response, transportState.adapter.name);
769
776
  const served = transportState.replayOAuthCredentialSnapshot;
770
777
  if (route.providerName === "kiro" && response.status === "completed" && served
771
778
  && noteKiroServedSuccess(served.accountId, served.generation)) persistKiroAccountState();
@@ -47,6 +47,8 @@ export const procfs: ProcReader;
47
47
  export function processIdentity(pid: number, execute?: DesktopSupervisionDeps["run"], onExecutable?: (path: string) => void):
48
48
  { parent: number; executable: string } | null;
49
49
  export function windowsPowerShellPath(resolveSystemDirectory?: () => string): string;
50
+ /** Trusted Windows system directory (GetSystemDirectoryW on Bun); throws off Windows. */
51
+ export function trustedWindowsSystemDirectory(): string;
50
52
  /** Pure consistency check over loaded-module paths; throws unless exactly one well-formed
51
53
  * namesake per KnownDLL shares one parent directory. Exported for tests. */
52
54
  export function windowsSystemDirectoryFromSharedObjects(loaded: unknown): string;
@@ -102,6 +102,11 @@ function resolveWindowsSystemDirectory() {
102
102
  return (windowsSystemDirectoryCache = directory);
103
103
  }
104
104
 
105
+ /** The trusted system directory, for callers that run another system binary (msiexec). */
106
+ export function trustedWindowsSystemDirectory() {
107
+ return resolveWindowsSystemDirectory();
108
+ }
109
+
105
110
  function resolveWindowsSystemDirectoryViaFfi() {
106
111
  const { dlopen, ptr } = createRequire(import.meta.url)("bun:ffi");
107
112
  const lib = dlopen("kernel32.dll", { GetSystemDirectoryW: { args: ["ptr", "u32"], returns: "u32" } });
@@ -121,14 +121,25 @@ export function classifyTaskEnd(result: WindowsStopCommandResult): WindowsTaskEn
121
121
  return toWindowsSchtasksError(error, ["/end", "/tn", TASK]).reason === "access-denied" ? "denied" : "failed";
122
122
  }
123
123
 
124
- /** schtasks /query /fo CSV /nh status column. Localized values fall back to PowerShell. */
124
+ /**
125
+ * Status words of `schtasks /query /fo CSV /nh`. schtasks localizes the column from its .mui
126
+ * resources, and the PowerShell fallback cannot start inside Part A's 1 s manager-state cap on a
127
+ * cold machine (#8863), so the words observed from shipped resources are read here: zh-CN from
128
+ * System32\zh-CN\schtasks.exe.mui, ko-KR from two machines. Any other word stays unknown and
129
+ * falls back to Get-ScheduledTask's locale-independent State enum.
130
+ */
131
+ const TASK_CSV_RUNNING = new Set(["running", "正在运行", "실행 중"]);
132
+ const TASK_CSV_NOT_RUNNING = new Set(["ready", "disabled", "queued", "就绪", "已禁用", "已排队", "준비"]);
133
+ /** ERROR_ACCESS_DENIED in the locales whose status words are read above (zh-CN, ko-KR). */
134
+ const LOCALIZED_ACCESS_DENIED = /拒绝访问|액세스가 거부/;
135
+
125
136
  export function parseTaskCsvState(csv: string): "running" | "not-running" | "unknown" {
126
137
  for (const line of csv.split(/\r?\n/)) {
127
138
  if (!windowsSchedulerCsvIncludesTask(line, TASK)) continue;
128
139
  const fields = [...line.matchAll(/"([^"]*)"/g)].map(match => match[1]!.trim());
129
- const status = fields[fields.length - 1] ?? "";
130
- if (/^running$/i.test(status)) return "running";
131
- if (/^(ready|disabled|queued)$/i.test(status)) return "not-running";
140
+ const status = (fields[fields.length - 1] ?? "").normalize("NFC").toLowerCase();
141
+ if (TASK_CSV_RUNNING.has(status)) return "running";
142
+ if (TASK_CSV_NOT_RUNNING.has(status)) return "not-running";
132
143
  return "unknown";
133
144
  }
134
145
  return "unknown";
@@ -291,7 +302,19 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption
291
302
  },
292
303
  async endTask(timeoutMs) {
293
304
  if (!gate()) return "failed";
294
- return classifyTaskEnd(await run("schtasks", ["/end", "/tn", TASK], timeoutMs));
305
+ const started = Date.now();
306
+ const ended = await run("schtasks", ["/end", "/tn", TASK], timeoutMs);
307
+ const verdict = classifyTaskEnd(ended);
308
+ // schtasks localizes "no running instance" as well (#8863). After a real nonzero exit, an
309
+ // idle task is not-running only when its own CSV state says so; a running or unreadable
310
+ // state, a timeout, or an /end that never ran keeps the failure. A localized denial stays a
311
+ // denial: Part A stops at it whatever the task's state.
312
+ if (verdict !== "failed" || ended.timedOut || ended.status === null) return verdict;
313
+ if (LOCALIZED_ACCESS_DENIED.test(ended.stderr + "\n" + ended.stdout)) return "denied";
314
+ const left = Math.floor(timeoutMs - (Date.now() - started));
315
+ if (left < 1) return "failed";
316
+ const csv = await run("schtasks", ["/query", "/tn", TASK, "/fo", "CSV", "/nh"], left);
317
+ return csv.status === 0 && !csv.timedOut && parseTaskCsvState(csv.stdout) === "not-running" ? "not-running" : "failed";
295
318
  },
296
319
  async taskState(timeoutMs) {
297
320
  const started = Date.now();
@@ -44,6 +44,17 @@ export function resolveStallTimeoutMs(configuredSec: number | undefined, options
44
44
  return resolveStallTimeoutSec(configuredSec, options) * 1_000;
45
45
  }
46
46
 
47
+ /**
48
+ * The operator's explicit positive stall budget in milliseconds, or `0` when the budget is unset or
49
+ * non-positive. Native Responses SSE relays arm their silence clock from this value only (#8206):
50
+ * an explicit value applies to local and public upstreams alike, and leaving the field unset keeps
51
+ * that relay without a silence clock, as it was before the budget was enforced there.
52
+ */
53
+ export function explicitStallTimeoutMs(configuredSec: number | undefined): number {
54
+ if (typeof configuredSec !== "number" || !Number.isFinite(configuredSec) || configuredSec <= 0) return 0;
55
+ return resolveStallTimeoutMs(configuredSec);
56
+ }
57
+
47
58
  /** Header-arrival (connect) deadline applied to public upstreams when the operator sets none. */
48
59
  export const DEFAULT_CONNECT_TIMEOUT_MS = 200_000;
49
60
 
@@ -7,9 +7,15 @@ import type { MultiAgentMode } from "./multi-agent";
7
7
  import type { OcxTelemetryConfig } from "./telemetry";
8
8
  import type { OcxClaudeCodeToolLoadingConfig } from "./claude-tool-loading";
9
9
  import type { OcxLinkHomeConfig, OcxLinkTransportConfig } from "./link";
10
+ import type { OcxRoutingProfileConfig } from "./routing-profile";
10
11
  export type { AnthropicAccountPoolConfig, AnthropicModelRoute, OcxAccountPoolRotationStrategy, OcxAccountPoolQuotaWindow } from "./anthropic-account-pool";
11
12
  export type { OcxFallbackConfig, OcxFallbackDeviceConfig, OcxFallbackKind, OcxFallbackSwitches } from "./fallback";
12
13
  export type { OcxClaudeCodeToolLoadingConfig } from "./claude-tool-loading";
14
+ export type {
15
+ OcxRoutingUnknownEvidenceMode, OcxRoutingProfileCandidate, OcxRoutingProfileRequirements, OcxRoutingProfileOptimize,
16
+ OcxRoutingUnknownCostCapMode, OcxRoutingProfileLimits, OcxRoutingProfileUnknownEvidence,
17
+ OcxRoutingProfileCompatibilitySuite, OcxRoutingProfileCompatibility, OcxRoutingProfileConfig,
18
+ } from "./routing-profile";
13
19
 
14
20
  /** Public inference API exposure. Responses and Chat Completions are always served. */
15
21
  export interface OcxApiSurfacesConfig {
@@ -855,10 +861,10 @@ export interface OcxConfig extends OcxLinkHomeConfig {
855
861
  * Unknown windows use maxTokens alone; overflow is archived locally with a path notice.
856
862
  * Native and opaque compaction output keep their existing protocols. */
857
863
  reasoningRetention?: { enabled?: boolean; maxContextPercent?: number; maxTokens?: number };
858
- /** Canonical ChatGPT reasoning replay allowances; both default off. */
859
- nativeReasoningRetention?: { modelSwitch?: boolean; accountSwitch?: boolean };
864
+ nativeReasoningRetention?: { modelSwitch?: boolean; accountSwitch?: boolean }; // canonical ChatGPT reasoning replay allowances; both default off
860
865
  /** Per-root fan-out ceilings (src/lib/workflow-budget.ts); omitted fields keep 8 / 256 / 64. */
861
866
  workflowBudget?: { maxConcurrentChildren?: number; maxPhysicalSends?: number; maxDistinctChildren?: number };
867
+ routedCatalogDefaults?: import("./routed-catalog-defaults").OcxRoutedCatalogDefaultsConfig; // #6872; provider/model declarations win
862
868
  /** Explicit opt-in; resumes Observe only using an existing trusted certificate and endpoints. */
863
869
  desktopCompatibility?: { startOnProxyStart: boolean };
864
870
  /**
@@ -1068,6 +1074,7 @@ export interface OcxConfig extends OcxLinkHomeConfig {
1068
1074
  * can hold the connection silent for minutes on a large prompt before the first header arrives.
1069
1075
  */
1070
1076
  connectTimeoutMs?: number;
1077
+ /** Opt-in (#7958): seconds (max 300) to wait for DNS after a pre-connect failure, then resend once. Unset or 0 is off. */ offlineResendWaitSec?: number;
1071
1078
  /** Graceful shutdown drain timeout (ms). Active turns are aborted after this deadline. Default 5000. */
1072
1079
  shutdownTimeoutMs?: number;
1073
1080
  /** Advertise supports_websockets so Codex opens the WS endpoint. Default false; set true to opt in. */ websockets?: boolean;
@@ -1103,6 +1110,10 @@ export interface OcxConfig extends OcxLinkHomeConfig {
1103
1110
  * non-loopback binds, whose admission token contract is unchanged.
1104
1111
  */
1105
1112
  codexDesktopAuthless?: boolean;
1113
+ /** Luna Reserve (#4961): seeded once from `codexDesktopAuthless`, then independent (absent = off). Grants no entitlement. */
1114
+ codexReserveEnabled?: boolean;
1115
+ /** Internal marker recording that one-time seed. */
1116
+ codexReserveMigration?: number;
1106
1117
  /**
1107
1118
  * Opt into Codex-owned client compaction while keeping OpenCodex routing. On an authenticated
1108
1119
  * loopback bind, inject the dedicated `opencodex` model provider instead of overriding the
@@ -1574,96 +1585,6 @@ export interface OcxComboConfig {
1574
1585
  sessionPin?: import("../combos/jev-session-pin-config").JevSessionPinConfig | null;
1575
1586
  }
1576
1587
 
1577
- export type OcxRoutingUnknownEvidenceMode = "allow" | "penalize" | "exclude";
1578
-
1579
- export interface OcxRoutingProfileCandidate {
1580
- provider: string;
1581
- model: string;
1582
- }
1583
-
1584
- export interface OcxRoutingProfileRequirements {
1585
- /** Minimum model context window in tokens. */
1586
- minContextWindow?: number;
1587
- /** Minimum remaining quota headroom fraction (0..1). */
1588
- minQuotaHeadroom?: number;
1589
- tools?: boolean;
1590
- imageInput?: boolean;
1591
- structuredOutput?: boolean;
1592
- reasoningEffort?: string;
1593
- serviceTier?: string;
1594
- localOnly?: boolean;
1595
- remoteAllowed?: boolean;
1596
- /** Special encrypted Codex task readability (ChatGPT forward pool). */
1597
- encryptedCodexTasks?: boolean;
1598
- }
1599
-
1600
- export interface OcxRoutingProfileOptimize {
1601
- latency?: number;
1602
- health?: number;
1603
- cost?: number;
1604
- quota?: number;
1605
- }
1606
-
1607
- /**
1608
- * Policy for the hard cost ceiling when a candidate has no finite cost
1609
- * estimate. `"allow"` (default) preserves the documented dry-run contract:
1610
- * the cap only excludes evidence known to exceed it, and the candidate's
1611
- * `cost.capOutcome` is `"unknown-allowed"`. `"exclude"` makes the ceiling
1612
- * fail-closed (`cost-limit-unknown` + `capOutcome: "unknown-excluded"`).
1613
- */
1614
- export type OcxRoutingUnknownCostCapMode = "allow" | "exclude";
1615
-
1616
- export interface OcxRoutingProfileLimits {
1617
- /** Hard per-request estimated-cost ceiling in USD. */
1618
- maxEstimatedCostUsd?: number;
1619
- /**
1620
- * How `maxEstimatedCostUsd` behaves when the estimate is unknown.
1621
- * Defaults to `"allow"` (eligible + `cost.capOutcome: "unknown-allowed"`);
1622
- * opt in to `"exclude"` for a true hard ceiling.
1623
- */
1624
- onUnknownCost?: OcxRoutingUnknownCostCapMode;
1625
- }
1626
-
1627
- export interface OcxRoutingProfileUnknownEvidence {
1628
- capability?: OcxRoutingUnknownEvidenceMode;
1629
- health?: OcxRoutingUnknownEvidenceMode;
1630
- quota?: OcxRoutingUnknownEvidenceMode;
1631
- cost?: OcxRoutingUnknownEvidenceMode;
1632
- }
1633
-
1634
- export interface OcxRoutingProfileCompatibilitySuite {
1635
- suiteId: string;
1636
- evidenceLayer: "protocol_conformance" | "live_route_compatibility";
1637
- }
1638
-
1639
- export interface OcxRoutingProfileCompatibility {
1640
- requiredSuites?: OcxRoutingProfileCompatibilitySuite[];
1641
- minStatus?: "PROBED" | "VERIFIED";
1642
- maxEvidenceAgeMs?: number;
1643
- unknownEvidence?: OcxRoutingUnknownEvidenceMode;
1644
- degradedEvidence?: OcxRoutingUnknownEvidenceMode;
1645
- }
1646
-
1647
- export interface OcxRoutingProfileConfig {
1648
- /**
1649
- * Explicit candidate allowlist (`provider/model` refs). No implicit
1650
- * expansion in v1.
1651
- */
1652
- candidates: OcxRoutingProfileCandidate[];
1653
- /** Optional public model name replacing the default `policy/<id>` slug. */
1654
- alias?: string;
1655
- /** Hard requirements evaluated before scoring. */
1656
- require?: OcxRoutingProfileRequirements;
1657
- /** Optimization weights; normalized deterministically. */
1658
- optimize?: OcxRoutingProfileOptimize;
1659
- limits?: OcxRoutingProfileLimits;
1660
- /** How unknown evidence is handled per dimension. */
1661
- unknownEvidence?: OcxRoutingProfileUnknownEvidence;
1662
- /** Optional Compatibility Lab policy (CL-06). */
1663
- compatibility?: OcxRoutingProfileCompatibility;
1664
- }
1665
-
1666
-
1667
1588
  export interface OcxTokenGuardianConfig {
1668
1589
  /** Global kill-switch. Default false — the guardian does nothing unless explicitly enabled. */
1669
1590
  enabled?: boolean;
@@ -1702,6 +1623,8 @@ export interface OcxImagesConfig {
1702
1623
  artifactsKeepCount?: number;
1703
1624
  /** Master switch for the video bridge. Default false — must be explicitly opted in. */
1704
1625
  videoBridgeEnabled?: boolean;
1626
+ /** Optional API-key provider that serves `video_gen` (its own baseUrl and key). Unset keeps xAI; an unusable value fails closed. */
1627
+ videoProvider?: string;
1705
1628
  /** Model for xAI video generation. Default "grok-imagine-video". */
1706
1629
  videoBridgeModel?: string;
1707
1630
  /** Max video-gen rounds before forced-final. Default 2 (video is slower than image). */
@@ -964,6 +964,11 @@ export interface OcxProviderConfig {
964
964
  * buffered JSON reconstructed from upstream SSE; ordinary upstream JSON is unchanged.
965
965
  */
966
966
  messagePhaseInference?: boolean;
967
+ /**
968
+ * Opt-in (#7427): on a native Responses route, add estimated `usage` to a completed response the
969
+ * provider sent without one, marked by `x-opencodex-usage-estimated`. Never used for cost, spend or quota.
970
+ */
971
+ estimateMissingUsage?: boolean;
967
972
  /**
968
973
  * Opt-in hosted-web-search bridge for this KEY-auth Responses passthrough provider (#3761).
969
974
  * Absent or disabled leaves the passthrough byte-identical to today.
@@ -1213,6 +1218,14 @@ export interface OcxProviderConfig {
1213
1218
  * the `advisor-tool-2026-03-01` beta too. `false`: never forwarded, even first-party.
1214
1219
  */
1215
1220
  forwardAdvisorTool?: boolean;
1221
+ /**
1222
+ * Experimental, default off (#6895). On an `anthropic`-adapter provider that sends to
1223
+ * `api.anthropic.com` with an API key, a Codex conversation that changes reasoning effort keeps
1224
+ * the top-level `output_config.effort` at its first turn's value and sends each change as an
1225
+ * effort-only system message (beta `mid-conversation-output-config-2026-07-01`), so the prompt
1226
+ * cache survives the change. Any turn the history cannot prove is sent exactly as without it.
1227
+ */
1228
+ perMessageEffort?: boolean;
1216
1229
  /**
1217
1230
  * Model ids that do NOT accept image inputs. The proxy gives them "eyes" via the vision sidecar:
1218
1231
  * attached images are described by a gpt vision model and replaced with text before the call.