@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
@@ -42,6 +42,14 @@ type MainPolicyQuota = { identityKey: string; quota: StoredAccountQuota };
42
42
  /** Fresh WHAM topology proof is consumed by the merge, never retained in a cache or DTO. */
43
43
  type MainPolicyQuotaObservation = Omit<StoredAccountQuota, "updatedAt"> & { shortWindowAbsent?: true; monthlyWindowAbsent?: true };
44
44
  let mainPolicyQuota: MainPolicyQuota | null = null;
45
+ /**
46
+ * When each main policy usage window was last measured in this process (#8113). A window's time
47
+ * moves only when a write measures that window's percentage; reset metadata, credits and other
48
+ * windows never renew it. Process-local and never persisted: a reading restored from disk has none.
49
+ */
50
+ type PolicyUsageWindow = "shortPercent" | "weeklyPercent" | "monthlyPercent";
51
+ const POLICY_USAGE_WINDOWS: readonly PolicyUsageWindow[] = ["shortPercent", "weeklyPercent", "monthlyPercent"];
52
+ let mainPolicyUsageObservation: { identityKey: string; at: Partial<Record<PolicyUsageWindow, number>> } | undefined;
45
53
  let diskHydrated = false;
46
54
  let persistTimer: ReturnType<typeof setTimeout> | null = null;
47
55
  let persistStartedAt: number | null = null;
@@ -442,6 +450,13 @@ export function setAccountQuotaFromParsed(
442
450
  const policyExisting = mainWriter && mainPolicyQuota?.identityKey === mainWriter.identityKey
443
451
  ? mainPolicyQuota.quota
444
452
  : undefined;
453
+ // Only a measured percentage renews its own window; anything else keeps the earlier time.
454
+ if (mainWriter && policyQuota) {
455
+ const at = mainPolicyUsageObservation?.identityKey === mainWriter.identityKey && policyExisting
456
+ ? { ...mainPolicyUsageObservation.at } : {};
457
+ for (const window of POLICY_USAGE_WINDOWS) if (finitePercent(policyQuota[window])) at[window] = updatedAt;
458
+ mainPolicyUsageObservation = { identityKey: mainWriter.identityKey, at };
459
+ }
445
460
  mainPolicyQuota = mainWriter && (policyQuota || policyExisting)
446
461
  ? {
447
462
  identityKey: mainWriter.identityKey,
@@ -450,6 +465,7 @@ export function setAccountQuotaFromParsed(
450
465
  : policyExisting!,
451
466
  }
452
467
  : null;
468
+ if (!mainPolicyQuota) mainPolicyUsageObservation = undefined;
453
469
  }
454
470
  schedulePersistAccountQuotas();
455
471
  // Credits carry the previous usage tuple; they must not refresh its observation clock.
@@ -831,7 +847,7 @@ export function updateAccountQuota(
831
847
  stampCodexQuotaUsageObservation(quota, { weeklyPercent: nextWeekly, monthlyPercent: nextMonthly }, existing);
832
848
  accountQuota.set(accountId, quota);
833
849
  // This legacy writer has no physical credential provenance.
834
- if (accountId === MAIN_CODEX_ACCOUNT_ID) mainPolicyQuota = null;
850
+ if (accountId === MAIN_CODEX_ACCOUNT_ID) { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; }
835
851
  schedulePersistAccountQuotas();
836
852
  // Observed like the other committed write. This function has no in-repo caller today, but it
837
853
  // is re-exported as public API through src/codex/auth-api.ts, so a future caller would
@@ -898,6 +914,7 @@ function hydrateAccountQuotasFromDisk(): void {
898
914
  quotaHistory.hydrate(parsed.history);
899
915
  // Policy evidence deliberately outlives the legacy six-hour rotation-cache TTL.
900
916
  mainPolicyQuota = readMainPolicyQuota(parsed.mainPolicyQuota);
917
+ mainPolicyUsageObservation = undefined;
901
918
  const now = Date.now();
902
919
  for (const [accountId, quota] of Object.entries(parsed.quotas)) {
903
920
  if (!quota || typeof quota !== "object" || typeof quota.updatedAt !== "number") continue;
@@ -955,6 +972,26 @@ export function getMainPolicyQuota(): StoredAccountQuota | null {
955
972
  return structuredClone(mainPolicyQuota.quota);
956
973
  }
957
974
 
975
+ /**
976
+ * The oldest measurement time among the windows the observed main identity's policy reading
977
+ * retains, or undefined when any of them was not measured in this process (for example a reading
978
+ * restored from disk) (#8113). Any stale retained window therefore makes the whole reading stale.
979
+ */
980
+ export function getMainPolicyUsageObservedAt(): number | undefined {
981
+ hydrateAccountQuotasFromDisk();
982
+ if (!mainPolicyQuota || mainPolicyQuota.identityKey !== getObservedMainQuotaIdentityKey()) return undefined;
983
+ const observation = mainPolicyUsageObservation?.identityKey === mainPolicyQuota.identityKey
984
+ ? mainPolicyUsageObservation.at : undefined;
985
+ let oldest: number | undefined;
986
+ for (const window of POLICY_USAGE_WINDOWS) {
987
+ if (!finitePercent(mainPolicyQuota.quota[window])) continue;
988
+ const at = observation?.[window];
989
+ if (at === undefined) return undefined;
990
+ oldest = oldest === undefined ? at : Math.min(oldest, at);
991
+ }
992
+ return oldest;
993
+ }
994
+
958
995
  /** An owned identity observation may retire legacy main quota only when its retained policy tag proves replacement. */
959
996
  export function discardMismatchedMainQuota(): void {
960
997
  hydrateAccountQuotasFromDisk();
@@ -1001,14 +1038,14 @@ export function clearAccountQuota(accountId?: string): void {
1001
1038
  if (accountId) {
1002
1039
  hydrateAccountQuotasFromDisk();
1003
1040
  accountQuota.delete(accountId);
1004
- if (accountId === MAIN_CODEX_ACCOUNT_ID) mainPolicyQuota = null;
1041
+ if (accountId === MAIN_CODEX_ACCOUNT_ID) { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; }
1005
1042
  schedulePersistAccountQuotas();
1006
1043
  forgetCodexQuotaBaseline(accountId);
1007
1044
  return;
1008
1045
  }
1009
1046
  accountQuota.clear();
1010
1047
  forgetCodexQuotaBaseline();
1011
- mainPolicyQuota = null;
1048
+ { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; }
1012
1049
  diskHydrated = false;
1013
1050
  if (persistTimer) {
1014
1051
  clearTimeout(persistTimer);
@@ -1063,7 +1100,8 @@ export function parseMainPolicyUsageQuota(data: WhamUsageResponse): MainPolicyQu
1063
1100
  const windows = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
1064
1101
  if (windows.some(window => isInvalidPolicyUsagePercent(window?.used_percent))) return null;
1065
1102
  const quota = filterMainPolicyMonthlyQuota(parseUsageQuota(data), isThirtyDayOnlyCodexPlan(data.plan_type));
1066
- return quota ? withWhamShortWindowAbsence(data, quota) : null;
1103
+ // #8596: a complete, allowed main read retires a carried monthly tuple under the pool proof (#8067).
1104
+ return quota ? withWhamMonthlyWindowAbsence(data, withWhamShortWindowAbsence(data, quota)) : null;
1067
1105
  }
1068
1106
 
1069
1107
  /** Derive absence from complete WHAM topology without changing the display quota. */
@@ -1097,22 +1135,33 @@ export function poolWhamPolicyObservation(
1097
1135
  data: WhamUsageResponse, quota: Omit<StoredAccountQuota, "updatedAt"> | null,
1098
1136
  ): MainPolicyQuotaObservation | null {
1099
1137
  if (!quota || !isValidWhamHistoryObservation(data)) return null;
1100
- // Retirement releases a block, so a present reading that does not parse is not "unknown".
1138
+ if (data.rate_limit?.allowed === false || hasMalformedWhamReading(data)) return quota;
1139
+ return withWhamMonthlyWindowAbsence(data, withWhamShortWindowAbsence(data, quota));
1140
+ }
1141
+
1142
+ /** Retirement releases a block, so a present reading that does not parse is not "unknown". */
1143
+ function hasMalformedWhamReading(data: WhamUsageResponse): boolean {
1101
1144
  const readings = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
1102
1145
  for (const limit of Array.isArray(data.additional_rate_limits) ? data.additional_rate_limits : []) {
1103
1146
  if (limit && typeof limit === "object") readings.push(limit.rate_limit?.primary_window, limit.rate_limit?.secondary_window);
1104
1147
  }
1105
- const malformed = readings.some(window => window?.used_percent != null
1148
+ return readings.some(window => window?.used_percent != null
1106
1149
  && normalizeUsagePercent(window.used_percent) === undefined);
1107
- if (data.rate_limit?.allowed === false || malformed) return quota;
1108
- const observation = withWhamShortWindowAbsence(data, quota);
1109
- // #8067: the same complete topology proves a pool account has no monthly window when no window
1110
- // declares a monthly duration and no tertiary window is present, so a plan change away from a
1111
- // monthly primary (Free to Pro Lite) retires the carried tuple. Pool-only: main observations
1112
- // keep their existing retention rules.
1150
+ }
1151
+
1152
+ /**
1153
+ * #8067/#8596: the complete topology that proves short-window absence also proves there is no
1154
+ * monthly window when no window declares a monthly duration and no tertiary window is present,
1155
+ * so a plan change away from a monthly primary (Free to Pro Lite) retires the carried tuple.
1156
+ * An explicit denial and invalid or unparseable readings never supply that proof.
1157
+ */
1158
+ function withWhamMonthlyWindowAbsence(
1159
+ data: WhamUsageResponse, observation: MainPolicyQuotaObservation,
1160
+ ): MainPolicyQuotaObservation {
1161
+ if (observation.shortWindowAbsent !== true || data.rate_limit?.allowed === false) return observation;
1162
+ if (!isValidWhamHistoryObservation(data) || hasMalformedWhamReading(data)) return observation;
1113
1163
  const [primary, secondary, tertiary] = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
1114
- return observation.shortWindowAbsent === true
1115
- && !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null
1164
+ return !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null
1116
1165
  ? { ...observation, monthlyWindowAbsent: true }
1117
1166
  : observation;
1118
1167
  }
@@ -2,7 +2,7 @@ import { parseResetCooldownMs } from "../codex/routing";
2
2
  import { CYBER_POLICY_FALLBACK_MESSAGE, TERMINAL_REFUSAL_FALLBACK_MESSAGE, classifyError, isCyberPolicyCode, isCyberPolicyMessage, isRateLimitOrQuotaFailureMessage, isSubscriptionGateMessage, isTerminalRefusalCode, safetyRefusalCodeFromMessage } from "../lib/errors";
3
3
  import { isHardPolicyOrOriginRefusal } from "../lib/hard-refusal";
4
4
  import { isNonReplayableUpstreamCode } from "../lib/upstream-retry";
5
- import { isAnthropicBillingFailure } from "../providers/anthropic-billing-refusal";
5
+ import { isAnthropicBillingFailure, isAnthropicExtraUsageFailure } from "../providers/anthropic-billing-refusal";
6
6
  import { hasConflictingReasoningEffortCode } from "../providers/reasoning-metadata";
7
7
  import { isKiroAccountProfileRefusal } from "../adapters/kiro-refusal";
8
8
  import type { OcxComboTarget } from "../types";
@@ -192,6 +192,16 @@ export function comboTargetCooldownExpiry(
192
192
  return entry.cooldownUntil;
193
193
  }
194
194
 
195
+ /** HTTP status recorded with the target's live cooldown, when the cooling failure had one. */
196
+ export function comboTargetCooldownStatus(
197
+ comboId: string,
198
+ target: Pick<OcxComboTarget, "provider" | "model">,
199
+ now = Date.now(),
200
+ ): number | undefined {
201
+ return isComboTargetInCooldown(comboId, target, now)
202
+ ? targetCooldowns.get(cooldownMapKey(comboId, target))?.status : undefined;
203
+ }
204
+
195
205
  /** Identity of the current live write, independent of its possibly repeated expiry. */
196
206
  export function comboTargetCooldownRevision(
197
207
  comboId: string,
@@ -988,6 +998,171 @@ function isResponseFormatCapabilityRefusal(
988
998
  return false;
989
999
  }
990
1000
 
1001
+ /**
1002
+ * Codes, types and params an unoffered-tool-call refusal may carry. The reported carrier uses
1003
+ * `type: "upstream_error"` with `code: null` -- an aggregator re-wrapping the model backend's
1004
+ * 400 -- while request-validation spellings stay accepted because gateways disagree on which
1005
+ * they emit. Anything outside these closed sets fails closed.
1006
+ */
1007
+ const UNOFFERED_TOOL_CALL_CODES = new Set(["", "invalid_request_error", "invalid_argument", "upstream_error"]);
1008
+ const UNOFFERED_TOOL_CALL_TYPES = new Set(["", "invalid_request_error", "upstream_error", "ai_apicallerror"]);
1009
+ const UNOFFERED_TOOL_CALL_PARAMS = new Set(["tools", "tool_choice"]);
1010
+ /**
1011
+ * The provider's own verdict sentences for target-local model failures, each anchored so a
1012
+ * validation message that merely quotes or reflects one cannot impersonate the verdict -- the
1013
+ * same failure mode moderation-refusal matching guards against. Both observed carriers arrive
1014
+ * as `type: "upstream_error"` with `code: null` behind aggregator re-wraps.
1015
+ */
1016
+ const UNOFFERED_TOOL_CALL_MESSAGES = [
1017
+ /^the model called a function that was not offered in tools\.?$/i,
1018
+ /^the model returned an unexpected parser control marker; no output was published\.?$/i,
1019
+ ] as const;
1020
+ /** Sibling records that could smuggle a competing verdict this classifier does not inspect. */
1021
+ const UNOFFERED_TOOL_CALL_CARRIERS = ["response", "last_error", "details", "detail", "errors"] as const;
1022
+
1023
+ function isUnofferedToolCallVerdict(text: string): boolean {
1024
+ const value = text.trim().replace(/^Provider error \d{3}: /, "").trim();
1025
+ return UNOFFERED_TOOL_CALL_MESSAGES.some(pattern => pattern.test(value));
1026
+ }
1027
+
1028
+ /**
1029
+ * A root message that carries its own envelope prefix is peeled and its contents must still
1030
+ * support the verdict: `Provider error 400: Invalid value for tools` contradicts a nested
1031
+ * refusal even though the prefix itself is recognized.
1032
+ */
1033
+ function isUnofferedToolCallCarrierVerdict(text: string): boolean {
1034
+ let value = text.trim();
1035
+ for (let depth = 0; depth < 3; depth += 1) {
1036
+ const proxyPrefix = /^Provider error \d{3}: /.exec(value);
1037
+ if (proxyPrefix) {
1038
+ value = value.slice(proxyPrefix[0].length).trim();
1039
+ continue;
1040
+ }
1041
+ if (value.startsWith("data:") && !value.includes("\n")) {
1042
+ value = value.slice("data:".length).trim();
1043
+ continue;
1044
+ }
1045
+ break;
1046
+ }
1047
+ return isUnofferedToolCallVerdict(value);
1048
+ }
1049
+
1050
+ function hasUnofferedToolCallCarrierPrefix(text: string): boolean {
1051
+ return /^Provider error \d{3}: /.test(text) || (text.startsWith("data:") && !text.includes("\n"));
1052
+ }
1053
+
1054
+ function unofferedToolCallRecordShape(record: Record<string, unknown>): boolean {
1055
+ if (record.code !== undefined && record.code !== null && typeof record.code !== "string" && typeof record.code !== "number") return false;
1056
+ if (record.type !== undefined && record.type !== null && typeof record.type !== "string") return false;
1057
+ if (record.param !== undefined && record.param !== null) {
1058
+ if (typeof record.param === "string") {
1059
+ if (!UNOFFERED_TOOL_CALL_PARAMS.has(record.param.trim().toLowerCase())) return false;
1060
+ } else if (typeof record.param === "object" && !Array.isArray(record.param)) {
1061
+ // An AI-SDK gateway wraps the verdict in an error object under `param`; accept it only
1062
+ // when a nested string field independently carries the same anchored verdict, so the
1063
+ // object cannot smuggle a different claim.
1064
+ const nested = record.param as Record<string, unknown>;
1065
+ const diagnostics = [nested.error, nested.message].filter((v) => v !== undefined && v !== null);
1066
+ if (diagnostics.length === 0) return false;
1067
+ for (const diagnostic of diagnostics) {
1068
+ if (typeof diagnostic !== "string" || !isUnofferedToolCallVerdict(diagnostic)) return false;
1069
+ }
1070
+ // The nested record is held to the same closed code/type sets and carrier ban as the
1071
+ // envelope, so a policy code tucked inside `param` cannot ride the verdict into a hop.
1072
+ if (nested.param !== undefined && nested.param !== null) return false;
1073
+ if (nested.code !== undefined && nested.code !== null
1074
+ && (typeof nested.code !== "string" && typeof nested.code !== "number"
1075
+ || !UNOFFERED_TOOL_CALL_CODES.has(normalizedFailureCode(nested.code)))) return false;
1076
+ if (nested.type !== undefined && nested.type !== null
1077
+ && (typeof nested.type !== "string" || !UNOFFERED_TOOL_CALL_TYPES.has(normalizedFailureCode(nested.type)))) return false;
1078
+ if (UNOFFERED_TOOL_CALL_CARRIERS.some(carrier => nested[carrier] !== undefined && nested[carrier] !== null)) return false;
1079
+ } else {
1080
+ return false;
1081
+ }
1082
+ }
1083
+ if (!UNOFFERED_TOOL_CALL_CODES.has(normalizedFailureCode(record.code as string | number | undefined))) return false;
1084
+ if (!UNOFFERED_TOOL_CALL_TYPES.has(normalizedFailureCode(record.type as string | undefined))) return false;
1085
+ for (const carrier of UNOFFERED_TOOL_CALL_CARRIERS) {
1086
+ if (record[carrier] !== undefined && record[carrier] !== null) return false;
1087
+ }
1088
+ return true;
1089
+ }
1090
+
1091
+ /**
1092
+ * A target-local model verdict -- an unoffered tool call, or output the transport could not
1093
+ * publish -- is evidence a later combo target may not repeat: the provider answered, the
1094
+ * request fit, and the failure arrives before any output commits, so advancing is replay-safe.
1095
+ *
1096
+ * The envelope is bounded like its siblings: a depth budget, one `Provider error NNN:` or
1097
+ * single-line `data:` unwrap per level, closed code/type/param sets, and fail-closed treatment
1098
+ * of any record carrying a competing diagnostic carrier or a contradicting root message.
1099
+ * Bare verdict text is also a carrier: a chat gateway can surface the sentence with no JSON
1100
+ * envelope at all.
1101
+ */
1102
+ export function isUnofferedToolCallRefusal(
1103
+ status: number,
1104
+ message: string,
1105
+ code?: string | number | null,
1106
+ ): boolean {
1107
+ if (status !== 400 || message.length > 16_384) return false;
1108
+ if (code !== undefined && code !== null && typeof code !== "string" && typeof code !== "number") return false;
1109
+ if (!UNOFFERED_TOOL_CALL_CODES.has(normalizedFailureCode(code))) return false;
1110
+ let text = message.trim();
1111
+ for (let depth = 0; depth < 4; depth += 1) {
1112
+ const proxyPrefix = /^Provider error \d{3}: /.exec(text);
1113
+ if (proxyPrefix) text = text.slice(proxyPrefix[0].length).trim();
1114
+ if (text.startsWith("data:") && !text.includes("\n")) text = text.slice("data:".length).trim();
1115
+ let payload: unknown;
1116
+ try {
1117
+ payload = JSON.parse(text);
1118
+ } catch {
1119
+ return isUnofferedToolCallVerdict(text);
1120
+ }
1121
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false;
1122
+ const root = payload as Record<string, unknown>;
1123
+ if (!unofferedToolCallRecordShape(root)) return false;
1124
+ const error = root.error;
1125
+ // A nested verdict must agree with the root's own message. When the root carries no error
1126
+ // record its message IS the payload carrier and is validated by the flat path below.
1127
+ if (error !== undefined && error !== null
1128
+ && typeof root.message === "string" && root.message.trim() !== ""
1129
+ && !isUnofferedToolCallCarrierVerdict(root.message)) return false;
1130
+ if (error === undefined || error === null) {
1131
+ if (typeof root.message !== "string") return false;
1132
+ if (hasUnofferedToolCallCarrierPrefix(root.message.trim())) {
1133
+ text = root.message.trim();
1134
+ continue;
1135
+ }
1136
+ return isUnofferedToolCallVerdict(root.message);
1137
+ }
1138
+ if (typeof error === "string") {
1139
+ if (hasUnofferedToolCallCarrierPrefix(error.trim())) {
1140
+ text = error.trim();
1141
+ continue;
1142
+ }
1143
+ return isUnofferedToolCallVerdict(error);
1144
+ }
1145
+ if (typeof error !== "object" || Array.isArray(error)) return false;
1146
+ const record = error as Record<string, unknown>;
1147
+ if (!unofferedToolCallRecordShape(record)) return false;
1148
+ if (record.error !== undefined && record.error !== null) {
1149
+ if (typeof record.error !== "string") return false;
1150
+ if (record.error.trim() !== "" && !isUnofferedToolCallVerdict(record.error)) return false;
1151
+ }
1152
+ if (root.param !== undefined && root.param !== null && record.param !== undefined && record.param !== null
1153
+ && String(root.param).trim().toLowerCase() !== String(record.param).trim().toLowerCase()) return false;
1154
+ if (typeof record.message !== "string") return false;
1155
+ const inner = record.message.trim();
1156
+ if (hasUnofferedToolCallCarrierPrefix(inner)) {
1157
+ // Our own wrapper, re-wrapped by a downstream hop. Peel it and look again, within budget.
1158
+ text = inner;
1159
+ continue;
1160
+ }
1161
+ return isUnofferedToolCallVerdict(record.message);
1162
+ }
1163
+ return false;
1164
+ }
1165
+
991
1166
  /** The classification text the combo path bounds a body to (src/server/responses/core-errors.ts). */
992
1167
  const MODERATION_EVIDENCE_LIMIT = 500;
993
1168
 
@@ -1314,6 +1489,7 @@ export function comboFailureCooldownScope(
1314
1489
  code?: string | number | null;
1315
1490
  malformedResponseFormat?: boolean;
1316
1491
  openRouterOpaque400?: boolean;
1492
+ unofferedToolCallRefusal?: boolean;
1317
1493
  /** Whole-body moderation verdict from a reader that saw the complete bounded body. */
1318
1494
  providerModerationRefusal?: boolean;
1319
1495
  },
@@ -1335,6 +1511,13 @@ export function comboFailureCooldownScope(
1335
1511
  // A capability gap says the target is healthy and the request did not fit it, which is the
1336
1512
  // same reason every other entry here refuses to cool a target.
1337
1513
  || isResponseFormatCapabilityRefusal(status, message, rawCode)
1514
+ // The provider answered and its model simply called a function it was never offered: the
1515
+ // request fit and the target is healthy, so this must not cool it either. A caller that
1516
+ // classified the intact bounded body supplies the verdict directly; the display-truncated
1517
+ // text here would fail the envelope parse on a long body.
1518
+ || (options?.unofferedToolCallRefusal !== undefined
1519
+ ? options.unofferedToolCallRefusal
1520
+ : isUnofferedToolCallRefusal(status, message, rawCode))
1338
1521
  ) return "none";
1339
1522
  if (isProviderScopedQuotaCap(status, message, rawCode)) return "provider";
1340
1523
  // A rejected or unpaid credential is provider-wide evidence: every target that routes
@@ -1481,6 +1664,7 @@ export function comboFailureDecision(
1481
1664
  verifiedPlanRefusal?: boolean;
1482
1665
  malformedResponseFormat?: boolean;
1483
1666
  openRouterOpaque400?: boolean;
1667
+ unofferedToolCallRefusal?: boolean;
1484
1668
  /** Whole-body moderation verdict from a reader that saw the complete bounded body. */
1485
1669
  providerModerationRefusal?: boolean;
1486
1670
  },
@@ -1509,6 +1693,7 @@ function decideComboFailure(
1509
1693
  verifiedPlanRefusal?: boolean;
1510
1694
  malformedResponseFormat?: boolean;
1511
1695
  openRouterOpaque400?: boolean;
1696
+ unofferedToolCallRefusal?: boolean;
1512
1697
  /** Whole-body moderation verdict from a reader that saw the complete bounded body. */
1513
1698
  providerModerationRefusal?: boolean;
1514
1699
  },
@@ -1600,7 +1785,16 @@ function decideComboFailure(
1600
1785
  // could have served the request (#4903).
1601
1786
  if (isResponseFormatCapabilityRefusal(status, message, rawCode)) return "hop";
1602
1787
  if (providerModerationHop(status, message, rawCode, options?.providerModerationRefusal, options?.malformedResponseFormat)) return "hop";
1788
+ // A model that calls a function the request never offered hallucinated the call: target-local
1789
+ // behavior on a healthy target, arriving as a pre-output 400. Must precede the generic
1790
+ // invalid_request_error stop, which is where this envelope ended the chain. A caller that
1791
+ // classified the intact bounded body supplies the verdict directly; the display-truncated
1792
+ // text here would fail the envelope parse on a long body.
1793
+ if (options?.unofferedToolCallRefusal !== undefined
1794
+ ? options.unofferedToolCallRefusal
1795
+ : isUnofferedToolCallRefusal(status, message, rawCode)) return "hop";
1603
1796
  if (isAnthropicBillingFailure(status, message, rawCode)) return "hop";
1797
+ if (isAnthropicExtraUsageFailure(status, message, rawCode)) return "hop";
1604
1798
  // Kiro's body validator rejects the request for the identity it was routed under. The account
1605
1799
  // layer rotates logins first; this is the no-alternate case, so the next combo target is the
1606
1800
  // only remaining chance to serve the turn. Only a caller that knows the failed target is a Kiro
@@ -22,8 +22,11 @@ export {
22
22
  export {
23
23
  advanceComboAfterFailure,
24
24
  clearComboSelectionState,
25
+ comboExclusion,
25
26
  comboExclusionReasons,
27
+ comboTargetUnavailableCause,
26
28
  comboTargetSkipTrigger,
29
+ comboUnavailableDiagnostics,
27
30
  NoAvailableComboTargetsError,
28
31
  noteComboFailure,
29
32
  noteComboSuccess,
@@ -34,7 +37,9 @@ export {
34
37
  snapshotComboQuotaCooldowns,
35
38
  tryPickComboModel,
36
39
  UnknownComboError,
40
+ type ComboExclusion,
37
41
  type ComboPick,
42
+ type ComboUnavailableDiagnostics,
38
43
  type QuotaInactiveReason,
39
44
  } from "./resolve";
40
45
  export {
@@ -6,6 +6,7 @@ import { sleepWithAbort } from "../lib/upstream-retry";
6
6
  import {
7
7
  clearComboTargetCooldownIfUnchanged,
8
8
  comboTargetCooldownRevision,
9
+ comboTargetCooldownStatus,
9
10
  coolComboTarget,
10
11
  earliestComboCooldown,
11
12
  isComboTargetInCooldown,
@@ -71,11 +72,49 @@ export function comboTargetLogLabel(config: OcxConfig, comboId: string, target:
71
72
 
72
73
  export type ComboExclusionReasons = string & { readonly [exclusionBrand]: true };
73
74
 
75
+ /** One target's coarse failure class in a `combo_unavailable` answer (#7965). */
76
+ export type ComboTargetUnavailableCause = "quota" | "permission" | "transient" | "unsupported" | "unavailable";
77
+ /** The combo-level class: the one class every classified target shares, `mixed` when they differ, `unknown` when none was classified. */
78
+ export type ComboUnavailableCause = ComboTargetUnavailableCause | "mixed" | "unknown";
79
+
80
+ /**
81
+ * Machine-readable fields on the public `combo_unavailable` error (#7965). Counts and closed classes
82
+ * only: no combo id, provider name, model, account or upstream text.
83
+ */
84
+ export interface ComboUnavailableDiagnostics {
85
+ readonly cause: ComboUnavailableCause;
86
+ /** Targets configured on the combo. */
87
+ readonly targets: number;
88
+ /** Targets this request dispatched before the answer. */
89
+ readonly attempted: number;
90
+ /** How many targets fell in each class; classes no target fell in are omitted. */
91
+ readonly causes: Readonly<Partial<Record<ComboTargetUnavailableCause, number>>>;
92
+ }
93
+
94
+ /** Fold per-target classes into the combo-level diagnostics. */
95
+ export function comboUnavailableDiagnostics(
96
+ targets: number,
97
+ attempted: number,
98
+ classes: readonly ComboTargetUnavailableCause[],
99
+ ): ComboUnavailableDiagnostics {
100
+ const causes: Partial<Record<ComboTargetUnavailableCause, number>> = {};
101
+ for (const value of classes) causes[value] = (causes[value] ?? 0) + 1;
102
+ const distinct = Object.keys(causes) as ComboTargetUnavailableCause[];
103
+ const cause: ComboUnavailableCause = distinct.length === 0 ? "unknown" : distinct.length === 1 ? distinct[0]! : "mixed";
104
+ return { cause, targets, attempted, causes };
105
+ }
106
+
107
+ /** Why a combo had no target to pick: the readable message suffix and its machine-readable form. */
108
+ export interface ComboExclusion {
109
+ readonly reasons: ComboExclusionReasons;
110
+ readonly diagnostics: ComboUnavailableDiagnostics;
111
+ }
112
+
74
113
  export class NoAvailableComboTargetsError extends Error {
75
114
  readonly code = "combo_unavailable";
76
115
 
77
- constructor(readonly comboId: string, readonly reasons?: ComboExclusionReasons) {
78
- super(`No available targets for combo${reasons ? ` (${reasons})` : ""}`);
116
+ constructor(readonly comboId: string, readonly exclusion?: ComboExclusion) {
117
+ super(`No available targets for combo${exclusion ? ` (${exclusion.reasons})` : ""}`);
79
118
  this.name = "NoAvailableComboTargetsError";
80
119
  }
81
120
  }
@@ -107,32 +146,89 @@ export function comboTargetSkipTrigger(
107
146
  return providerExclusionReason(config, target, now) === "quota exhausted" ? "quota_exhausted" : "unavailable";
108
147
  }
109
148
 
149
+ /**
150
+ * The class a skipped target contributes to `combo_unavailable` diagnostics. A cooldown is
151
+ * classified by the HTTP status its entry kept: 429/402 is quota, 401/403 is permission, and any
152
+ * other or missing status is transient.
153
+ */
154
+ function exclusionCause(reason: ComboExclusionReason, comboId: string, target: OcxComboTarget, now: number): ComboTargetUnavailableCause {
155
+ if (reason === "quota exhausted") return "quota";
156
+ if (reason === "ineligible for this request") return "unsupported";
157
+ if (reason !== "cooldown") return "unavailable";
158
+ const status = comboTargetCooldownStatus(comboId, target, now);
159
+ return status === 429 || status === 402 ? "quota" : status === 401 || status === 403 ? "permission" : "transient";
160
+ }
161
+
110
162
  /**
111
163
  * Why each target of a combo cannot be picked right now, for a zero-attempt refusal. Only the
112
- * target index, validated provider label and a closed exclusion reason are named.
164
+ * target index, validated provider label and a closed exclusion reason are named; the same pass
165
+ * yields the machine-readable diagnostics.
113
166
  */
114
- export function comboExclusionReasons(
167
+ /** Why the picker would pass over one target, in picker order: provider, cooldown, then request eligibility. */
168
+ function targetExclusionReason(
169
+ config: OcxConfig,
170
+ comboId: string,
171
+ target: NormalizedComboTarget,
172
+ eligible: ((target: NormalizedComboTarget) => boolean) | undefined,
173
+ now: number,
174
+ ): ComboExclusionReason | undefined {
175
+ let reason = providerExclusionReason(config, target, now);
176
+ const cooldown = reason ? undefined : earliestComboCooldown(comboId, [target], now);
177
+ if (cooldown) reason = "cooldown";
178
+ if (!reason && eligible) {
179
+ try {
180
+ if (!eligible(target)) reason = "ineligible for this request";
181
+ } catch {
182
+ // An eligibility check can exhaust the translator budget; the target still was not picked.
183
+ reason = "ineligible for this request";
184
+ }
185
+ }
186
+ return reason;
187
+ }
188
+
189
+ /**
190
+ * One target's `combo_unavailable` class, from the same checks and precedence as
191
+ * {@link comboExclusion}, or `undefined` when nothing excludes it.
192
+ */
193
+ export function comboTargetUnavailableCause(
115
194
  config: OcxConfig,
116
195
  comboId: string,
196
+ target: NormalizedComboTarget,
117
197
  eligible?: (target: NormalizedComboTarget) => boolean,
118
198
  now = Date.now(),
119
- ): ComboExclusionReasons {
199
+ ): ComboTargetUnavailableCause | undefined {
200
+ const reason = targetExclusionReason(config, comboId, target, eligible, now);
201
+ return reason ? exclusionCause(reason, comboId, target, now) : undefined;
202
+ }
203
+
204
+ export function comboExclusion(
205
+ config: OcxConfig,
206
+ comboId: string,
207
+ eligible?: (target: NormalizedComboTarget) => boolean,
208
+ now = Date.now(),
209
+ ): ComboExclusion {
120
210
  const targets = getCombo(config, comboId)?.targets ?? [];
211
+ const classes: ComboTargetUnavailableCause[] = [];
121
212
  const reasons = targets.flatMap((target, index) => {
122
- let reason = providerExclusionReason(config, target, now);
123
- const cooldown = reason ? undefined : earliestComboCooldown(comboId, [target], now);
124
- if (cooldown) reason = "cooldown";
125
- if (!reason && eligible) {
126
- try {
127
- if (!eligible(target)) reason = "ineligible for this request";
128
- } catch {
129
- // An eligibility check can exhaust the translator budget; the target still was not picked.
130
- reason = "ineligible for this request";
131
- }
132
- }
133
- return reason ? [`target ${index + 1} (${errorDestinationText(providerErrorDestinationLabel(target.provider))}): ${reason}`] : [];
213
+ const reason = targetExclusionReason(config, comboId, target, eligible, now);
214
+ if (!reason) return [];
215
+ classes.push(exclusionCause(reason, comboId, target, now));
216
+ return [`target ${index + 1} (${errorDestinationText(providerErrorDestinationLabel(target.provider))}): ${reason}`];
134
217
  }).join("; ");
135
- return `${targets.length} target${targets.length === 1 ? "" : "s"}${reasons ? `; ${reasons}` : ""}` as ComboExclusionReasons;
218
+ return {
219
+ reasons: `${targets.length} target${targets.length === 1 ? "" : "s"}${reasons ? `; ${reasons}` : ""}` as ComboExclusionReasons,
220
+ diagnostics: comboUnavailableDiagnostics(targets.length, 0, classes),
221
+ };
222
+ }
223
+
224
+ /** The readable half of {@link comboExclusion}. */
225
+ export function comboExclusionReasons(
226
+ config: OcxConfig,
227
+ comboId: string,
228
+ eligible?: (target: NormalizedComboTarget) => boolean,
229
+ now = Date.now(),
230
+ ): ComboExclusionReasons {
231
+ return comboExclusion(config, comboId, eligible, now).reasons;
136
232
  }
137
233
 
138
234
  /** Capture usable providers' quota cooldowns; request eligibility is deferred to exhaustion. */
@@ -760,6 +856,6 @@ export function tryPickComboModel(config: OcxConfig, modelId: string, preview =
760
856
  if (!comboId) return null;
761
857
  if (!getCombo(config, comboId)) throw new UnknownComboError(comboId);
762
858
  const picked = pickComboTarget(config, comboId, { preview, allowCooldownReprobe: false });
763
- if (!picked) throw new NoAvailableComboTargetsError(comboId, comboExclusionReasons(config, comboId));
859
+ if (!picked) throw new NoAvailableComboTargetsError(comboId, comboExclusion(config, comboId));
764
860
  return picked;
765
861
  }
@@ -11,6 +11,7 @@ import * as z from "zod/v4";
11
11
  import { compactionRecoveryConfigError } from "./schema/compaction-recovery";
12
12
  import { nativeReasoningRetentionConfigError } from "./schema/native-reasoning-retention";
13
13
  import { WORKFLOW_BUDGET_SHAPE_HINT, workflowBudgetConfigError } from "./schema/workflow-budget";
14
+ import { ROUTED_CATALOG_DEFAULTS_SHAPE_HINT, routedCatalogDefaultsConfigError } from "./schema/routed-catalog-defaults";
14
15
  import { desktopCompatibilityConfigError } from "./schema/desktop-compatibility";
15
16
  import { blockedModelRedirectsError } from "./schema/blocked-model-redirects";
16
17
  import { mainAccountHardLockFallbackError } from "./schema/main-account-hard-lock-fallback";
@@ -151,6 +152,7 @@ function validFileConfigDiagnostics(config: OcxConfig, rawParsed: unknown): Conf
151
152
  if (blockedModelRedirectsError(rawParsed)) warnings.push("blockedModelRedirects ignored: expected a map of nonempty model keys to nonempty string targets");
152
153
  if (nativeReasoningRetentionConfigError(rawParsed)) warnings.push("nativeReasoningRetention ignored: expected only optional boolean modelSwitch and accountSwitch fields; both remain off");
153
154
  if (workflowBudgetConfigError(rawParsed)) warnings.push("workflowBudget ignored: " + WORKFLOW_BUDGET_SHAPE_HINT + "; the built-in ceilings remain");
155
+ if (routedCatalogDefaultsConfigError(rawParsed)) warnings.push("routedCatalogDefaults ignored: " + ROUTED_CATALOG_DEFAULTS_SHAPE_HINT + "; routed catalog rows keep their derived values");
154
156
  if (mainAccountHardLockFallbackError(rawParsed)) warnings.push("codexMainAccountHardLockFallback ignored: expected a nonblank model selector and an optional declared reasoningEffort");
155
157
  if (fallbackPolicyError(rawParsed)) warnings.push("fallback partly ignored: expected boolean model/provider switches, providers/routes/devices maps of them, and devices.<id>.localFallback; ignored leaves keep today's fallback behavior");
156
158
  const quotaAutoRefreshWarning = degradedCodexQuotaAutoRefreshWarning(rawParsed, normalized);
@@ -778,6 +780,7 @@ export function validateConfigCandidate(value: unknown): { ok: true; config: Ocx
778
780
  ?? fallbackPolicyError(value)
779
781
  ?? nativeReasoningRetentionConfigError(value)
780
782
  ?? workflowBudgetConfigError(value)
783
+ ?? routedCatalogDefaultsConfigError(value)
781
784
  ?? mainAccountHardLockFallbackError(value)
782
785
  ?? compactionRecoveryConfigError(value) ?? desktopCompatibilityConfigError(value) ?? configReasoningPinsConfigError(value)
783
786
  ?? blankHostnameError(value)
@@ -2,7 +2,8 @@ import { observeAccountAutoPauseRevisions, snapshotAutoPauseFingerprints } from
2
2
  import type { OcxConfig, OcxProviderConfig, ProviderCostOverlay } from "../types";
3
3
  import { configReasoningPinsConfigError } from "./provider-validation";
4
4
  import { carryPersistedTelemetry } from "./telemetry-carry";
5
- import { adoptCustomModelCatalogMigration, projectCustomModelCatalogMigration } from "../codex/custom-model-catalog-migration";
5
+ import { adoptPersistedConfigMigrations, projectPersistedConfigMigrations } from "./persisted-projections";
6
+ import { RESERVE_CAPABILITY_KEYS } from "./reserve-capability";
6
7
  import { refreshPreservedProviderOwner } from "../usage/user-cost-overlays";
7
8
  import { refreshConfigDerivedRegistries } from "./derived-registries";
8
9
  import {
@@ -598,6 +599,8 @@ export function saveConfigPreservingClaudeCode(config: OcxConfig): void {
598
599
  ...(provenanceExists
599
600
  ? Object.keys(persistedDiagnostics.config as unknown as Record<string, unknown>)
600
601
  : []),
602
+ // An absent Reserve value reads as off, so a disk-only value is never left behind.
603
+ ...RESERVE_CAPABILITY_KEYS,
601
604
  ]);
602
605
  for (const key of Object.keys(persistedDiagnostics.config as unknown as Record<string, unknown>)) {
603
606
  if (!rebaseableKeys.has(key)) skipped.add(key);
@@ -640,7 +643,7 @@ export function saveConfigPreservingClaudeCode(config: OcxConfig): void {
640
643
  if (diskDeletedKeys.size) durableProjection.configRebaseProvenance = { version: 1,
641
644
  deletedTopLevelKeys: [...new Set([...configRebaseDeletionKeys(durableProjection), ...diskDeletedKeys])].sort() };
642
645
  const provenanceProjection = projectConfigRebaseProvenance(durableProjection);
643
- const projectedConfig = projectCustomModelCatalogMigration(
646
+ const projectedConfig = projectPersistedConfigMigrations(
644
647
  onDisk,
645
648
  durableProjection,
646
649
  );
@@ -661,7 +664,7 @@ export function saveConfigPreservingClaudeCode(config: OcxConfig): void {
661
664
  } else {
662
665
  persist(projectedConfig);
663
666
  }
664
- adoptCustomModelCatalogMigration(config, projectedConfig);
667
+ adoptPersistedConfigMigrations(config, projectedConfig);
665
668
  captureLiveTopologyBaseline(config);
666
669
  if (claudeCodeBaseline.has(config)) {
667
670
  claudeCodeBaseline.set(config, structuredClone(config.claudeCode));