@bitkyc08/opencodex 2.92.0 → 2.93.0-preview.20261027

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 (259) hide show
  1. package/bin/ocx.mjs +10 -5
  2. package/gui/dist/assets/App-CJZoq-uF.js +58 -0
  3. package/gui/dist/assets/{Tray-BSsxznDm.js → Tray-BWQPcgZn.js} +1 -1
  4. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  5. package/gui/dist/assets/{index-BlFE_VB_.js → index-Xfct8owH.js} +12 -12
  6. package/gui/dist/assets/{quota-summary-BRlbXgw0.js → quota-summary-DxToX1rV.js} +1 -1
  7. package/gui/dist/index.html +2 -2
  8. package/package.json +5 -5
  9. package/src/adapters/anthropic.ts +28 -5
  10. package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
  11. package/src/adapters/coding-agent/profile.ts +54 -16
  12. package/src/adapters/coding-agent/turn.ts +30 -2
  13. package/src/adapters/command-code.ts +114 -7
  14. package/src/adapters/cursor/native-exec-fs.ts +11 -9
  15. package/src/adapters/devin/live-models.ts +4 -0
  16. package/src/adapters/google-wire-compiler.ts +1 -2
  17. package/src/adapters/kiro/reasoning.ts +2 -0
  18. package/src/adapters/kiro-refusal.ts +6 -1
  19. package/src/adapters/kiro-wire.ts +1 -1
  20. package/src/adapters/openai-chat/messages.ts +8 -2
  21. package/src/adapters/openai-chat/passthrough.ts +35 -14
  22. package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
  23. package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
  24. package/src/adapters/openai-chat/required-tool-result.ts +64 -0
  25. package/src/adapters/openai-chat.ts +7 -8
  26. package/src/adapters/openai-responses/passthrough.ts +7 -4
  27. package/src/adapters/openai-responses/reasoning.ts +13 -0
  28. package/src/adapters/openai-responses/request-strips.ts +1 -1
  29. package/src/adapters/qoder/adapter.ts +129 -8
  30. package/src/adapters/qoder/scaffold-guard.ts +5 -0
  31. package/src/adapters/reasoning-controls.ts +16 -0
  32. package/src/adapters/tool-call-id.ts +1 -3
  33. package/src/bridge/errors.ts +27 -0
  34. package/src/bridge.ts +1 -1
  35. package/src/chat/inbound.ts +4 -1
  36. package/src/chat/outbound.ts +9 -2
  37. package/src/chat/reasoning-details.ts +28 -5
  38. package/src/claude/desktop-first-party.ts +54 -4
  39. package/src/claude/desktop-picker.ts +11 -8
  40. package/src/claude/first-party-settings.ts +3 -1
  41. package/src/claude/inbound.ts +2 -1
  42. package/src/claude/intercept/local-ca.ts +2 -1
  43. package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
  44. package/src/claude/intercept/picker-ca-startup.ts +3 -1
  45. package/src/claude/intercept/picker-models.ts +6 -3
  46. package/src/claude/intercept/picker-runtime.ts +3 -2
  47. package/src/claude/intercept/runtime.ts +6 -3
  48. package/src/claude/model-info.ts +31 -8
  49. package/src/cli/account-api.ts +11 -0
  50. package/src/cli/capabilities-agents-routing.ts +2 -2
  51. package/src/cli/capabilities-base.ts +7 -1
  52. package/src/cli/capabilities-observe-system.ts +10 -0
  53. package/src/cli/claude-desktop.ts +9 -8
  54. package/src/cli/claude.ts +3 -2
  55. package/src/cli/codex-shim-autorestore.ts +9 -0
  56. package/src/cli/combo-result.ts +7 -0
  57. package/src/cli/combo.ts +18 -0
  58. package/src/cli/cross-home-owner.ts +13 -1
  59. package/src/cli/dispatch.ts +25 -6
  60. package/src/cli/ensure-desired-integrations.ts +8 -6
  61. package/src/cli/export-command.ts +4 -1
  62. package/src/cli/help.ts +2 -1
  63. package/src/cli/index.ts +45 -45
  64. package/src/cli/integration-plan-dto.ts +4 -0
  65. package/src/cli/opencode.ts +20 -9
  66. package/src/cli/registry.ts +6 -4
  67. package/src/cli/root.ts +9 -0
  68. package/src/cli/status.ts +59 -1
  69. package/src/cli/stop-restore.ts +113 -0
  70. package/src/cli/sync-expectation.ts +60 -0
  71. package/src/cli/uninstall-integrations.ts +41 -7
  72. package/src/client/connect.ts +40 -3
  73. package/src/client/link-home.ts +10 -1
  74. package/src/client/machine-api.ts +3 -1
  75. package/src/client/sync-expectation.ts +118 -0
  76. package/src/clients/config-export/agent-clients.ts +96 -0
  77. package/src/clients/config-export/contracts.ts +25 -7
  78. package/src/clients/config-export/qoder.ts +38 -23
  79. package/src/clients/config-export/reasoning-metadata.ts +55 -8
  80. package/src/clients/config-export.ts +12 -0
  81. package/src/clients/lazycodex.ts +7 -2
  82. package/src/clients/reasoning-controls.ts +49 -0
  83. package/src/codex/auth-api/account-identity.ts +14 -0
  84. package/src/codex/auth-api/account-list.ts +29 -2
  85. package/src/codex/auth-api/http.ts +13 -0
  86. package/src/codex/auth-api/main-account-probe.ts +2 -2
  87. package/src/codex/auth-api/pool-mode-gate.ts +16 -3
  88. package/src/codex/auth-api/pool-quota-probe.ts +15 -0
  89. package/src/codex/auth-context.ts +15 -12
  90. package/src/codex/catalog/build-entries.ts +22 -0
  91. package/src/codex/catalog/configured-tiers.ts +70 -0
  92. package/src/codex/catalog/effort.ts +44 -10
  93. package/src/codex/catalog/gather-capture.ts +1 -0
  94. package/src/codex/catalog/heal-observation.ts +155 -13
  95. package/src/codex/catalog/metadata.ts +6 -0
  96. package/src/codex/catalog/model-hints.ts +60 -11
  97. package/src/codex/catalog/model-visibility.ts +3 -2
  98. package/src/codex/catalog/native-models.ts +18 -3
  99. package/src/codex/catalog/parsing.ts +10 -8
  100. package/src/codex/catalog/pinned-models.ts +2 -1
  101. package/src/codex/catalog/provider-models.ts +4 -5
  102. package/src/codex/catalog/retained-sync.ts +2 -1
  103. package/src/codex/catalog/routed-gather.ts +19 -20
  104. package/src/codex/catalog/write-audit.ts +3 -2
  105. package/src/codex/catalog-self-heal.ts +43 -23
  106. package/src/codex/collision-identity.ts +30 -5
  107. package/src/codex/convergence.ts +4 -3
  108. package/src/codex/data/roster-pinned-models.json +177 -1
  109. package/src/codex/desired-state.ts +6 -1
  110. package/src/codex/desktop-compatibility/installed-build.ts +88 -12
  111. package/src/codex/desktop-compatibility/runtime.ts +29 -5
  112. package/src/codex/desktop-compatibility/usage-controller.ts +2 -0
  113. package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
  114. package/src/codex/inject/config-toml.ts +0 -18
  115. package/src/codex/inject/plan.ts +18 -3
  116. package/src/codex/inject/remove.ts +6 -2
  117. package/src/codex/inject.ts +1 -1
  118. package/src/codex/journal.ts +61 -1
  119. package/src/codex/model-entitlements.ts +1 -1
  120. package/src/codex/native-main-owner.ts +27 -1
  121. package/src/codex/native-profile-store.ts +2 -1
  122. package/src/codex/pool-credit-policy.ts +35 -1
  123. package/src/codex/quota-types.ts +3 -0
  124. package/src/codex/quota.ts +24 -4
  125. package/src/codex/role-auto-assign.ts +6 -2
  126. package/src/codex/subagent-defaults.ts +49 -4
  127. package/src/combos/failover.ts +17 -2
  128. package/src/combos/jev-decision-contract.ts +22 -1
  129. package/src/combos/jev-service-exchange.ts +3 -1
  130. package/src/combos/jev.ts +95 -9
  131. package/src/combos/resolve.ts +45 -1
  132. package/src/combos/types.ts +24 -0
  133. package/src/config/load-degrade.ts +5 -0
  134. package/src/config/paths.ts +19 -3
  135. package/src/config/pending-teardown.ts +22 -1
  136. package/src/config/provider-validation.ts +15 -4
  137. package/src/config/removed-opencode-free.ts +11 -0
  138. package/src/config/schema/leaf-validators.ts +5 -0
  139. package/src/generated/compatibility-version.json +314 -230
  140. package/src/generated/model-metadata.ts +5 -5
  141. package/src/images/loop.ts +16 -2
  142. package/src/integrations/catalog-refresh.ts +1 -1
  143. package/src/integrations/hermes-profiles.ts +251 -0
  144. package/src/integrations/merge.ts +8 -0
  145. package/src/integrations/mutation-plan.ts +19 -4
  146. package/src/integrations/registry.ts +5 -0
  147. package/src/integrations/state.ts +36 -1
  148. package/src/integrations/writer.ts +18 -4
  149. package/src/lib/bun-path-runtime.mjs +2 -1
  150. package/src/lib/errors.ts +62 -0
  151. package/src/lib/eventstream-decoder.ts +81 -37
  152. package/src/lib/opaque-proxy-tunnel.ts +32 -8
  153. package/src/lib/pinned-http.ts +35 -2
  154. package/src/lib/process-control.ts +13 -1
  155. package/src/lib/socks5-fetch.ts +59 -64
  156. package/src/lib/socks5-upload-waiter.ts +50 -0
  157. package/src/lib/sse-decoder.ts +7 -2
  158. package/src/lib/state-store-sweeper.ts +40 -14
  159. package/src/lib/windows-native-principal-worker.ts +14 -0
  160. package/src/lib/windows-native-principal.ts +188 -0
  161. package/src/lib/windows-secret-acl.ts +39 -3
  162. package/src/lib/windows-user-principal.ts +62 -18
  163. package/src/link/ssh-config.ts +35 -3
  164. package/src/providers/account-quota-disk.ts +12 -4
  165. package/src/providers/codebuddy-models.ts +6 -0
  166. package/src/providers/codex-capacity.ts +3 -1
  167. package/src/providers/derive.ts +28 -0
  168. package/src/providers/kiro-models.ts +3 -0
  169. package/src/providers/mimo-thinking.ts +12 -0
  170. package/src/providers/model-rename-fields.ts +1 -0
  171. package/src/providers/model-rename-migration.ts +10 -0
  172. package/src/providers/openai-sidecar-credit.ts +2 -2
  173. package/src/providers/reasoning-capabilities.ts +76 -0
  174. package/src/providers/registry/entries-core.ts +14 -12
  175. package/src/providers/registry/entries-extended.ts +63 -20
  176. package/src/providers/registry/model-ids.ts +2 -0
  177. package/src/providers/registry/model-seeds.ts +93 -28
  178. package/src/providers/registry/types.ts +10 -1
  179. package/src/providers/resolved-model-policy.ts +26 -6
  180. package/src/providers/routed-config.ts +9 -1
  181. package/src/providers/stale-model-roster-migration.ts +44 -7
  182. package/src/remote-control/workspace-pi-runtime.ts +11 -6
  183. package/src/responses/compaction-summary.ts +45 -0
  184. package/src/responses/muse-tool-name-alias.ts +1 -2
  185. package/src/responses/parser.ts +3 -2
  186. package/src/responses/schema.ts +1 -0
  187. package/src/responses/thought-signature-replay.ts +10 -2
  188. package/src/routing/capability.ts +8 -2
  189. package/src/routing/history/ingest.ts +28 -3
  190. package/src/server/auth-cors.ts +3 -2
  191. package/src/server/chat-completions.ts +7 -0
  192. package/src/server/chat-native-eligibility.ts +7 -0
  193. package/src/server/chat-native-reasoning.ts +14 -4
  194. package/src/server/direct-local-http.ts +5 -2
  195. package/src/server/effort-policy.ts +5 -1
  196. package/src/server/index/live-sideband.ts +18 -15
  197. package/src/server/index/serve-options.ts +5 -4
  198. package/src/server/management/agent-settings-routes.ts +27 -15
  199. package/src/server/management/combo-routes.ts +4 -0
  200. package/src/server/management/config-routes.ts +2 -2
  201. package/src/server/management/decision-discovery.ts +12 -2
  202. package/src/server/management/hermes-profile-routes.ts +156 -0
  203. package/src/server/management/integration-routes.ts +85 -24
  204. package/src/server/management/model-routes.ts +2 -2
  205. package/src/server/management/model-row-export-metadata.ts +25 -6
  206. package/src/server/management/model-rows.ts +15 -20
  207. package/src/server/management/native-integration-routes.ts +11 -8
  208. package/src/server/management/route-registry.ts +4 -0
  209. package/src/server/management-api.ts +5 -0
  210. package/src/server/models-capabilities.ts +21 -3
  211. package/src/server/responses/adapter-delivery.ts +11 -1
  212. package/src/server/responses/adapter-dispatch.ts +2 -2
  213. package/src/server/responses/codex-ws-exchange.ts +39 -9
  214. package/src/server/responses/codex-ws-session.ts +38 -4
  215. package/src/server/responses/codex-ws-wire.ts +6 -1
  216. package/src/server/responses/combo-required-tool-contract.ts +103 -0
  217. package/src/server/responses/combo-stream-preflight.ts +8 -1
  218. package/src/server/responses/compact.ts +4 -3
  219. package/src/server/responses/context-overflow.ts +8 -1
  220. package/src/server/responses/core-combo-failure.ts +10 -0
  221. package/src/server/responses/core-combo.ts +23 -15
  222. package/src/server/responses/core-lifetime.ts +3 -0
  223. package/src/server/responses/core-normalize.ts +11 -1
  224. package/src/server/responses/core-options.ts +2 -0
  225. package/src/server/responses/main-hard-lock-routing.ts +60 -44
  226. package/src/server/responses/passthrough-delivery.ts +40 -2
  227. package/src/server/responses/policy-fallback.ts +6 -1
  228. package/src/server/responses/request-compression.ts +12 -7
  229. package/src/server/responses/request-prepare.ts +22 -2
  230. package/src/server/responses/request-sidecar-auth.ts +2 -0
  231. package/src/server/responses/response-effects.ts +22 -10
  232. package/src/server/responses/sidecar-execution.ts +11 -3
  233. package/src/server/stop-teardown.ts +36 -1
  234. package/src/server/ws-bridge.ts +1 -1
  235. package/src/service/desktop-supervision.d.mts +7 -4
  236. package/src/service/desktop-supervision.mjs +90 -13
  237. package/src/service/ownership-mutation-lease.mjs +21 -7
  238. package/src/types/config.ts +8 -2
  239. package/src/types/provider.ts +20 -6
  240. package/src/types/request.ts +10 -0
  241. package/src/types.ts +1 -0
  242. package/src/update/bind-probe.ts +29 -0
  243. package/src/update/job.ts +10 -29
  244. package/src/update/npm-install-job.ps1 +173 -0
  245. package/src/update/npm-install.mjs +70 -0
  246. package/src/update/stop-contract.d.mts +1 -0
  247. package/src/update/stop-contract.mjs +14 -0
  248. package/src/update/stop-decision.d.mts +1 -1
  249. package/src/update/stop-decision.mjs +13 -3
  250. package/src/update/teardown-handover.ts +166 -0
  251. package/src/update/transactional-install.d.mts +14 -3
  252. package/src/update/transactional-install.mjs +33 -7
  253. package/src/usage/expected-prices.ts +64 -31
  254. package/src/usage/timeline.ts +19 -9
  255. package/src/vision/eligibility.ts +15 -5
  256. package/src/vision/plan.ts +2 -2
  257. package/src/web-search/loop.ts +16 -2
  258. package/gui/dist/assets/App-sUf_8afJ.js +0 -58
  259. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
@@ -28,12 +28,16 @@ import type { OAuthAccountHealth, OAuthHealthLabel } from "../../oauth/health";
28
28
  import { isSelectableCodexPoolAccount } from "../account-id";
29
29
  import type { AdmissionLease } from "../../lib/admission";
30
30
  import { tryAcquireNativeMainProfileClaim } from "../native-main-admission";
31
- import { withNativeMainCredentialClaim, isNativeMainClaimUnavailable } from "./http";
31
+ import { withNativeMainCredentialClaim, isNativeMainClaimUnavailable, isNativeMainObservationUnavailable } from "./http";
32
32
  import { fetchMainAccountInfoAttempt, EMPTY_MAIN_ACCOUNT_INFO, mainResetCreditsForCurrentIdentity } from "./main-account-probe";
33
33
  import { fetchPoolAccountQuota, PoolQuotaProbeBusyError, POOL_QUOTA_REFRESH_CONCURRENCY } from "./pool-quota-probe";
34
34
  import type { PoolQuotaResult } from "./pool-quota-probe";
35
35
  import { getRuntimeConfig, configuredPoolAccount, mapWithConcurrency } from "./runtime-config";
36
36
  import { isPassiveRead } from "../../lib/passive-read";
37
+ import { configuredAdminToken } from "../../lib/admin-secrets";
38
+ import { nativeUserIdClaims } from "../reserve-availability";
39
+ import { extractAccountIdClaims } from "../../oauth/chatgpt";
40
+ import { codexUpstreamAccountKey } from "./account-identity";
37
41
  import { CODEX_MAIN_DUPLICATE_ACTION, configuredCodexMainDuplicate, getObservedMainCodexCollisionIdentity } from "../collision-identity";
38
42
 
39
43
  export function quotaForPlan<T extends Omit<StoredAccountQuota, "updatedAt"> | StoredAccountQuota | null>(
@@ -109,6 +113,7 @@ export function poolAccountDto(
109
113
  paused: boolean,
110
114
  priority: number,
111
115
  maskEmails: boolean,
116
+ upstreamAccountKey?: string,
112
117
  ): CodexAuthAccountDto {
113
118
  const plan = codexPlanValue(account.plan);
114
119
  const quota = quotaForPlan(quotaResult.quota, plan);
@@ -136,6 +141,9 @@ export function poolAccountDto(
136
141
  const duplicateMain = configuredCodexMainDuplicate(config, account.id);
137
142
  return {
138
143
  id: account.id,
144
+ slotId: account.id,
145
+ slotKind: "pool",
146
+ ...(upstreamAccountKey ? { upstreamAccountKey } : {}),
139
147
  email: projectEmail(account.email, maskEmails) ?? account.email,
140
148
  ...(account.alias !== undefined ? { alias: account.alias } : {}),
141
149
  ...(plan !== undefined ? { plan } : {}),
@@ -166,6 +174,11 @@ export function poolAccountDto(
166
174
 
167
175
  export interface CodexAuthAccountDto {
168
176
  id: string;
177
+ /** Registered slot identity; equal to id, including __main__ for native Codex. */
178
+ slotId: string;
179
+ slotKind: "native-main" | "pool";
180
+ /** Opaque local join key, present only with account and user claims. */
181
+ upstreamAccountKey?: string;
169
182
  alias?: string;
170
183
  email: string;
171
184
  plan?: string | null;
@@ -285,6 +298,7 @@ export async function listCodexAuthAccountsSnapshot(
285
298
  pruneCodexCredits([MAIN_CODEX_ACCOUNT_ID, ...poolAccounts.map(account => account.id)]);
286
299
  // One redaction decision for the whole snapshot, read once from the operator's config (#3859).
287
300
  const maskEmails = emailMaskingEnabled(runtimeConfig);
301
+ const identitySecret = configuredAdminToken();
288
302
  // A passive read (a Remote Link Child's, #6959) reports what this machine already observed: no
289
303
  // token refresh, no WHAM probe, and so none of the plan or credential writes they make.
290
304
  const passive = isPassiveRead();
@@ -292,6 +306,7 @@ export async function listCodexAuthAccountsSnapshot(
292
306
  ? { info: getMainAccountInfoCache() ?? EMPTY_MAIN_ACCOUNT_INFO, credentialChecked: false, hasCredential: false,
293
307
  identityGeneration: captureMainAccountIdentityGeneration() }
294
308
  : await fetchMainAccountInfoAttempt(forceRefresh, 1, undefined, false, forceRefresh, false, runtimeConfig);
309
+ const observedMainIdentity = getObservedMainCodexCollisionIdentity();
295
310
  const refreshedPool = await mapWithConcurrency(poolAccounts, POOL_QUOTA_REFRESH_CONCURRENCY, async account => {
296
311
  const cred = getCodexAccountCredential(account.id);
297
312
  let quotaResult: PoolQuotaResult;
@@ -363,6 +378,10 @@ export async function listCodexAuthAccountsSnapshot(
363
378
  const dtoAccount = generationLive && quotaResult.freshPlan
364
379
  ? { ...currentAccount, plan: quotaResult.freshPlan }
365
380
  : currentAccount;
381
+ const user = nativeUserIdClaims(currentCredential.accessToken);
382
+ const accountClaim = extractAccountIdClaims(currentCredential.accessToken);
383
+ const verifiedAccountId = !accountClaim.conflict && accountClaim.accountId === currentCredential.chatgptAccountId
384
+ ? accountClaim.accountId : undefined;
366
385
  return [poolAccountDto(
367
386
  runtimeConfig,
368
387
  dtoAccount,
@@ -371,6 +390,8 @@ export async function listCodexAuthAccountsSnapshot(
371
390
  isCodexAccountPaused(runtimeConfig, accountId),
372
391
  getCodexAccountPriority(runtimeConfig, accountId),
373
392
  maskEmails,
393
+ codexUpstreamAccountKey(identitySecret, verifiedAccountId,
394
+ user.conflict ? undefined : user.userId),
374
395
  )];
375
396
  });
376
397
  const projectSnapshot = (mainRefreshRefused = false): CodexAuthAccountsSnapshot => {
@@ -402,8 +423,14 @@ export async function listCodexAuthAccountsSnapshot(
402
423
  ? mainResult.terminalAuthFailure === true && liveQuotaRefresh?.status === "http_error"
403
424
  ? "unauthorized" : "refresh_failed"
404
425
  : mainHealth.status === "reauth_required" ? mainHealth.reason : undefined;
426
+ const mainIdentity = mainSnapshotLive && getObservedMainCodexCollisionIdentity() === observedMainIdentity
427
+ ? observedMainIdentity : undefined;
428
+ const mainAccountKey = codexUpstreamAccountKey(identitySecret, mainIdentity?.accountId, mainIdentity?.userId);
405
429
  const main: CodexAuthAccountDto = {
406
430
  id: MAIN_CODEX_ACCOUNT_ID,
431
+ slotId: MAIN_CODEX_ACCOUNT_ID,
432
+ slotKind: "native-main",
433
+ ...(mainAccountKey ? { upstreamAccountKey: mainAccountKey } : {}),
407
434
  email: projectEmail(mainInfo.email, maskEmails) ?? "Codex App login",
408
435
  plan: mainInfo.plan,
409
436
  ...(liveQuotaRefresh ? { quotaRefresh: liveQuotaRefresh } : {}),
@@ -442,7 +469,7 @@ export async function listCodexAuthAccountsSnapshot(
442
469
  try {
443
470
  return await withNativeMainCredentialClaim(async () => projectSnapshot(isMainAccountRefreshGrantRejected()));
444
471
  } catch (error) {
445
- if (isNativeMainClaimUnavailable(error)) return projectSnapshot();
472
+ if (isNativeMainObservationUnavailable(error)) return projectSnapshot();
446
473
  throw error;
447
474
  } finally {
448
475
  projectionLease.release();
@@ -1,3 +1,5 @@
1
+ import { codexHomeIsAbsent } from "../codex-home-owner";
2
+ import { getCodexHome } from "../paths";
1
3
  import { withNativeMainSharedClaim } from "../native-main-claim";
2
4
  import { resolveNativeProfileContext } from "../native-profile-store";
3
5
  import { NativeProfileError } from "../native-profile-types";
@@ -7,6 +9,17 @@ export function isNativeMainClaimUnavailable(error: unknown): error is NativePro
7
9
  && (error.code === "NATIVE_MAIN_CLAIM_BUSY" || error.code === "NATIVE_MAIN_CLAIM_UNAVAILABLE");
8
10
  }
9
11
 
12
+ /** Missing native homes leave reads unobserved; credential operations still require their claim. */
13
+ export function isNativeMainObservationUnavailable(error: unknown): error is NativeProfileError {
14
+ if (isNativeMainClaimUnavailable(error)) return true;
15
+ if (!(error instanceof NativeProfileError) || error.code !== "CODEX_HOME_UNAVAILABLE") return false;
16
+ try {
17
+ return codexHomeIsAbsent(getCodexHome());
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+
10
23
  export function withNativeMainCredentialClaim<T>(operation: () => Promise<T>): Promise<T> {
11
24
  return withNativeMainSharedClaim(resolveNativeProfileContext(), operation);
12
25
  }
@@ -23,7 +23,7 @@ import type { AdmissionLease } from "../../lib/admission";
23
23
  import { nonEmptyPlan } from "./runtime-config";
24
24
  import { tryAcquireNativeMainProfileClaim } from "../native-main-admission";
25
25
  import { WHAM_REQUEST_TIMEOUT_MS } from "../quota-recovery-timing";
26
- import { withNativeMainCredentialClaim, isNativeMainClaimUnavailable } from "./http";
26
+ import { withNativeMainCredentialClaim, isNativeMainObservationUnavailable } from "./http";
27
27
  import { readMainAuthErrorCode, currentQuotaDispatchSequence, nextQuotaDispatchSequence, isQuotaDispatchCurrent, publishQuotaDispatch } from "./pool-quota-probe";
28
28
 
29
29
  /**
@@ -198,7 +198,7 @@ export async function fetchMainAccountInfoAttempt(
198
198
  try {
199
199
  return await withNativeMainCredentialClaim(operation);
200
200
  } catch (error) {
201
- if (isNativeMainClaimUnavailable(error)) {
201
+ if (isNativeMainObservationUnavailable(error)) {
202
202
  return {
203
203
  info: EMPTY_MAIN_ACCOUNT_INFO,
204
204
  credentialChecked: false,
@@ -2,7 +2,7 @@ import { codexAccountUsesCreditsAfterLimit, codexUsageLimitResetAt } from "../ac
2
2
  import { nextCodexUsageQueryAt, nextQuotaQueryDelay, pruneRemovedCodexPoolUsageAccounts } from "../quota-query-backoff";
3
3
  import { CODEX_PRIORITY_FAILBACK_REFRESH_MS } from "../account-priority";
4
4
  import { codexQuotaHasFreshUsage } from "../quota-observation-freshness";
5
- import { getCodexAccountCredential, getValidCodexToken, readCodexAccountRecord } from "../account-store";
5
+ import { getCodexAccountCredential, getValidCodexToken, isCodexAccountGenerationLive, readCodexAccountRecord } from "../account-store";
6
6
  import { getAccountQuota, getMainPolicyQuota, isCompleteCodexQuotaRecoverySnapshot } from "../quota";
7
7
  import { isCodexAccountPaused } from "../account-pause";
8
8
  import { hasSpendableCodexCredits } from "../quota-types";
@@ -80,6 +80,13 @@ const MAIN_CREDIT_RENEWAL_AGE_MS = 3 * 60_000;
80
80
 
81
81
  /** Traffic headers renew usage, never the independent credit observation (#7377). */
82
82
  function poolCreditRenewalDue(config: OcxConfig, accountId: string, now = Date.now()): boolean {
83
+ const openai = config.providers[OPENAI_CODEX_PROVIDER_ID];
84
+ if (!openai || openai.disabled === true || !isCanonicalOpenAiForwardProvider(openai)) return false;
85
+ const mode = providerCodexAccountMode(OPENAI_CODEX_PROVIDER_ID, openai);
86
+ // Direct may renew only explicitly bound stored accounts. Check queued work too:
87
+ // credit opt-in alone does not authorize reads for every saved login.
88
+ if (mode !== "pool" && (mode !== "direct"
89
+ || !Object.values(config.codexAccountNamespaces ?? {}).includes(accountId))) return false;
83
90
  const account = configuredPoolAccount(config, accountId);
84
91
  if (!account || !codexAccountUsesCreditsAfterLimit(config, accountId)
85
92
  || isCodexAccountPaused(config, accountId) || isAccountNeedsReauth(accountId)) return false;
@@ -313,7 +320,9 @@ export async function primeCodexPoolQuotas(
313
320
  !openai
314
321
  || openai.disabled === true
315
322
  || !isCanonicalOpenAiForwardProvider(openai)
316
- || providerCodexAccountMode(OPENAI_CODEX_PROVIDER_ID, openai) !== "pool"
323
+ || (providerCodexAccountMode(OPENAI_CODEX_PROVIDER_ID, openai) !== "pool"
324
+ && !(reason === "credit-renewal"
325
+ && providerCodexAccountMode(OPENAI_CODEX_PROVIDER_ID, openai) === "direct"))
317
326
  ) return;
318
327
  if (primeInFlight) return primeInFlight;
319
328
  // Count attempted passes, including failed reads; incoming traffic must not flood WHAM.
@@ -384,7 +393,11 @@ export async function primeCodexPoolQuotas(
384
393
  const quota = getAccountQuota(a.id);
385
394
  const bypassCachedQuota = reason === "credit-renewal" || (reason === "priority-failback" && quota !== null
386
395
  && !codexQuotaHasFreshUsage(quota, a.plan, Date.now(), CODEX_PRIORITY_FAILBACK_REFRESH_MS));
387
- result = await fetchPoolAccountQuota(a.id, bypassCachedQuota, a.plan, getValidPoolTokenForPrime);
396
+ result = await fetchPoolAccountQuota(a.id, bypassCachedQuota, a.plan, getValidPoolTokenForPrime,
397
+ false, undefined, undefined, false, reason === "credit-renewal"
398
+ ? generation => isCodexAccountGenerationLive(a.id, generation)
399
+ && poolCreditRenewalDue(getRuntimeConfig(config), a.id)
400
+ : undefined);
388
401
  } catch (error) {
389
402
  // Local quota-flight saturation proves no WHAM request existed for this account.
390
403
  // Consume it per item so sibling workers remain inside the shared prime lifetime.
@@ -88,6 +88,8 @@ export function publishQuotaDispatch(sequence: number): void {
88
88
 
89
89
  export interface PoolQuotaProbeEvidence {
90
90
  onDispatch?: (sequence: number) => void;
91
+ /** Optional caller authority rechecked after token preparation, including 401 replay. */
92
+ mayDispatch?: (credentialGeneration: number) => boolean;
91
93
  mayPublish?: () => boolean;
92
94
  attempted?: NonNullable<PoolQuotaResult["quotaProbeAttempted"]>;
93
95
  }
@@ -109,6 +111,7 @@ export function withQuotaProbeEvidence(
109
111
 
110
112
  export interface PoolQuotaRefreshFlight {
111
113
  state: {
114
+ dispatchGuarded?: boolean;
112
115
  dispatchSequence?: number;
113
116
  superseded?: boolean;
114
117
  startCredentialGeneration?: number;
@@ -255,6 +258,10 @@ export async function recoverPoolQuotaFrom401(ctx: {
255
258
  // generation and opens a redundant flight.
256
259
  ctx.onCredentialGeneration?.(refreshed.generation);
257
260
 
261
+ if (ctx.quotaProbeEvidence.mayDispatch?.(refreshed.generation) === false) {
262
+ return { quota: getAccountQuota(accountId), needsReauth: false, credentialGeneration: refreshed.generation, quotaProbeSkipped: true };
263
+ }
264
+
258
265
  const writerGeneration = captureConfigGeneration();
259
266
  const poolWriter = capturePoolQuotaWriter(accountId, refreshed);
260
267
  const replayRead = await fetchCodexUsage<PoolQuotaResult>(`pool:${accountId}:${writerGeneration}:${refreshed.generation}`, {
@@ -403,6 +410,9 @@ export async function fetchFreshPoolAccountQuota(
403
410
  const poolWriter = capturePoolQuotaWriter(accountId, { accessToken, chatgptAccountId, generation });
404
411
  requestCredentialGeneration = generation;
405
412
  onCredentialGeneration?.(generation);
413
+ if (quotaProbeEvidence.mayDispatch?.(generation) === false) {
414
+ return { quota: getAccountQuota(accountId), needsReauth: false, credentialGeneration: generation, quotaProbeSkipped: true };
415
+ }
406
416
  const admission = await fetchCodexUsage<PoolQuotaResult>(
407
417
  `pool:${accountId}:${writerGeneration}:${generation}${afterDispatchSequence === undefined ? "" : `:post-reset:${afterDispatchSequence}`}`, {
408
418
  headers: { Authorization: `Bearer ${accessToken}`, "ChatGPT-Account-Id": chatgptAccountId },
@@ -496,6 +506,7 @@ export async function fetchPoolAccountQuota(
496
506
  afterDispatchSequence?: number,
497
507
  recoveryProbeNow?: number,
498
508
  explicitRefresh = false,
509
+ mayDispatch?: PoolQuotaProbeEvidence["mayDispatch"],
499
510
  ): Promise<PoolQuotaResult> {
500
511
  const existing = getAccountQuota(accountId);
501
512
  if (afterDispatchSequence === undefined && !forceRefresh && existing && Date.now() - existing.updatedAt < POOL_CACHE_TTL) {
@@ -527,6 +538,8 @@ export async function fetchPoolAccountQuota(
527
538
  const generation = flight.state.resolvedCredentialGeneration
528
539
  ?? flight.state.startCredentialGeneration;
529
540
  return !flight.state.superseded
541
+ // An ordinary read must not inherit a renewal owner's revocable authority.
542
+ && (mayDispatch !== undefined || !flight.state.dispatchGuarded)
530
543
  && (afterDispatchSequence === undefined || (flight.state.dispatchSequence ?? 0) > afterDispatchSequence)
531
544
  && generation !== undefined && isCodexAccountGenerationLive(accountId, generation);
532
545
  });
@@ -543,6 +556,7 @@ export async function fetchPoolAccountQuota(
543
556
  for (const flight of flights ?? []) flight.state.superseded = true;
544
557
  }
545
558
  const state: PoolQuotaRefreshFlight["state"] = {
559
+ dispatchGuarded: mayDispatch !== undefined,
546
560
  startCredentialGeneration: record?.generation,
547
561
  validatePending,
548
562
  };
@@ -554,6 +568,7 @@ export async function fetchPoolAccountQuota(
554
568
  getValidToken,
555
569
  {
556
570
  onDispatch: sequence => { state.dispatchSequence = sequence; },
571
+ mayDispatch,
557
572
  mayPublish: () => state.superseded !== true,
558
573
  },
559
574
  afterDispatchSequence,
@@ -1,4 +1,4 @@
1
- import { bindPoolCreditPolicy, poolCreditHoldResetAt, poolContextCreditHoldResetAt } from "./pool-credit-policy";
1
+ import { bindPoolCreditPolicy, poolCreditHoldResetAt, poolContextCreditHoldResetAt, poolCreditRecoveryNeeded, poolContextCreditRecoveryNeeded, poolCreditRecoveryRetryAt } from "./pool-credit-policy";
2
2
  import { hasSpendableCodexCredits } from "./quota-types";
3
3
  import { nextQuotaQueryDelay } from "./quota-query-backoff";
4
4
  import { noteMainAccountActivity } from "./main-account-external-usage";
@@ -548,17 +548,20 @@ export class CodexMainAccountHardLockError extends CodexAccountCooldownError {
548
548
  export class CodexPoolAccountCreditsOffError extends CodexAccountCooldownError {
549
549
  readonly resetAt: number;
550
550
 
551
- constructor(accountId: string, resetAt: number) {
552
- super(accountId, resetAt);
551
+ constructor(accountId: string, resetAt: number, creditRecovery = false, quotaScope?: CodexQuotaScope) {
552
+ // Keep the included reset; a metadata hint neither admits nor clears an upstream hold.
553
+ super(accountId, creditRecovery ? poolCreditRecoveryRetryAt(accountId, resetAt, quotaScope) : resetAt);
553
554
  this.name = "CodexPoolAccountCreditsOffError";
554
555
  this.resetAt = resetAt;
555
- this.message = "The selected Codex account reached its usage limit, and spending credits is off or no fresh spendable balance is available."
556
+ this.message = creditRecovery
557
+ ? "The selected Codex account reached its usage limit and needs a fresh credit observation. Retry later; spending remains blocked until fresh spendable credits are observed."
558
+ : "The selected Codex account reached its usage limit, and spending credits is off or no fresh spendable balance is available."
556
559
  + " Wait for the limit to reset, choose another account, or explicitly allow credits for this account in Codex Auth.";
557
560
  }
558
561
  }
559
562
 
560
- function assertPoolAccountCredits(accountId: string, resetAt: number | undefined): void {
561
- if (resetAt !== undefined) throw new CodexPoolAccountCreditsOffError(accountId, resetAt);
563
+ function assertPoolAccountCredits(accountId: string, resetAt: number | undefined, creditRecovery: boolean, quotaScope?: CodexQuotaScope): void {
564
+ if (resetAt !== undefined) throw new CodexPoolAccountCreditsOffError(accountId, resetAt, creditRecovery, quotaScope);
562
565
  }
563
566
 
564
567
  /** The main login may not spend credits and one of its usage windows is full (#6334). */
@@ -780,7 +783,7 @@ export function createCodexAuthDispatchGuard(
780
783
  return headers => {
781
784
  if (config.pausedCodexAccountIds?.includes(ctx.accountId)) throw new CodexPoolAuthenticationError("Selected Codex account is paused; resume it in account settings");
782
785
  if (ctx.kind === "main-pool") { reserveGuard?.(headers); return; }
783
- assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx, config));
786
+ assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx, config), poolContextCreditRecoveryNeeded(ctx, config), ctx.quotaScope);
784
787
  reserveGuard?.(headers);
785
788
  };
786
789
  }
@@ -1569,7 +1572,7 @@ async function resolveCodexAuthContextUnannotated(
1569
1572
  try {
1570
1573
  assertCodexAccountValidationReady(accountId);
1571
1574
  if (configuredCodexMainDuplicate(config, accountId)) throw new CodexPoolAuthenticationError(CODEX_MAIN_DUPLICATE_ACTION);
1572
- assertPoolAccountCredits(accountId, poolCreditHoldResetAt(policy, accountId, config));
1575
+ assertPoolAccountCredits(accountId, poolCreditHoldResetAt(policy, accountId, config), poolCreditRecoveryNeeded(policy, accountId), quotaScope);
1573
1576
  } catch (cause) {
1574
1577
  // Nothing will reach upstream, so give the trial back instead of leaving the held account
1575
1578
  // unprobeable until the lease deadline lapses (#4701).
@@ -1700,7 +1703,7 @@ async function resolveCodexAuthContextUnannotated(
1700
1703
  const token = await getValidCodexToken(accountId, { signal: options.signal });
1701
1704
  assertCodexAccountValidationReady(accountId);
1702
1705
  if (configuredCodexMainDuplicate(config, accountId)) throw new CodexPoolAuthenticationError(CODEX_MAIN_DUPLICATE_ACTION);
1703
- assertPoolAccountCredits(accountId, poolCreditHoldResetAt(policy, accountId, config));
1706
+ assertPoolAccountCredits(accountId, poolCreditHoldResetAt(policy, accountId, config), poolCreditRecoveryNeeded(policy, accountId), quotaScope);
1704
1707
  return bindPoolCreditPolicy({
1705
1708
  kind: "pool",
1706
1709
  accountId,
@@ -1732,7 +1735,7 @@ async function resolveCodexAuthContextUnannotated(
1732
1735
 
1733
1736
  export function assertCodexAuthContextNotCooled(ctx: CodexAuthContext | undefined): void {
1734
1737
  if (ctx?.kind !== "pool" && ctx?.kind !== "main-pool") return;
1735
- if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx));
1738
+ if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx), poolContextCreditRecoveryNeeded(ctx), ctx.quotaScope);
1736
1739
  // A context holding the probe lease was deliberately admitted through the cooldown.
1737
1740
  if (ctx.probeLeaseId) return;
1738
1741
  const cooldown = getCodexQuotaHealthSnapshot(ctx.accountId, ctx.quotaScope);
@@ -1748,7 +1751,7 @@ export function applyCodexAuthContextToProvider(
1748
1751
  ): OcxRuntimeProviderConfig {
1749
1752
  if (mode !== "pool" || (ctx.kind !== "pool" && ctx.kind !== "main-pool") || provider.authMode !== "forward") return provider;
1750
1753
  assertCodexAccountValidationReady(ctx.accountId);
1751
- if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx));
1754
+ if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx), poolContextCreditRecoveryNeeded(ctx), ctx.quotaScope);
1752
1755
  return {
1753
1756
  ...provider,
1754
1757
  _codexAccountOverride: {
@@ -1803,7 +1806,7 @@ export function materializeCodexUpstreamAuth(
1803
1806
  }
1804
1807
  if (ctx.kind === "pool" || ctx.kind === "main-pool") {
1805
1808
  assertCodexAccountValidationReady(ctx.accountId);
1806
- if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx, options.config));
1809
+ if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx, options.config), poolContextCreditRecoveryNeeded(ctx, options.config), ctx.quotaScope);
1807
1810
  selected.set("authorization", `Bearer ${ctx.accessToken}`);
1808
1811
  selected.set("chatgpt-account-id", ctx.chatgptAccountId);
1809
1812
  if (ctx.kind === "main-pool") {
@@ -485,6 +485,8 @@ export interface ObservedCatalogMergeInput {
485
485
  readonly ultraFastTier?: boolean;
486
486
  /** Current captured wire declarations; disk rows and templates never populate this set. */
487
487
  readonly configuredUltraFastSlugs?: ReadonlySet<string>;
488
+ /** Current config-only verdict for persisted rows (not authority from the old disk tier). */
489
+ readonly retainedFlexPolicyBySlug?: ReadonlyMap<string, boolean>;
488
490
  readonly catalogModels: readonly RawEntry[];
489
491
  readonly baselineCatalogModels: readonly RawEntry[];
490
492
  readonly routedEntries: readonly RawEntry[];
@@ -532,6 +534,7 @@ export interface ObservedCatalogMergeInput {
532
534
  export function mergeCatalogEntriesFromObservedState({
533
535
  ultraFastTier = false,
534
536
  configuredUltraFastSlugs = new Set(),
537
+ retainedFlexPolicyBySlug = new Map(),
535
538
  catalogModels,
536
539
  baselineCatalogModels,
537
540
  routedEntries,
@@ -889,6 +892,25 @@ export function mergeCatalogEntriesFromObservedState({
889
892
  || trustedAccountBoundNativeCatalogSlug(entry) !== undefined) continue;
890
893
  applyConfiguredUltraFast(entry, operatorRows.get(entry.slug), configuredUltraFastSlugs.has(entry.slug), ultraFastTier);
891
894
  }
895
+ // Degraded discovery preserves disk rows, so they bypass fresh tier generation.
896
+ // Revoke only an explicitly disallowed Flex tier according to today's provider policy;
897
+ // a transient outage must not erase Flex while the configured wire still permits it.
898
+ const persistedRoutedSet = new Set(preservedRoutedEntries);
899
+ for (const entry of finalRoutedEntries) {
900
+ if (!persistedRoutedSet.has(entry)) continue;
901
+ const slug = typeof entry.slug === "string" ? entry.slug : "";
902
+ const excluded = isNativeAliasCatalogEntry(entry) || isExactComboCatalogEntry(entry, exactComboSlugs);
903
+ if (!excluded && retainedFlexPolicyBySlug.get(slug) !== false) continue;
904
+ if (Array.isArray(entry.service_tiers)) {
905
+ entry.service_tiers = entry.service_tiers.filter(tier => tier?.id !== "flex");
906
+ }
907
+ if (Array.isArray(entry.additional_speed_tiers)) {
908
+ entry.additional_speed_tiers = entry.additional_speed_tiers.filter(tier => tier !== "flex");
909
+ }
910
+ for (const field of ["service_tier", "default_service_tier"] as const) {
911
+ if (entry[field] === "flex") delete entry[field];
912
+ }
913
+ }
892
914
  const finalRoutedEntrySet = new Set(finalRoutedEntries);
893
915
  const degradedPreservedCount = preservedRoutedEntries.filter(entry => {
894
916
  if (!finalRoutedEntrySet.has(entry)) return false;
@@ -1,10 +1,21 @@
1
1
  import { COMBO_NAMESPACE } from "../../combos";
2
+ import type { OcxProviderConfig } from "../../types";
3
+ import { decodeRoutedModelId } from "../../providers/slug-codec";
4
+ import { fastPolicyForModel } from "../../providers/service-tier";
2
5
  import type { ResolvedFastPolicy } from "../../providers/fastwire";
3
6
  import { catalogModelSlug, type CatalogModel, type RawEntry } from "./parsing";
4
7
  import { preserveOperatorUltraFastTiers } from "./operator-tiers";
5
8
 
6
9
  const MANAGED_ULTRAFAST = "opencodex_managed_ultrafast";
7
10
 
11
+ /** Advertise Flex only when the final route can forward the caller's exact flex tier. */
12
+ export function supportsConfiguredFlex(policy: ResolvedFastPolicy | undefined): boolean {
13
+ return policy?.eligibility === "eligible"
14
+ && policy.fastWire?.kind === "service-tier"
15
+ && policy.fastWire.canonicalToWire.flex === "flex"
16
+ && policy.forwardCallerTier;
17
+ }
18
+
8
19
  /** Advertise Ultra Fast only when the eligible final wire explicitly maps that exact tier. */
9
20
  export function supportsConfiguredUltraFast(policy: ResolvedFastPolicy | undefined): boolean {
10
21
  return policy?.eligibility === "eligible"
@@ -48,3 +59,62 @@ export function applyConfiguredUltraFast(
48
59
  // Advertising a selectable capability does not opt the user into its increased usage.
49
60
  entry[MANAGED_ULTRAFAST] = entry.slug;
50
61
  }
62
+
63
+ /**
64
+ * Re-evaluate persisted routed Flex choices using current provider configuration. Degraded
65
+ * discovery keeps disk rows but cannot let a withdrawn wire declaration keep old picker tiers.
66
+ * Only rows tied to a configured provider are judged; unmanaged foreign rows are untouched.
67
+ */
68
+ export function retainedFlexPolicyBySlug(
69
+ providers: Readonly<Record<string, OcxProviderConfig>>,
70
+ rows: readonly RawEntry[],
71
+ observedModels: readonly CatalogModel[],
72
+ ): ReadonlyMap<string, boolean> {
73
+ const result = new Map<string, boolean>();
74
+ const currentModels = new Map<string, CatalogModel[]>();
75
+ for (const model of observedModels) {
76
+ const slug = catalogModelSlug(model);
77
+ const candidates = currentModels.get(slug) ?? [];
78
+ candidates.push(model);
79
+ currentModels.set(slug, candidates);
80
+ }
81
+ for (const row of rows) {
82
+ const slug = typeof row.slug === "string" ? row.slug : "";
83
+ const slash = slug.indexOf("/");
84
+ if (slash <= 0) continue;
85
+ const namespace = slug.slice(0, slash);
86
+ const owner = Object.entries(providers).find(([name, provider]) =>
87
+ name === namespace || provider.alias === namespace);
88
+ if (!owner) continue;
89
+ const [name, provider] = owner;
90
+ if (provider.disabled === true || namespace === COMBO_NAMESPACE || name === COMBO_NAMESPACE) {
91
+ result.set(slug, false);
92
+ continue;
93
+ }
94
+ const observed = currentModels.get(slug);
95
+ if (observed?.length) {
96
+ // The current gather re-applies captured policy hints; conflicting rows fail closed.
97
+ result.set(slug, observed.every(model =>
98
+ model.provider !== COMBO_NAMESPACE && model.nativeAlias !== true
99
+ && model.supportsServiceTier === true && model.supportsFlexTier === true));
100
+ continue;
101
+ }
102
+ const requested = slug.slice(slash + 1);
103
+ const aliased = Object.entries(provider.modelAliases ?? {})
104
+ .filter(([, alias]) => alias === requested).map(([id]) => id);
105
+ // A non-unique short alias is not authority for a capability declaration.
106
+ if (aliased.length > 1) {
107
+ result.set(slug, false);
108
+ continue;
109
+ }
110
+ const knownIds = [
111
+ ...(provider.models ?? []),
112
+ ...Object.keys(provider.modelSupportsServiceTier ?? {}),
113
+ ...Object.keys(provider.modelAliases ?? {}),
114
+ ...Object.keys(provider.modelAdapters ?? {}),
115
+ ];
116
+ const modelId = aliased[0] ?? decodeRoutedModelId(requested, knownIds);
117
+ result.set(slug, supportsConfiguredFlex(fastPolicyForModel(provider, modelId, name)));
118
+ }
119
+ return result;
120
+ }
@@ -9,6 +9,7 @@ import { CODEX_CONFIG_PATH, CODEX_MODELS_CACHE_PATH, DEFAULT_CATALOG_PATH, readR
9
9
  import { clearModelCache, DEFAULT_MODEL_CACHE_TTL_MS, getFreshCached, getStaleCached, isModelsFetchCoolingDown, markModelsFetchFailure, setCached } from "../model-cache";
10
10
  import { buildModelsRequest, resolveModelsAuthToken } from "../../oauth";
11
11
  import type { OcxConfig, OcxProviderConfig } from "../../types";
12
+ import { exportDefaultReasoningEffort, exportReasoningEfforts } from "../../clients/config-export/reasoning-metadata";
12
13
  import { modelInList } from "../../types";
13
14
  import { CODEX_REASONING_LEVELS, codexEffortRank, configuredReasoningEfforts, modelRecordValue, sanitizeCodexReasoningEfforts, type CodexReasoningLevel } from "../../reasoning-effort";
14
15
  import { getModelMetadata, getModelMetadataCaseInsensitive, listModelMetadata, resolveMetadataProvider } from "../../generated/model-metadata";
@@ -53,19 +54,20 @@ import {
53
54
  } from "../runtime";
54
55
 
55
56
  export function nativeEffortClamp(slug: string, effort: string | undefined): string | null {
56
- if (!effort || (effort !== "max" && effort !== "ultra")) return null;
57
+ if (!effort) return null;
57
58
  if (slug.includes("/")) return null; // routed models map efforts in their adapters
58
59
  // `ultra` is a client-facing catalog choice (max reasoning plus proactive delegation) that
59
60
  // codex-rs converts to `max` before any request (core/src/client.rs
60
61
  // `reasoning_effort_for_request`). The ChatGPT backend rejects it with HTTP 400 even for a
61
62
  // model whose pinned ladder lists it (#7590), so it is never a native wire value: fold it to
62
63
  // `max`, then clamp `max` like a direct selection.
63
- const wire = "max";
64
+ const wire = effort === "ultra" ? "max" : effort;
64
65
  const entry = UPSTREAM_NATIVE_ENTRIES.get(slug);
65
66
  const levels = Array.isArray(entry?.supported_reasoning_levels)
66
67
  ? entry.supported_reasoning_levels as Array<{ effort?: string }>
67
68
  : [];
68
69
  if (levels.length === 0) {
70
+ if (wire !== "max") return null;
69
71
  // Not snapshot-covered. gpt-5.6 natives have a REAL max rung (ensureGpt56ReasoningLevels
70
72
  // restores it even off-snapshot) -> never clamp. Every other bare native (gpt-5.5,
71
73
  // a retired slug a client still asks for, and future old-ladder slugs)
@@ -76,12 +78,11 @@ export function nativeEffortClamp(slug: string, effort: string | undefined): str
76
78
  }
77
79
  const supported = levels.flatMap(l => typeof l.effort === "string" ? [l.effort] : []);
78
80
  if (supported.includes(wire)) return effort === wire ? null : wire;
79
- const rank = ["minimal", "low", "medium", "high", "xhigh", "max"];
80
- const highest = supported
81
- .filter(e => rank.includes(e))
82
- .sort((a, b) => rank.indexOf(a) - rank.indexOf(b))
83
- .at(-1);
84
- return highest ?? null;
81
+ const rank = ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"];
82
+ const requestedRank = rank.indexOf(wire);
83
+ if (requestedRank < 0) return null;
84
+ const available = supported.filter(e => rank.includes(e)).sort((a, b) => rank.indexOf(a) - rank.indexOf(b));
85
+ return available.filter(e => rank.indexOf(e) <= requestedRank).at(-1) ?? available[0] ?? null;
85
86
  }
86
87
 
87
88
  export function shouldApplyNativeEffortClamp(
@@ -139,6 +140,13 @@ export const ROUTED_REASONING_LEVELS = [...CODEX_REASONING_LEVELS];
139
140
 
140
141
  export function applyCatalogModelMetadata(entry: RawEntry, model?: CatalogModel): void {
141
142
  if (!model) return;
143
+ applyClientReasoningCapabilities(entry, model);
144
+ if (model.supportsThinkingToggle === true && model.supportsReasoningEffort === false
145
+ && Array.isArray(entry.supported_reasoning_levels)) {
146
+ entry.supported_reasoning_levels = entry.supported_reasoning_levels.map(level => ({
147
+ ...level, description: level.effort === "none" ? "Thinking off" : "Thinking on",
148
+ }));
149
+ }
142
150
  // This marker survives strict catalog normalization and lets sync distinguish a stale
143
151
  // bare combo alias from a genuine native model row.
144
152
  if (model.provider === COMBO_NAMESPACE) entry.owned_by = model.owned_by ?? COMBO_NAMESPACE;
@@ -184,6 +192,8 @@ export function applyCatalogModelMetadata(entry: RawEntry, model?: CatalogModel)
184
192
  entry.supports_reasoning_summaries = model.supportsReasoningSummaries;
185
193
  }
186
194
  if (model.supportsServiceTier === true) {
195
+ const eligibleRoutedFlex = model.supportsFlexTier === true
196
+ && model.provider !== COMBO_NAMESPACE && model.nativeAlias !== true;
187
197
  const nativeFast = model.codexForwardNativeCapabilityAlias && Array.isArray(entry.service_tiers)
188
198
  ? entry.service_tiers.find(tier => tier?.id === "priority")
189
199
  : undefined;
@@ -192,8 +202,12 @@ export function applyCatalogModelMetadata(entry: RawEntry, model?: CatalogModel)
192
202
  id: "priority",
193
203
  name: "Fast",
194
204
  description: model.fastTierDescription ?? nativeFast?.description ?? "1.5x speed, increased usage",
195
- }];
196
- entry.additional_speed_tiers = ["fast"];
205
+ }, ...(eligibleRoutedFlex ? [{
206
+ id: "flex",
207
+ name: "Flex",
208
+ description: "Capacity-dependent processing; availability and latency may vary",
209
+ }] : [])];
210
+ entry.additional_speed_tiers = eligibleRoutedFlex ? ["fast", "flex"] : ["fast"];
197
211
  }
198
212
  stampCapabilityProvenance(entry, model);
199
213
  }
@@ -248,6 +262,26 @@ function stampCapabilityProvenance(entry: RawEntry, model: CatalogModel): void {
248
262
  };
249
263
  }
250
264
 
265
+ /** Project explicit independent capabilities only at Codex's effort-enum boundary. */
266
+ function applyClientReasoningCapabilities(entry: RawEntry, model: CatalogModel): void {
267
+ // Positive effort support can be inferred from a legacy ladder. It does not classify
268
+ // independent controls or opt that model out of the existing max/ultra synthesis.
269
+ if (model.supportsThinkingToggle === undefined && model.supportsReasoningEffort !== false
270
+ && model.supportsReasoning !== false) return;
271
+ const efforts = exportReasoningEfforts(model);
272
+ if (efforts === undefined && model.supportsReasoningEffort === undefined) {
273
+ // A negative toggle declaration says nothing about an unknown effort capability.
274
+ const legacy = catalogEntryEfforts(entry).filter(effort => effort !== "none");
275
+ applyReasoningLevels(entry, legacy, typeof entry.default_reasoning_level === "string" ? entry.default_reasoning_level : undefined, true);
276
+ return;
277
+ }
278
+ const declaredDefault = exportDefaultReasoningEffort(model);
279
+ applyReasoningLevels(entry, efforts ?? [], declaredDefault, true);
280
+ if (model.supportsThinkingToggle === true && declaredDefault === undefined) {
281
+ delete entry.default_reasoning_level;
282
+ }
283
+ }
284
+
251
285
  export function applyReasoningLevels(
252
286
  entry: RawEntry,
253
287
  effortsOverride?: string[],
@@ -552,6 +552,7 @@ function providerCatalogFingerprint(name: string, prov: OcxProviderConfig): Reco
552
552
  maxOut: prov.modelMaxOutputTokens ?? null,
553
553
  autoCompact: prov.modelAutoCompactTokenLimits ?? null,
554
554
  inMod: prov.modelInputModalities ?? null,
555
+ inModAll: prov.inputModalities ?? null,
555
556
  capabilities: prov.modelCapabilities ?? null,
556
557
  re: prov.modelReasoningEfforts ?? null,
557
558
  suppressMax: prov.modelSuppressSyntheticMax ?? null,