tuxevil-rotator 4.0.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +8 -1
  3. package/package.json +1 -1
  4. package/src/audio-transcription.ts +44 -4
  5. package/src/compat.ts +196 -222
  6. package/src/config-defaults.ts +5 -0
  7. package/src/config-overrides.ts +16 -0
  8. package/src/dashboard-live.ts +10 -8
  9. package/src/dashboard-types.ts +94 -1
  10. package/src/dashboard.ts +194 -1
  11. package/src/effort-levels.ts +43 -0
  12. package/src/effort-routing.ts +304 -0
  13. package/src/index.ts +2 -5
  14. package/src/model-catalog-revision.ts +20 -0
  15. package/src/model-catalog.ts +304 -0
  16. package/src/providers/adapter.ts +18 -0
  17. package/src/providers/google-antigravity/catalog.ts +190 -1
  18. package/src/providers/google-antigravity/forward.ts +2 -0
  19. package/src/providers/google-antigravity/index.ts +11 -0
  20. package/src/providers/google-antigravity/translators.ts +67 -14
  21. package/src/providers/ollama/index.ts +11 -1
  22. package/src/providers/ollama/quota-poll-store.ts +22 -1
  23. package/src/providers/ollama/quota.ts +95 -23
  24. package/src/providers/openai-codex/catalog.ts +9 -4
  25. package/src/providers/openai-codex/index.ts +18 -2
  26. package/src/providers/opencode-zen/index.ts +11 -2
  27. package/src/proxy.ts +143 -28
  28. package/src/rotator.ts +296 -21
  29. package/src/settings-repository.ts +36 -5
  30. package/src/types.ts +72 -26
  31. package/src/validators.ts +37 -1
  32. package/src/web/app.tsx +6 -1
  33. package/src/web/components/icons.tsx +29 -0
  34. package/src/web/components/overlays.tsx +13 -1
  35. package/src/web/components/ui.tsx +6 -1
  36. package/src/web/lib/accounts.ts +1 -0
  37. package/src/web/lib/attention.ts +12 -0
  38. package/src/web/lib/effort.ts +407 -0
  39. package/src/web/lib/models.ts +284 -0
  40. package/src/web/lib/pools.ts +53 -9
  41. package/src/web/lib/status.ts +13 -3
  42. package/src/web/nav.ts +1 -0
  43. package/src/web/pages/AccountDetail.tsx +16 -2
  44. package/src/web/pages/EffortRouting.tsx +1130 -0
  45. package/src/web/pages/Models.tsx +888 -0
  46. package/src/web/pages/Overview.tsx +31 -15
  47. package/src/web/pages/Usage.tsx +3 -3
  48. package/src/web/state/api.ts +31 -0
  49. package/src/web/state/model-catalog.ts +103 -0
  50. package/src/web/state/router.ts +150 -19
  51. package/src/web/state/store.ts +6 -6
  52. package/src/web/styles/app.css +854 -0
package/src/rotator.ts CHANGED
@@ -60,10 +60,26 @@ import {
60
60
  primaryProviderId,
61
61
  findProviderForModel,
62
62
  getProviderIdForPoolKey,
63
+ isKnownProvider,
63
64
  isOllamaQuotaPoolKey,
64
65
  PROVIDER_ORDER,
65
66
  } from "./providers/registry.js";
66
67
  import type { QuotaFetchContext } from "./providers/adapter.js";
68
+ import {
69
+ isProviderModelOff,
70
+ isProviderTurnedOff,
71
+ listCatalogModels,
72
+ parseModelKey,
73
+ resolveProviderOrder,
74
+ routedProviderId,
75
+ setAutoEnableNewModels as autoEnablePatch,
76
+ setModelsTurnedOff,
77
+ setProviderTurnedOff,
78
+ type CatalogModel,
79
+ } from "./model-catalog.js";
80
+ import { getModelCatalogRevision } from "./model-catalog-revision.js";
81
+ import { applyConfigOverrides } from "./config-overrides.js";
82
+ import { planEffortRouteDelete, planEffortRouteSave, type EffortRoutePlan } from "./effort-routing.js";
67
83
  import { logger } from "./logger.js";
68
84
  import { getAccountProxyDispatcher } from "./providers/proxy-dispatcher.js";
69
85
  import {
@@ -71,6 +87,8 @@ import {
71
87
  getCodexModels,
72
88
  isCodexRequestModel,
73
89
  isCodexProviderModelId,
90
+ setDiscoveredCodexModels,
91
+ type CodexModel,
74
92
  } from "./providers/openai-codex/catalog.js";
75
93
  import { CodexOAuthError } from "./providers/openai-codex/oauth.js";
76
94
  import { CODEX_QUOTA_MODEL_KEY } from "./providers/openai-codex/quota.js";
@@ -269,6 +287,8 @@ export class AccountRotator {
269
287
  private codexModels = new Set<string>(getCodexModels().map((model) => model.id));
270
288
  private readonly usagePredictor = new UsagePredictor();
271
289
  private lastOllamaCatalogFetch = 0;
290
+ private lastCodexCatalogFetch = 0;
291
+ private codexCatalogFetch: Promise<void> | null = null;
272
292
 
273
293
  setOllamaModels(models: string[]): void {
274
294
  this.ollamaModels = new Set(models.map((m) => m.trim()).filter(Boolean));
@@ -280,11 +300,21 @@ export class AccountRotator {
280
300
  }
281
301
 
282
302
  hasActiveProvider(providerId: string): boolean {
303
+ if (isProviderTurnedOff(this.config, providerId)) return false;
283
304
  return this.accounts.some(
284
305
  (account) =>
285
306
  !account.disabled &&
286
307
  !account.flagged &&
287
- hasCredential(account.config, providerId),
308
+ hasCredential(account.config, providerId) &&
309
+ !account.disabledProviders?.includes(providerId),
310
+ );
311
+ }
312
+
313
+ /** Turned off on the Models page, for every account or for this one. */
314
+ isProviderOffForAccount(account: AccountRuntime, providerId: string): boolean {
315
+ return (
316
+ isProviderTurnedOff(this.config, providerId) ||
317
+ (account.disabledProviders?.includes(providerId) ?? false)
288
318
  );
289
319
  }
290
320
 
@@ -345,18 +375,49 @@ export class AccountRotator {
345
375
  return [...this.codexModels];
346
376
  }
347
377
 
348
- async primeCodexCatalog(): Promise<void> {
349
- const account = this.accounts.find(
350
- (candidate) => hasCredential(candidate.config, "openai-codex") && !candidate.disabled && !candidate.flagged,
378
+ primeCodexCatalog(): Promise<void> {
379
+ return this.refreshCodexCatalogOnce(true);
380
+ }
381
+
382
+ private refreshCodexCatalogOnce(force = false): Promise<void> {
383
+ if (this.codexCatalogFetch) return this.codexCatalogFetch;
384
+ const now = Date.now();
385
+ if (!force && now - this.lastCodexCatalogFetch < TAGS_CACHE_TTL_MS) return Promise.resolve();
386
+ const accounts = this.accounts.filter(
387
+ (candidate) => hasCredential(candidate.config, "openai-codex") &&
388
+ !candidate.disabled && !candidate.flagged &&
389
+ !candidate.invalidProviders?.["openai-codex"] &&
390
+ !this.isProviderOffForAccount(candidate, "openai-codex"),
351
391
  );
352
- if (!account) return;
353
- try {
354
- await this.ensureValidTokenForProvider(account, "openai-codex");
355
- const models = await fetchCodexCatalog(account);
356
- this.setCodexModels(models.map((model) => model.id));
357
- } catch {
358
- // The verified base allowlist stays active when discovery is unavailable.
359
- }
392
+ if (accounts.length === 0) return Promise.resolve();
393
+ this.lastCodexCatalogFetch = now;
394
+ this.codexCatalogFetch = (async () => {
395
+ const merged = new Map<string, CodexModel>();
396
+ // Plans expose different catalogs. Query all eligible accounts, limiting
397
+ // concurrency so a large pool does not burst token refreshes or discovery.
398
+ for (let offset = 0; offset < accounts.length; offset += 4) {
399
+ const results = await Promise.allSettled(accounts.slice(offset, offset + 4).map(async (account) => {
400
+ await this.ensureValidTokenForProvider(account, "openai-codex");
401
+ return fetchCodexCatalog(account);
402
+ }));
403
+ for (const result of results) {
404
+ if (result.status !== "fulfilled") continue;
405
+ for (const model of result.value) {
406
+ // A restricted account's base fallback must not overwrite metadata
407
+ // discovered through another account with access to the model.
408
+ if (model.source === "discovered" || !merged.has(model.id)) merged.set(model.id, model);
409
+ }
410
+ }
411
+ }
412
+ if (merged.size > 0) {
413
+ const models = [...merged.values()];
414
+ setDiscoveredCodexModels(models.filter((model) => model.source === "discovered"));
415
+ this.setCodexModels(models.map((model) => model.id));
416
+ }
417
+ })().finally(() => {
418
+ this.codexCatalogFetch = null;
419
+ });
420
+ return this.codexCatalogFetch;
360
421
  }
361
422
 
362
423
  /** Fetch the Ollama Cloud catalog once at startup so provider-aware routing and /v1/models work before the first quota poll. */
@@ -624,6 +685,11 @@ export class AccountRotator {
624
685
  this.provider429Events = state.safety?.provider429Events ?? [];
625
686
  this.rollDailySafetyIfNeeded(Date.now());
626
687
 
688
+ const emailCounts = new Map<string, number>();
689
+ for (const account of this.accounts) {
690
+ const email = account.config.email;
691
+ emailCounts.set(email, (emailCounts.get(email) ?? 0) + 1);
692
+ }
627
693
  for (const account of this.accounts) {
628
694
  const saved = state.accounts[account.config.email];
629
695
  if (saved) {
@@ -645,6 +711,13 @@ export class AccountRotator {
645
711
  account.allowFreshWindowStartsOverride =
646
712
  saved.allowFreshWindowStartsOverride ?? false;
647
713
  }
714
+ // A legacy email switch cannot identify one of several project/workspace
715
+ // accounts. New state is authoritative so changed identities do not
716
+ // inherit switches from an older credential with the same email.
717
+ const disabledProviders = state.disabledProvidersByAccount
718
+ ? state.disabledProvidersByAccount[getAccountIdentity(account)]
719
+ : emailCounts.get(account.config.email) === 1 ? saved?.disabledProviders : undefined;
720
+ if (disabledProviders?.length) account.disabledProviders = [...disabledProviders];
648
721
  }
649
722
  this.migratePersistedQuotaStateKeys();
650
723
  // Cap explicit generic/non-Google cooldowns to 30 min. An unresolved key
@@ -763,6 +836,7 @@ export class AccountRotator {
763
836
  }
764
837
  }
765
838
 
839
+ const disabledProvidersByAccount: Record<string, string[]> = {};
766
840
  const state: PersistedState = {
767
841
  dynamicModelQuotaPools: dynamicCatalog.getDiscoveredQuotaPools(),
768
842
  dynamicModelOwnership: dynamicCatalog.getPersistedModelOwnership(
@@ -795,9 +869,11 @@ export class AccountRotator {
795
869
  modelBreakers: { ...this.modelBreakers },
796
870
  provider429Events: [...this.provider429Events],
797
871
  },
872
+ disabledProvidersByAccount,
798
873
  accounts: {},
799
874
  };
800
875
  for (const account of this.accounts) {
876
+ disabledProvidersByAccount[getAccountIdentity(account)] = [...(account.disabledProviders ?? [])];
801
877
  state.accounts[account.config.email] = {
802
878
  totalRequests: account.totalRequests,
803
879
  dailyRequestCount: account.dailyRequestCount,
@@ -1021,6 +1097,7 @@ export class AccountRotator {
1021
1097
 
1022
1098
  private async pollAllQuotasOnce(): Promise<void> {
1023
1099
  void this.refreshOllamaCatalogOnce().catch(() => {});
1100
+ void this.refreshCodexCatalogOnce().catch(() => {});
1024
1101
 
1025
1102
  const available = this.accounts.filter((a) => !a.disabled && !a.flagged);
1026
1103
  this.reconcileDynamicCatalog();
@@ -1131,6 +1208,12 @@ export class AccountRotator {
1131
1208
  : quotaKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
1132
1209
  ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
1133
1210
  : undefined);
1211
+ if (!q && quotaKey === "monthly") {
1212
+ // Legacy subscriptions still report explicit session/weekly windows on
1213
+ // /api/balance; both windows constrain the same Ollama account.
1214
+ const windows = account.quota.filter((quota) => quota.modelKey === "session" || quota.modelKey === "weekly");
1215
+ if (windows.length > 0) return Math.min(...windows.map((quota) => quota.percentRemaining));
1216
+ }
1134
1217
  if (!q) return -1;
1135
1218
  // Legacy Ollama state used a session pool gated by a weekly pool. Keep
1136
1219
  // that compatibility rule only for old in-memory state; current Ollama
@@ -1139,6 +1222,12 @@ export class AccountRotator {
1139
1222
  const weekly = account.quota.find((w) => w.modelKey === "weekly");
1140
1223
  if (weekly && weekly.percentRemaining === 0) return 0;
1141
1224
  }
1225
+ // Included monthly credits can be exhausted while prepaid credits still work.
1226
+ // Keep the actual included percentage in status; use a positive eligibility
1227
+ // floor for routing while the provider reports spendable purchased credit.
1228
+ if (q.modelKey === "monthly" && (q.credits?.purchasedUsd ?? 0) > 0) {
1229
+ return Math.max(1, q.percentRemaining);
1230
+ }
1142
1231
  return q.percentRemaining;
1143
1232
  }
1144
1233
 
@@ -1539,6 +1628,10 @@ export class AccountRotator {
1539
1628
  (account.cooldownsByModel.__default__ ?? 0) > now;
1540
1629
  if (account.flagged) return "flagged";
1541
1630
  if (account.disabled) return "disabled";
1631
+ const providers = (account.config.credentials ?? []).map((credential) => credential.provider);
1632
+ if (providers.length > 0 && providers.every((id) => this.isProviderOffForAccount(account, id))) {
1633
+ return "off";
1634
+ }
1542
1635
  if (account.consecutiveErrors > 0 && !account.disabled) return "error";
1543
1636
  // Pool cooldowns stay visible in cooldownsByModel but must not make the
1544
1637
  // whole account unavailable for unrelated quota pools.
@@ -1871,6 +1964,7 @@ export class AccountRotator {
1871
1964
  );
1872
1965
 
1873
1966
  diagnostics.push({
1967
+ id: getAccountIdentity(account),
1874
1968
  email: account.config.email,
1875
1969
  label: account.config.label || account.config.email,
1876
1970
  status,
@@ -3412,6 +3506,127 @@ export class AccountRotator {
3412
3506
  return true;
3413
3507
  }
3414
3508
 
3509
+ // ── Models page ─────────────────────────────────────────────────────────
3510
+
3511
+ /** Every provider's models, in provider order, with whether each is served. */
3512
+ getModelCatalog(): CatalogModel[] {
3513
+ return listCatalogModels(this);
3514
+ }
3515
+
3516
+ async setProviderEnabled(providerId: string, enabled: boolean): Promise<boolean> {
3517
+ if (!isKnownProvider(providerId)) return false;
3518
+ if (await this.updateModelSettings(setProviderTurnedOff(this.config, providerId, !enabled))) {
3519
+ this.log(
3520
+ `Operator turned ${getProviderAdapter(providerId).displayName} ${enabled ? "on" : "off"}`,
3521
+ "warn",
3522
+ );
3523
+ }
3524
+ return true;
3525
+ }
3526
+
3527
+ async setProviderOrder(order: string[]): Promise<boolean> {
3528
+ if (!order.every(isKnownProvider)) return false;
3529
+ const next = resolveProviderOrder(order);
3530
+ if (await this.updateModelSettings({ providerOrder: next })) {
3531
+ this.log(`Operator set the provider order: ${next.join(", ")}`);
3532
+ }
3533
+ return true;
3534
+ }
3535
+
3536
+ /** Keys are "<provider>/<model>". */
3537
+ async setModelsEnabled(keys: string[], enabled: boolean): Promise<boolean> {
3538
+ if (keys.length === 0 || !keys.every((key) => parseModelKey(key))) return false;
3539
+ if (await this.updateModelSettings(setModelsTurnedOff(this.config, keys, !enabled))) {
3540
+ this.log(`Operator turned ${enabled ? "on" : "off"} ${keys.join(", ")}`, "warn");
3541
+ }
3542
+ return true;
3543
+ }
3544
+
3545
+ async setAutoEnableNewModels(enabled: boolean): Promise<void> {
3546
+ // The review snapshot records what providers list now; load the live
3547
+ // lists first so a provider whose list has not loaded is not held back.
3548
+ if (!enabled && this.config.autoEnableNewModels !== false) {
3549
+ await this.refreshModelCatalogs();
3550
+ }
3551
+ if (await this.updateModelSettings(autoEnablePatch(this, enabled))) {
3552
+ this.log(
3553
+ enabled
3554
+ ? "Operator set new models to turn on automatically"
3555
+ : "Operator set new models to stay off until reviewed",
3556
+ );
3557
+ }
3558
+ }
3559
+
3560
+ /** Exact identity target; a legacy email is accepted only if it names one account. */
3561
+ async setAccountProviderEnabled(
3562
+ accountId: string,
3563
+ providerId: string,
3564
+ enabled: boolean,
3565
+ ): Promise<boolean> {
3566
+ let matches = this.accounts.filter((a) => getAccountIdentity(a) === accountId);
3567
+ if (matches.length === 0) matches = this.accounts.filter((a) => a.config.email === accountId);
3568
+ if (matches.length !== 1) return false;
3569
+ const account = matches[0];
3570
+ if (!hasCredential(account.config, providerId)) return false;
3571
+ const current = account.disabledProviders ?? [];
3572
+ if (current.includes(providerId) === !enabled) return true;
3573
+ const rest = current.filter((id) => id !== providerId);
3574
+ const next = enabled ? rest : [...rest, providerId];
3575
+ account.disabledProviders = next.length > 0 ? next : undefined;
3576
+ await this.saveState();
3577
+ this.log(
3578
+ `${account.config.email}: operator turned ${getProviderAdapter(providerId).displayName} ${enabled ? "on" : "off"} for this account`,
3579
+ "warn",
3580
+ );
3581
+ this.requestWaiterDrain();
3582
+ return true;
3583
+ }
3584
+
3585
+ /**
3586
+ * Create (`previousAlias` null), replace or rename an effort route from a
3587
+ * dashboard request body. Saved routes apply to new requests right away.
3588
+ */
3589
+ async saveEffortRoute(previousAlias: string | null, body: unknown): Promise<EffortRoutePlan> {
3590
+ const plan = planEffortRouteSave(this, previousAlias, body);
3591
+ if (plan.ok && (await this.updateModelSettings(plan.patch))) {
3592
+ applyConfigOverrides(this.config);
3593
+ this.log(
3594
+ previousAlias === null
3595
+ ? `Operator created effort model ${plan.alias}`
3596
+ : `Operator updated effort model ${previousAlias}${previousAlias === plan.alias ? "" : ` as ${plan.alias}`}`,
3597
+ "warn",
3598
+ );
3599
+ }
3600
+ return plan;
3601
+ }
3602
+
3603
+ async deleteEffortRoute(alias: string): Promise<EffortRoutePlan> {
3604
+ const plan = planEffortRouteDelete(this.config, alias);
3605
+ if (plan.ok && (await this.updateModelSettings(plan.patch))) {
3606
+ applyConfigOverrides(this.config);
3607
+ this.log(`Operator deleted effort model ${plan.alias}`, "warn");
3608
+ }
3609
+ return plan;
3610
+ }
3611
+
3612
+ /** Re-read the Ollama and Codex model lists now instead of on the next poll. */
3613
+ async refreshModelCatalogs(): Promise<void> {
3614
+ this.lastOllamaCatalogFetch = 0;
3615
+ await Promise.all([this.refreshOllamaCatalogOnce(), this.primeCodexCatalog()]);
3616
+ }
3617
+
3618
+ /** Applies a settings patch; returns false (and saves nothing) when nothing changes. */
3619
+ private async updateModelSettings(patch: Partial<Config>): Promise<boolean> {
3620
+ const changed = (Object.keys(patch) as Array<keyof Config>).some(
3621
+ (key) => JSON.stringify(patch[key]) !== JSON.stringify(this.config[key]),
3622
+ );
3623
+ if (!changed) return false;
3624
+ this.config = { ...this.config, ...patch };
3625
+ await saveAccountsConfig(this.config);
3626
+ this.requestWaiterDrain();
3627
+ return true;
3628
+ }
3629
+
3415
3630
  async setAutoWarmup(enabled: boolean): Promise<boolean> {
3416
3631
  if (this.autoWarmupEnabled === enabled) return false;
3417
3632
  this.autoWarmupEnabled = enabled;
@@ -3680,6 +3895,7 @@ export class AccountRotator {
3680
3895
  if (!this.isAvailable(account, now)) return false;
3681
3896
  const providerId = getProviderIdForPoolKey(modelKey);
3682
3897
  if (account.invalidProviders?.[providerId]) return false;
3898
+ if (this.isProviderOffForAccount(account, providerId)) return false;
3683
3899
  if ((account.providerCooldowns?.[providerId] ?? 0) > now) return false;
3684
3900
  const modelCooldown =
3685
3901
  account.cooldownsByModel[this.resolveQuotaStateKey(modelKey)] ?? 0;
@@ -3793,6 +4009,18 @@ export class AccountRotator {
3793
4009
  detail: `${providerId} credential is invalid; re-authentication required`,
3794
4010
  };
3795
4011
  }
4012
+ if (isProviderTurnedOff(this.config, providerId)) {
4013
+ return {
4014
+ reason: "provider-ineligible",
4015
+ detail: `${getProviderAdapter(providerId).displayName} is turned off on the Models page`,
4016
+ };
4017
+ }
4018
+ if (account.disabledProviders?.includes(providerId)) {
4019
+ return {
4020
+ reason: "provider-ineligible",
4021
+ detail: `${getProviderAdapter(providerId).displayName} is turned off for this account`,
4022
+ };
4023
+ }
3796
4024
  if (
3797
4025
  providerId === "openai-codex" &&
3798
4026
  !getProviderAdapter(providerId).hasValidCredentials(account)
@@ -3827,19 +4055,25 @@ export class AccountRotator {
3827
4055
 
3828
4056
  private resolvePoolKeyForModel(model: string, providerId?: string): string | null {
3829
4057
  const normalizedModel = model.trim().toLowerCase();
3830
- if (
3831
- !isStaticAntigravityModel(model) &&
3832
- dynamicCatalog.wasDiscovered(model)
3833
- ) return normalizedModel;
3834
- if (this.hasRelevantQuotaStateForModel(normalizedModel, Date.now())) {
3835
- return normalizedModel;
4058
+ // Decide the provider first: the Google pool shortcuts below must not
4059
+ // capture a request that is pinned or routed to another provider.
4060
+ const provider = providerId ?? routedProviderId(this, model);
4061
+ if (!provider || provider === DEFAULT_PROVIDER) {
4062
+ if (
4063
+ !isStaticAntigravityModel(model) &&
4064
+ dynamicCatalog.wasDiscovered(model)
4065
+ ) return normalizedModel;
4066
+ if (this.hasRelevantQuotaStateForModel(normalizedModel, Date.now())) {
4067
+ return normalizedModel;
4068
+ }
3836
4069
  }
3837
4070
  const context = {
3838
4071
  ollamaModels: this.ollamaModels,
3839
4072
  codexModels: this.codexModels,
3840
- providerId,
3841
4073
  };
3842
- const adapter = findProviderForModel(model, context);
4074
+ const adapter = provider
4075
+ ? getProviderAdapter(provider)
4076
+ : findProviderForModel(model, context);
3843
4077
  if (adapter?.getPoolKey) {
3844
4078
  return adapter.getPoolKey(model);
3845
4079
  }
@@ -3936,7 +4170,8 @@ export class AccountRotator {
3936
4170
  const candidateProviderId = providerId ?? getProviderIdForPoolKey(modelKey);
3937
4171
  if (
3938
4172
  !hasCredential(account.config, candidateProviderId) ||
3939
- account.invalidProviders?.[candidateProviderId]
4173
+ account.invalidProviders?.[candidateProviderId] ||
4174
+ this.isProviderOffForAccount(account, candidateProviderId)
3940
4175
  ) {
3941
4176
  continue;
3942
4177
  }
@@ -4010,6 +4245,7 @@ export class AccountRotator {
4010
4245
  const tokenBucket = this.getTokenBucketSnapshot(a, now);
4011
4246
 
4012
4247
  return {
4248
+ id: getAccountIdentity(a),
4013
4249
  email: a.config.email,
4014
4250
  provider:
4015
4251
  (a.config.credentials ?? []).map((c) => c.provider).join("+") ||
@@ -4033,6 +4269,9 @@ export class AccountRotator {
4033
4269
  hasValidToken: !!(a.accessToken && a.tokenExpires > now),
4034
4270
  invalidProviders: a.invalidProviders,
4035
4271
  providerCooldowns: a.providerCooldowns,
4272
+ ...(a.disabledProviders?.length
4273
+ ? { disabledProviders: [...a.disabledProviders] }
4274
+ : {}),
4036
4275
  quota: a.quota,
4037
4276
  inFlightRequests: a.inFlightRequests,
4038
4277
  inFlightByModel: a.inFlightByModel,
@@ -4139,6 +4378,7 @@ export class AccountRotator {
4139
4378
  hostedOAuthConfigured: isHostedOAuthConfigured(),
4140
4379
  ollamaModels: this.getOllamaModels(),
4141
4380
  codexModels: this.getCodexModels(),
4381
+ modelCatalogRevision: getModelCatalogRevision(this),
4142
4382
  modelTierAccess: this.accounts.some((a) =>
4143
4383
  hasCredential(a.config, "ollama"),
4144
4384
  )
@@ -4247,6 +4487,7 @@ export class AccountRotator {
4247
4487
  const mergedAccounts = normalized.accounts.map(matchAndReuseAccount);
4248
4488
  this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
4249
4489
  this.accounts = mergedAccounts;
4490
+ applyConfigOverrides(this.config);
4250
4491
  this.reconcileDynamicCatalog();
4251
4492
  this.requestWaiterDrain();
4252
4493
  await saveAccountsConfig(this.config);
@@ -4302,6 +4543,9 @@ export class AccountRotator {
4302
4543
  }
4303
4544
 
4304
4545
  async addOrUpdateAccount(accountConfig: AccountConfig): Promise<void> {
4546
+ const receivesCodexCredential = accountConfig.credentials?.some(
4547
+ (credential) => credential.provider === "openai-codex",
4548
+ );
4305
4549
  const existingIndex = this.accounts.findIndex(
4306
4550
  (account) => account.config.email === accountConfig.email,
4307
4551
  );
@@ -4319,6 +4563,20 @@ export class AccountRotator {
4319
4563
  existing.consecutiveErrors = 0;
4320
4564
  existing.accessToken = null;
4321
4565
  existing.tokenExpires = 0;
4566
+ if (receivesCodexCredential) {
4567
+ if (existing.invalidProviders) {
4568
+ delete existing.invalidProviders["openai-codex"];
4569
+ if (Object.keys(existing.invalidProviders).length === 0) {
4570
+ delete existing.invalidProviders;
4571
+ }
4572
+ }
4573
+ if (existing.providerTokens) {
4574
+ delete existing.providerTokens["openai-codex"];
4575
+ if (Object.keys(existing.providerTokens).length === 0) {
4576
+ delete existing.providerTokens;
4577
+ }
4578
+ }
4579
+ }
4322
4580
  this.config.accounts[existingIndex] = existing.config;
4323
4581
  this.log(`${accountConfig.email}: account updated via hosted login`);
4324
4582
  } else {
@@ -4454,6 +4712,7 @@ export class AccountRotator {
4454
4712
  return this.accounts.find((a) => a.config.email === email);
4455
4713
  }
4456
4714
 
4715
+ /** In-service accounts; benchmarkAccount skips providers turned off on the Models page. */
4457
4716
  public getBenchmarkAccounts(): AccountRuntime[] {
4458
4717
  return this.accounts.filter((account) => !account.disabled && !account.flagged);
4459
4718
  }
@@ -4689,6 +4948,22 @@ export class AccountRotator {
4689
4948
  error: "quota pool has no configured kickstart provider",
4690
4949
  };
4691
4950
  }
4951
+ if (this.isProviderOffForAccount(account, target.providerId)) {
4952
+ return {
4953
+ ok: false,
4954
+ status: 409,
4955
+ upstreamModel: "",
4956
+ error: "provider turned off on the Models page",
4957
+ };
4958
+ }
4959
+ if (isProviderModelOff(this, target.providerId, target.upstreamModel)) {
4960
+ return {
4961
+ ok: false,
4962
+ status: 409,
4963
+ upstreamModel: target.upstreamModel,
4964
+ error: "kickstart model turned off on the Models page",
4965
+ };
4966
+ }
4692
4967
 
4693
4968
  const denialKey = `${email}\0${target.upstreamModel}`;
4694
4969
  if ((this.kickstartDeniedUntil.get(denialKey) ?? 0) > Date.now()) {
@@ -25,6 +25,26 @@ const { Pool } = pg;
25
25
  * JSON-serialized objects). Both implementations guarantee that `get()`
26
26
  * always returns the latest value set via `set()` (in-process consistency).
27
27
  */
28
+ /**
29
+ * Runs writes for one key one at a time. Each write persists the newest cached
30
+ * value when it runs, so an older write can never land after a newer one (for
31
+ * example two quick toggles whose disk backups finish out of order).
32
+ */
33
+ class KeyedWriteQueue {
34
+ private tails = new Map<string, Promise<void>>();
35
+
36
+ run(key: string, write: () => Promise<void>): Promise<void> {
37
+ const previous = this.tails.get(key) ?? Promise.resolve();
38
+ const next = previous.then(write);
39
+ const tail = next.catch(() => {});
40
+ this.tails.set(key, tail);
41
+ void tail.then(() => {
42
+ if (this.tails.get(key) === tail) this.tails.delete(key);
43
+ });
44
+ return next;
45
+ }
46
+ }
47
+
28
48
  export interface ISettingsRepository {
29
49
  /** Initialize the repository (create table / load from disk) */
30
50
  init(): Promise<void>;
@@ -89,6 +109,7 @@ interface PendingWrite {
89
109
  export class PostgresSettingsRepository implements ISettingsRepository {
90
110
  private pool: pg.Pool | null = null;
91
111
  private cache = new Map<string, string>();
112
+ private writes = new KeyedWriteQueue();
92
113
  private initialized = false;
93
114
  private pendingRetries = new Map<string, PendingWrite>();
94
115
  private retryTimer: ReturnType<typeof setTimeout> | null = null;
@@ -174,23 +195,27 @@ export class PostgresSettingsRepository implements ISettingsRepository {
174
195
 
175
196
  async set(key: string, value: string): Promise<void> {
176
197
  this.cache.set(key, value);
177
- if (this.pool) {
198
+ if (!this.pool) return;
199
+ await this.writes.run(key, async () => {
200
+ const pool = this.pool;
201
+ const latest = this.cache.get(key) ?? value;
202
+ if (!pool) return;
178
203
  try {
179
204
  // Account changes must be durable before the API reports success.
180
205
  // A background-only write could be lost when the service restarts.
181
- await this.pool.query(
206
+ await pool.query(
182
207
  `INSERT INTO rotator_settings (key, value, updated_at)
183
208
  VALUES ($1, $2, CURRENT_TIMESTAMP)
184
209
  ON CONFLICT (key) DO UPDATE
185
210
  SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP`,
186
- [key, value],
211
+ [key, latest],
187
212
  );
188
213
  } catch (err) {
189
214
  console.error(`Failed to save ${key} to database: ${err}`);
190
- this.enqueueRetry(key, value);
215
+ this.enqueueRetry(key, latest);
191
216
  throw err;
192
217
  }
193
- }
218
+ });
194
219
  }
195
220
 
196
221
  private enqueueRetry(key: string, value: string): void {
@@ -274,6 +299,7 @@ export class PostgresSettingsRepository implements ISettingsRepository {
274
299
 
275
300
  export class FileSettingsRepository implements ISettingsRepository {
276
301
  private cache = new Map<string, string>();
302
+ private writes = new KeyedWriteQueue();
277
303
 
278
304
  async init(): Promise<void> {
279
305
  // Pre-load all known keys from their disk files into cache
@@ -299,7 +325,12 @@ export class FileSettingsRepository implements ISettingsRepository {
299
325
  // Persist to disk
300
326
  const path = diskPath(key);
301
327
  if (!path) return;
328
+ await this.writes.run(key, () => this.writeToDisk(key, path));
329
+ }
302
330
 
331
+ private async writeToDisk(key: string, path: string): Promise<void> {
332
+ const value = this.cache.get(key);
333
+ if (value === undefined) return;
303
334
  const spec = DISK_FILES[key];
304
335
  try {
305
336
  if (spec?.backup) {