tuxevil-rotator 3.4.0 → 3.6.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.
package/src/rotator.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { createHash } from "node:crypto";
2
1
  import {
3
2
  type AccountConfig,
4
3
  type AccountRuntime,
@@ -9,7 +8,6 @@ import {
9
8
  type ModelQuota,
10
9
  type ModelRotationState,
11
10
  type PersistedState,
12
- type ProviderCredential,
13
11
  type RoutingAccountDiagnostic,
14
12
  type RoutingModelDiagnostics,
15
13
  type RoutingRejectionReason,
@@ -17,8 +15,8 @@ import {
17
15
  type TokenBucket,
18
16
  type TokenUsageData,
19
17
  type TokenUsageTiered,
20
- MODEL_PRICING,
21
18
  MODEL_TIER_ACCESS,
19
+ getModelPricing,
22
20
  QUOTA_USER_AGENT,
23
21
  REQUEST_GOOG_API_CLIENT,
24
22
  REQUEST_CLIENT_METADATA,
@@ -29,9 +27,11 @@ import {
29
27
  DEFAULT_QUOTA_POLL_INTERVAL_MS,
30
28
  MAX_QUOTA_POLL_INTERVAL_MS,
31
29
  MIN_QUOTA_POLL_INTERVAL_MS,
30
+ isStaticAntigravityModel,
32
31
  resolveQuotaModelKey,
33
32
  resolveDisplayModelKey,
34
33
  } from "./types.js";
34
+ import { dynamicCatalog } from "./providers/google-antigravity/dynamic-catalog.js";
35
35
  import {
36
36
  reportFlagEvent,
37
37
  FLAG_PATTERNS,
@@ -88,59 +88,18 @@ import {
88
88
  parseRetryAfterMs,
89
89
  RESOURCE_EXHAUSTED_FALLBACK_MS,
90
90
  } from "./rate-limit-parser.js";
91
-
92
- function credentialFingerprint(secret?: string): string {
93
- if (!secret) return "";
94
- // SHA-256 is intentional: this is a non-secret deduplication fingerprint, not a
95
- // password hash. It must be deterministic and fast (bcrypt/argon2 would be wrong here).
96
- // codeql[js/insufficient-password-hash]
97
- return createHash("sha256").update(secret).digest("hex").slice(0, 12);
98
- }
99
-
100
- export function getProviderCredentialDetails(
101
- norm: AccountConfig,
102
- cred?: ProviderCredential,
103
- ): {
104
- provider: string;
105
- projectId: string;
106
- providerAccountId: string;
107
- secret: string;
108
- fingerprint: string;
109
- } {
110
- const provider = cred?.provider ?? DEFAULT_PROVIDER;
111
- const projectId = getProviderProjectId(norm, provider);
112
- let providerAccountId = cred?.providerAccountId || "";
113
- let secret = cred?.refreshToken || cred?.apiKey || "";
114
-
115
- if (provider === "google-antigravity") {
116
- secret ||= norm.refreshToken || norm.apiKey || "";
117
- } else if (provider === "openai-codex") {
118
- providerAccountId ||= norm.codexAccountId || "";
119
- secret ||= norm.codexRefreshToken || "";
120
- }
121
-
122
- const fingerprint = !projectId && !providerAccountId && secret ? credentialFingerprint(secret) : "";
123
- return { provider, projectId, providerAccountId, secret, fingerprint };
124
- }
125
-
126
- export function getAccountIdentity(account: AccountConfig | AccountRuntime): string {
127
- const config = "config" in account ? account.config : account;
128
- const norm = normalizeAccountConfig(config);
129
- const email = norm.email.toLowerCase().trim();
130
- const creds = (norm.credentials ?? [])
131
- .slice()
132
- .sort((a, b) => a.provider.localeCompare(b.provider))
133
- .map((c) => {
134
- const details = getProviderCredentialDetails(norm, c);
135
- return `${details.provider}:${details.projectId}:${details.providerAccountId}:${details.fingerprint}`;
136
- })
137
- .join("|");
138
- if (!creds) {
139
- const details = getProviderCredentialDetails(norm, { provider: DEFAULT_PROVIDER });
140
- return `${email}#${details.provider}:${details.projectId}:${details.providerAccountId}:${details.fingerprint}`;
141
- }
142
- return `${email}#${creds}`;
143
- }
91
+ import {
92
+ getAccountIdentity,
93
+ getCredentialGeneration,
94
+ getCredentialGenerationFingerprint,
95
+ getProviderCredentialDetails,
96
+ } from "./account-identity.js";
97
+
98
+ export {
99
+ getAccountIdentity,
100
+ getCredentialGeneration,
101
+ getProviderCredentialDetails,
102
+ } from "./account-identity.js";
144
103
 
145
104
  export function areAccountIdentitiesCompatible(
146
105
  incomingConfig: AccountConfig,
@@ -198,18 +157,6 @@ export function areAccountIdentitiesCompatible(
198
157
  return true;
199
158
  }
200
159
 
201
- export function getCredentialGeneration(
202
- account: AccountRuntime | AccountConfig,
203
- providerId: string,
204
- ): string {
205
- const config = "config" in account ? account.config : account;
206
- const norm = normalizeAccountConfig(config);
207
- const cred = norm.credentials?.find((c) => c.provider === providerId);
208
- const details = getProviderCredentialDetails(norm, cred ?? { provider: providerId });
209
- if (!cred && !details.secret) return "none";
210
- return `${providerId}:${details.projectId}:${details.providerAccountId}:${details.secret}`;
211
- }
212
-
213
160
  const rotatorLogger = logger.child("rotator");
214
161
 
215
162
  function currentUtcDay(now = Date.now()): string {
@@ -403,9 +350,27 @@ export class AccountRotator {
403
350
  this.config = applyConfigDefaults(config);
404
351
  this.initAccounts();
405
352
  this.loadState();
353
+ this.reconcileDynamicCatalog();
406
354
  this.startQuotaPolling();
407
355
  }
408
356
 
357
+ private reconcileDynamicCatalog(): void {
358
+ dynamicCatalog.retainAccounts(
359
+ this.accounts
360
+ .filter(
361
+ (account) =>
362
+ !account.disabled &&
363
+ !account.flagged &&
364
+ !account.invalidProviders?.[DEFAULT_PROVIDER] &&
365
+ hasCredential(account.config, DEFAULT_PROVIDER),
366
+ )
367
+ .map((account) => ({
368
+ id: getAccountIdentity(account),
369
+ generation: getCredentialGeneration(account, DEFAULT_PROVIDER),
370
+ })),
371
+ );
372
+ }
373
+
409
374
  private initAccounts(): void {
410
375
  this.accounts = this.config.accounts.map((config) => ({
411
376
  config,
@@ -529,6 +494,17 @@ export class AccountRotator {
529
494
  }
530
495
 
531
496
  try {
497
+ dynamicCatalog.restoreDiscoveredQuotaPools(state.dynamicModelQuotaPools);
498
+ dynamicCatalog.restorePersistedModelOwnership(
499
+ state.dynamicModelOwnership,
500
+ this.accounts
501
+ .filter((account) => hasCredential(account.config, DEFAULT_PROVIDER))
502
+ .map((account) => ({
503
+ id: getAccountIdentity(account),
504
+ credentialGenerationFingerprint:
505
+ getCredentialGenerationFingerprint(account, DEFAULT_PROVIDER),
506
+ })),
507
+ );
532
508
  // Load per-model account assignments
533
509
  if (state.modelAccounts) {
534
510
  for (const [model, idx] of Object.entries(state.modelAccounts)) {
@@ -585,8 +561,9 @@ export class AccountRotator {
585
561
  saved.allowFreshWindowStartsOverride ?? false;
586
562
  }
587
563
  }
588
- // Cap generic stale cooldowns to 30 min max from now. Antigravity's
589
- // explicit Claude/Gemini reset deadlines must survive restarts intact.
564
+ this.migratePersistedQuotaStateKeys();
565
+ // Cap explicit generic/non-Google cooldowns to 30 min. An unresolved key
566
+ // may be a dynamic Google model, so preserve it until catalog hydration.
590
567
  const maxCooldown = 30 * 60 * 1000;
591
568
  const now = Date.now();
592
569
  for (const account of this.accounts) {
@@ -596,6 +573,8 @@ export class AccountRotator {
596
573
  if (
597
574
  model !== "claude" &&
598
575
  model !== "gemini" &&
576
+ (model === "__default__" ||
577
+ getProviderIdForPoolKey(model) !== DEFAULT_PROVIDER) &&
599
578
  cooldown > now + maxCooldown
600
579
  ) {
601
580
  account.cooldownsByModel[model] = now + maxCooldown;
@@ -609,6 +588,41 @@ export class AccountRotator {
609
588
  this.loadTokenUsage();
610
589
  }
611
590
 
591
+ private migratePersistedQuotaStateKeys(): void {
592
+ const foldDeadlines = (deadlines: Record<string, number>) => {
593
+ const folded: Record<string, number> = {};
594
+ for (const [key, deadline] of Object.entries(deadlines)) {
595
+ const canonical = this.resolveQuotaStateKey(key);
596
+ folded[canonical] = Math.max(folded[canonical] ?? 0, deadline);
597
+ }
598
+ return folded;
599
+ };
600
+
601
+ this.modelBreakers = foldDeadlines(this.modelBreakers);
602
+ const projectBreakers: Record<string, number> = {};
603
+ for (const [key, deadline] of Object.entries(this.projectModelBreakers)) {
604
+ const separator = key.lastIndexOf("::");
605
+ const canonical = separator < 0
606
+ ? key
607
+ : projectModelKey(
608
+ key.slice(0, separator),
609
+ this.resolveQuotaStateKey(key.slice(separator + 2)),
610
+ );
611
+ projectBreakers[canonical] = Math.max(
612
+ projectBreakers[canonical] ?? 0,
613
+ deadline,
614
+ );
615
+ }
616
+ this.projectModelBreakers = projectBreakers;
617
+ this.provider429Events = this.provider429Events.map((event) => ({
618
+ ...event,
619
+ modelKey: this.resolveQuotaStateKey(event.modelKey),
620
+ }));
621
+ for (const account of this.accounts) {
622
+ account.cooldownsByModel = foldDeadlines(account.cooldownsByModel);
623
+ }
624
+ }
625
+
612
626
  private loadTokenUsage(): void {
613
627
  try {
614
628
  const parsed = getCachedTokenUsage() as any;
@@ -665,6 +679,22 @@ export class AccountRotator {
665
679
  }
666
680
 
667
681
  const state: PersistedState = {
682
+ dynamicModelQuotaPools: dynamicCatalog.getDiscoveredQuotaPools(),
683
+ dynamicModelOwnership: dynamicCatalog.getPersistedModelOwnership(
684
+ this.accounts
685
+ .filter(
686
+ (account) =>
687
+ !account.disabled &&
688
+ !account.flagged &&
689
+ !account.invalidProviders?.[DEFAULT_PROVIDER] &&
690
+ hasCredential(account.config, DEFAULT_PROVIDER),
691
+ )
692
+ .map((account) => ({
693
+ id: getAccountIdentity(account),
694
+ credentialGenerationFingerprint:
695
+ getCredentialGenerationFingerprint(account, DEFAULT_PROVIDER),
696
+ })),
697
+ ),
668
698
  modelAccounts,
669
699
  modelRequestCounts,
670
700
  modelStickyAccounts,
@@ -849,6 +879,9 @@ export class AccountRotator {
849
879
  try {
850
880
  await this.ensureValidTokenForProvider(account, pid);
851
881
  await getProviderAdapter(pid).fetchQuota(account, quotaCtx);
882
+ if (pid === DEFAULT_PROVIDER) {
883
+ this.migratePersistedQuotaStateKeys();
884
+ }
852
885
  quotaPublished = true;
853
886
  } catch {
854
887
  // One invalid provider credential must not suppress sibling pools.
@@ -904,6 +937,7 @@ export class AccountRotator {
904
937
  void this.refreshOllamaCatalogOnce().catch(() => {});
905
938
 
906
939
  const available = this.accounts.filter((a) => !a.disabled && !a.flagged);
940
+ this.reconcileDynamicCatalog();
907
941
  let quotaPublished = false;
908
942
  for (const account of available) {
909
943
  if (await this.pollAccountQuota(account)) {
@@ -1000,10 +1034,13 @@ export class AccountRotator {
1000
1034
 
1001
1035
  // Get quota % for a specific model on an account. Returns -1 if no data.
1002
1036
  private getModelQuota(account: AccountRuntime, modelKey: string): number {
1003
- const q = account.quota.find((q) => q.modelKey === modelKey) ??
1004
- (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
1037
+ const quotaKey = isStaticAntigravityModel(modelKey)
1038
+ ? modelKey
1039
+ : dynamicCatalog.resolveQuotaPool(modelKey) ?? modelKey;
1040
+ const q = account.quota.find((q) => q.modelKey === quotaKey) ??
1041
+ (quotaKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
1005
1042
  ? account.quota.find((candidate) => candidate.modelKey === CODEX_QUOTA_MODEL_KEY)
1006
- : modelKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
1043
+ : quotaKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
1007
1044
  ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
1008
1045
  : undefined);
1009
1046
  if (!q) return -1;
@@ -1011,7 +1048,7 @@ export class AccountRotator {
1011
1048
  // quota is fully exhausted (0%), the account cannot accept any requests
1012
1049
  // regardless of how much session quota remains. Treat it as 0 so the
1013
1050
  // account is skipped at all call sites that check `quota === 0`.
1014
- if (modelKey === "session") {
1051
+ if (quotaKey === "session") {
1015
1052
  const weekly = account.quota.find((w) => w.modelKey === "weekly");
1016
1053
  if (weekly && weekly.percentRemaining === 0) return 0;
1017
1054
  }
@@ -1023,10 +1060,13 @@ export class AccountRotator {
1023
1060
  account: AccountRuntime,
1024
1061
  modelKey: string,
1025
1062
  ): "fresh" | "5h" | "7d" {
1026
- const q = account.quota.find((q) => q.modelKey === modelKey) ??
1027
- (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
1063
+ const quotaKey = isStaticAntigravityModel(modelKey)
1064
+ ? modelKey
1065
+ : dynamicCatalog.resolveQuotaPool(modelKey) ?? modelKey;
1066
+ const q = account.quota.find((q) => q.modelKey === quotaKey) ??
1067
+ (quotaKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
1028
1068
  ? account.quota.find((candidate) => candidate.modelKey === CODEX_QUOTA_MODEL_KEY)
1029
- : modelKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
1069
+ : quotaKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
1030
1070
  ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
1031
1071
  : undefined);
1032
1072
  return q?.timerType ?? "fresh";
@@ -1379,9 +1419,10 @@ export class AccountRotator {
1379
1419
  ignoreConcurrency = false,
1380
1420
  ): string | null {
1381
1421
  const projectId = this.getProjectIdForModel(account, modelKey);
1382
- if (this.isModelBreakerActive(modelKey, now))
1422
+ const quotaStateKey = this.resolveQuotaStateKey(modelKey);
1423
+ if (this.isModelBreakerActive(quotaStateKey, now))
1383
1424
  return "model circuit breaker active";
1384
- if (this.isProjectModelBreakerActive(projectId, modelKey, now))
1425
+ if (this.isProjectModelBreakerActive(projectId, quotaStateKey, now))
1385
1426
  return "project circuit breaker active";
1386
1427
  if (
1387
1428
  projectId &&
@@ -1460,7 +1501,8 @@ export class AccountRotator {
1460
1501
  const defaultCooldown = account.cooldownsByModel["__default__"] ?? 0;
1461
1502
  if (defaultCooldown > now)
1462
1503
  return { reason: "cooldown", detail: "default cooldown active" };
1463
- const modelCooldown = account.cooldownsByModel[modelKey] ?? 0;
1504
+ const modelCooldown =
1505
+ account.cooldownsByModel[this.resolveQuotaStateKey(modelKey)] ?? 0;
1464
1506
  if (modelCooldown > now)
1465
1507
  return { reason: "cooldown", detail: "model cooldown active" };
1466
1508
  // Ollama Cloud (pool key "session") imposes no per-account
@@ -2459,7 +2501,7 @@ export class AccountRotator {
2459
2501
  ): void {
2460
2502
  const now = new Date();
2461
2503
  const minuteKey = now.toISOString().slice(0, 16); // "2026-04-28T12:05"
2462
- const modelKey = model ? resolveDisplayModelKey(model) : "unknown";
2504
+ const modelKey = model ? this.resolveObservedModelKey(model) : "unknown";
2463
2505
 
2464
2506
  // Upsert minute bucket
2465
2507
  let bucket = this.tokenBuckets.minutes.find((b) => b.period === minuteKey);
@@ -2497,7 +2539,7 @@ export class AccountRotator {
2497
2539
  ttfbMs: number,
2498
2540
  totalMs: number,
2499
2541
  ): void {
2500
- const modelKey = model ? resolveDisplayModelKey(model) : "unknown";
2542
+ const modelKey = model ? this.resolveObservedModelKey(model) : "unknown";
2501
2543
  let records = this.latencyRecords.get(modelKey);
2502
2544
  if (!records) {
2503
2545
  records = [];
@@ -2888,17 +2930,7 @@ export class AccountRotator {
2888
2930
  let totalUsd = 0;
2889
2931
  const byModel: TokenUsageData["savings"]["byModel"] = {};
2890
2932
  for (const [model, totals] of Object.entries(modelTotals)) {
2891
- let pricing = MODEL_PRICING[model];
2892
- if (!pricing) {
2893
- const lower = model.toLowerCase();
2894
- if (lower.includes("opus")) pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
2895
- else if (lower.includes("sonnet")) pricing = MODEL_PRICING["claude-sonnet-4-6"];
2896
- else if (lower.includes("3.8-flash")) pricing = MODEL_PRICING["gemini-3.8-flash-high"];
2897
- else if (lower.includes("3.7-flash")) pricing = MODEL_PRICING["gemini-3.7-flash-tiered"];
2898
- else if (lower.includes("3.6-flash")) pricing = MODEL_PRICING["gemini-3.6-flash-high"];
2899
- else if (lower.includes("flash")) pricing = MODEL_PRICING["gemini-3-flash"];
2900
- else if (lower.includes("pro")) pricing = MODEL_PRICING["gemini-3.1-pro"];
2901
- }
2933
+ const pricing = getModelPricing(model);
2902
2934
  if (!pricing) continue;
2903
2935
  const inputUsd = (totals.input / 1_000_000) * pricing.inputPer1M;
2904
2936
  const outputUsd = (totals.output / 1_000_000) * pricing.outputPer1M;
@@ -3078,6 +3110,7 @@ export class AccountRotator {
3078
3110
  account.consecutiveErrors++;
3079
3111
  if (account.consecutiveErrors >= 5) {
3080
3112
  account.disabled = true;
3113
+ this.reconcileDynamicCatalog();
3081
3114
  this.log(
3082
3115
  `${account.config.email}: DISABLED after ${account.consecutiveErrors} consecutive errors`,
3083
3116
  "error",
@@ -3101,6 +3134,7 @@ export class AccountRotator {
3101
3134
  account.consecutiveErrors = 0;
3102
3135
  account.lastError = null;
3103
3136
  account.cooldownsByModel = {};
3137
+ this.reconcileDynamicCatalog();
3104
3138
  await this.saveState();
3105
3139
  this.log(`${email}: re-enabled`);
3106
3140
  this.requestWaiterDrain();
@@ -3112,6 +3146,7 @@ export class AccountRotator {
3112
3146
  if (!account) return false;
3113
3147
  account.disabled = true;
3114
3148
  account.lastError = "Disabled by operator";
3149
+ this.reconcileDynamicCatalog();
3115
3150
  await this.saveState();
3116
3151
  this.log(`${email}: disabled by operator`, "warn");
3117
3152
  return true;
@@ -3125,6 +3160,7 @@ export class AccountRotator {
3125
3160
  if (!account) return false;
3126
3161
  account.flagged = true;
3127
3162
  account.lastError = reason;
3163
+ this.reconcileDynamicCatalog();
3128
3164
  await this.saveState();
3129
3165
  this.log(`${email}: quarantined by operator`, "warn");
3130
3166
  return true;
@@ -3137,6 +3173,7 @@ export class AccountRotator {
3137
3173
  account.flagged = false;
3138
3174
  account.consecutiveErrors = 0;
3139
3175
  account.lastError = null;
3176
+ this.reconcileDynamicCatalog();
3140
3177
  await this.saveState();
3141
3178
  this.log(`${email}: restored by operator`, "warn");
3142
3179
  this.requestWaiterDrain();
@@ -3154,6 +3191,7 @@ export class AccountRotator {
3154
3191
  (entry) => entry.email === email,
3155
3192
  );
3156
3193
  if (existing) Object.assign(existing, patch);
3194
+ this.reconcileDynamicCatalog();
3157
3195
  await saveAccountsConfig(this.config);
3158
3196
  await this.saveState();
3159
3197
  this.log(`${email}: metadata updated by operator`, "warn");
@@ -3426,6 +3464,7 @@ export class AccountRotator {
3426
3464
  account.providerTokens ??= {};
3427
3465
  account.providerTokens[providerId] = { accessToken: null, tokenExpires: 0 };
3428
3466
  account.lastError = reason;
3467
+ if (providerId === DEFAULT_PROVIDER) this.reconcileDynamicCatalog();
3429
3468
  this.log(`${account.config.email}: ${providerId} credential requires re-authentication`, "warn");
3430
3469
  this.scheduleStateSave();
3431
3470
  }
@@ -3460,7 +3499,8 @@ export class AccountRotator {
3460
3499
  const providerId = getProviderIdForPoolKey(modelKey);
3461
3500
  if (account.invalidProviders?.[providerId]) return false;
3462
3501
  if ((account.providerCooldowns?.[providerId] ?? 0) > now) return false;
3463
- const modelCooldown = account.cooldownsByModel[modelKey] ?? 0;
3502
+ const modelCooldown =
3503
+ account.cooldownsByModel[this.resolveQuotaStateKey(modelKey)] ?? 0;
3464
3504
  if (modelCooldown > now) return false;
3465
3505
  // Ollama Cloud (pool key "session") imposes no per-account concurrency
3466
3506
  // limit. Antigravity keeps it so long streams don't pile up on a
@@ -3485,6 +3525,7 @@ export class AccountRotator {
3485
3525
  account.lastError = reason;
3486
3526
  account.inFlightRequests = 0;
3487
3527
  account.inFlightByModel = {};
3528
+ this.reconcileDynamicCatalog();
3488
3529
  this.requestWaiterDrain();
3489
3530
  this.log(`${account.config.email}: FLAGGED - ${reason}`, "error");
3490
3531
  const triggerProtectivePause = options.triggerProtectivePause ?? true;
@@ -3538,6 +3579,14 @@ export class AccountRotator {
3538
3579
  account: AccountRuntime,
3539
3580
  modelKey: string,
3540
3581
  ): boolean {
3582
+ const accountId = getAccountIdentity(account);
3583
+ if (
3584
+ !isStaticAntigravityModel(modelKey) &&
3585
+ dynamicCatalog.hasOwnershipForModel(modelKey) &&
3586
+ !dynamicCatalog.hasModelForAccount(accountId, modelKey)
3587
+ ) {
3588
+ return false;
3589
+ }
3541
3590
  const providerId = getProviderIdForPoolKey(modelKey);
3542
3591
  return hasCredential(account.config, providerId) &&
3543
3592
  !account.invalidProviders?.[providerId] &&
@@ -3549,11 +3598,24 @@ export class AccountRotator {
3549
3598
  return this.resolveRequestPoolKey(model);
3550
3599
  }
3551
3600
 
3601
+ /** Preserve the exact identity of models learned from the runtime catalog. */
3602
+ resolveObservedModelKey(model: string): string {
3603
+ return dynamicCatalog.getObservedModelId(model) ?? resolveDisplayModelKey(model);
3604
+ }
3605
+
3552
3606
  private resolveRequestPoolKey(model: string): string {
3553
3607
  return this.resolvePoolKeyForModel(model) ?? "__default__";
3554
3608
  }
3555
3609
 
3556
3610
  private resolvePoolKeyForModel(model: string): string | null {
3611
+ const normalizedModel = model.trim().toLowerCase();
3612
+ if (
3613
+ !isStaticAntigravityModel(model) &&
3614
+ dynamicCatalog.wasDiscovered(model)
3615
+ ) return normalizedModel;
3616
+ if (this.hasRelevantQuotaStateForModel(normalizedModel, Date.now())) {
3617
+ return normalizedModel;
3618
+ }
3557
3619
  const context = {
3558
3620
  ollamaModels: this.ollamaModels,
3559
3621
  codexModels: this.codexModels,
@@ -3565,6 +3627,30 @@ export class AccountRotator {
3565
3627
  return resolveQuotaModelKey(model) ?? null;
3566
3628
  }
3567
3629
 
3630
+ private hasRelevantQuotaStateForModel(modelKey: string, now: number): boolean {
3631
+ if ((this.modelBreakers[modelKey] ?? 0) > now) return true;
3632
+ if (
3633
+ this.accounts.some(
3634
+ (account) => (account.cooldownsByModel[modelKey] ?? 0) > now,
3635
+ )
3636
+ ) return true;
3637
+ if (
3638
+ Object.entries(this.projectModelBreakers).some(([key, deadline]) =>
3639
+ key.endsWith(`::${modelKey}`) && deadline > now
3640
+ )
3641
+ ) return true;
3642
+ const windowMs = this.config.projectCircuitBreakerWindowMs ?? 10 * 60 * 1000;
3643
+ return this.provider429Events.some(
3644
+ (event) => event.modelKey === modelKey && now - event.ts <= windowMs,
3645
+ );
3646
+ }
3647
+
3648
+ private resolveQuotaStateKey(modelKey: string): string {
3649
+ return dynamicCatalog.resolveQuotaPool(modelKey) ??
3650
+ resolveQuotaModelKey(modelKey) ??
3651
+ modelKey;
3652
+ }
3653
+
3568
3654
  /** Map a candidate key (model name or pool key) to the account's pool key. */
3569
3655
  private resolvePoolKey(account: AccountRuntime, key: string): string {
3570
3656
  if (
@@ -3581,6 +3667,8 @@ export class AccountRotator {
3581
3667
  private resolveAccountPoolKey(account: AccountRuntime, key: string): string {
3582
3668
  const kickstartPool = QUOTA_POOL_FOR_KICKSTART_MODEL[key];
3583
3669
  if (kickstartPool) return this.resolvePoolKey(account, kickstartPool);
3670
+ const dynamicPool = dynamicCatalog.resolveQuotaPool(key);
3671
+ if (dynamicPool) return this.resolvePoolKey(account, dynamicPool);
3584
3672
  if (
3585
3673
  Object.values(QUOTA_POOL_FOR_KICKSTART_MODEL).includes(key) ||
3586
3674
  account.quota.some((quota) => quota.modelKey === key) ||
@@ -3619,8 +3707,9 @@ export class AccountRotator {
3619
3707
  const modelKey = model
3620
3708
  ? (this.resolvePoolKeyForModel(model) ?? resolveQuotaModelKey(model) ?? "__default__")
3621
3709
  : "__default__";
3710
+ const quotaStateKey = this.resolveQuotaStateKey(modelKey);
3622
3711
  const dailyResetAt = nextUtcDayStartMs(now);
3623
- const modelBreaker = this.modelBreakers[modelKey] ?? 0;
3712
+ const modelBreaker = this.modelBreakers[quotaStateKey] ?? 0;
3624
3713
  if (modelBreaker > now) retryTimes.push(modelBreaker);
3625
3714
  for (const account of this.accounts) {
3626
3715
  if (account.disabled || account.flagged) continue;
@@ -3636,14 +3725,14 @@ export class AccountRotator {
3636
3725
  if (this.isDailySafetyStopped(account, now))
3637
3726
  retryTimes.push(dailyResetAt);
3638
3727
  const cooldown = Math.max(
3639
- account.cooldownsByModel[modelKey] ?? 0,
3728
+ account.cooldownsByModel[quotaStateKey] ?? 0,
3640
3729
  account.cooldownsByModel.__default__ ?? 0,
3641
3730
  );
3642
3731
  if (cooldown > now) retryTimes.push(cooldown);
3643
3732
  const projectId = this.getProjectIdForModel(account, modelKey);
3644
3733
  if (projectId) {
3645
3734
  const projectBreaker =
3646
- this.projectModelBreakers[projectModelKey(projectId, modelKey)] ?? 0;
3735
+ this.projectModelBreakers[projectModelKey(projectId, quotaStateKey)] ?? 0;
3647
3736
  if (projectBreaker > now) retryTimes.push(projectBreaker);
3648
3737
  }
3649
3738
  if ((this.config.routingPolicy || "timer-first") === "hybrid") {
@@ -3914,6 +4003,7 @@ export class AccountRotator {
3914
4003
  const mergedAccounts = normalized.accounts.map(matchAndReuseAccount);
3915
4004
  this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
3916
4005
  this.accounts = mergedAccounts;
4006
+ this.reconcileDynamicCatalog();
3917
4007
  this.requestWaiterDrain();
3918
4008
  await saveAccountsConfig(this.config);
3919
4009
  await this.saveState();
@@ -4025,6 +4115,7 @@ export class AccountRotator {
4025
4115
  this.log(`${accountConfig.email}: account added via hosted login`);
4026
4116
  }
4027
4117
 
4118
+ this.reconcileDynamicCatalog();
4028
4119
  await saveAccountsConfig(this.config);
4029
4120
  await this.saveState();
4030
4121
  this.requestWaiterDrain();
@@ -4045,6 +4136,7 @@ export class AccountRotator {
4045
4136
  this.accounts.splice(idx, 1);
4046
4137
  const configIdx = this.config.accounts.findIndex((a) => a.email === email);
4047
4138
  if (configIdx >= 0) this.config.accounts.splice(configIdx, 1);
4139
+ this.reconcileDynamicCatalog();
4048
4140
 
4049
4141
  // Fix up modelState indices that may now be stale after the splice
4050
4142
  for (const [, mState] of this.modelState.entries()) {
@@ -1,5 +1,5 @@
1
1
  import randomBytes from "node:crypto";
2
- import { MODEL_PRICING, type SpendLog, type DailySpend } from "./types.js";
2
+ import { getModelPricing, type SpendLog, type DailySpend } from "./types.js";
3
3
  import { isDbConfigured, queryDb } from "./db-store.js";
4
4
  import { rotatorEnv } from "./env.js";
5
5
 
@@ -59,7 +59,7 @@ export function logSpend(
59
59
  return;
60
60
  }
61
61
 
62
- const pricing = MODEL_PRICING[log.model] || { inputPer1M: 0, outputPer1M: 0 };
62
+ const pricing = getModelPricing(log.model) ?? { inputPer1M: 0, outputPer1M: 0 };
63
63
  const promptTokens = Math.max(0, log.promptTokens || 0);
64
64
  const completionTokens = Math.max(0, log.completionTokens || 0);
65
65
  const promptCostUsd = (promptTokens / 1_000_000) * (pricing.inputPer1M || 0);
@@ -253,25 +253,7 @@ export async function flushSpendLogs(): Promise<void> {
253
253
  }
254
254
 
255
255
  export function calculateCost(model: string, promptTokens: number, completionTokens: number): number {
256
- let pricing = MODEL_PRICING[model];
257
- if (!pricing) {
258
- const lower = model.toLowerCase();
259
- if (lower.includes("opus")) {
260
- pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
261
- } else if (lower.includes("sonnet")) {
262
- pricing = MODEL_PRICING["claude-sonnet-4-6"];
263
- } else if (lower.includes("3.8-flash")) {
264
- pricing = MODEL_PRICING["gemini-3.8-flash-high"];
265
- } else if (lower.includes("3.7-flash")) {
266
- pricing = MODEL_PRICING["gemini-3.7-flash-tiered"];
267
- } else if (lower.includes("3.6-flash")) {
268
- pricing = MODEL_PRICING["gemini-3.6-flash-high"];
269
- } else if (lower.includes("flash")) {
270
- pricing = MODEL_PRICING["gemini-3-flash"];
271
- } else if (lower.includes("pro")) {
272
- pricing = MODEL_PRICING["gemini-3.1-pro"];
273
- }
274
- }
256
+ const pricing = getModelPricing(model);
275
257
  if (!pricing) return 0;
276
258
  const inputCost = (promptTokens / 1_000_000) * pricing.inputPer1M;
277
259
  const outputCost = (completionTokens / 1_000_000) * pricing.outputPer1M;
@@ -1221,13 +1221,16 @@ var MODEL_PRICING_CLIENT = {
1221
1221
  function getModelPricingClient(m) {
1222
1222
  if (MODEL_PRICING_CLIENT[m]) return MODEL_PRICING_CLIENT[m];
1223
1223
  var lower = (m || "").toLowerCase();
1224
- if (lower.indexOf("opus") !== -1) return MODEL_PRICING_CLIENT["claude-opus-4-6-thinking"];
1225
- if (lower.indexOf("sonnet") !== -1) return MODEL_PRICING_CLIENT["claude-sonnet-4-6"];
1226
- if (lower.indexOf("3.8-flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3.8-flash-high"];
1227
- if (lower.indexOf("3.7-flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3.7-flash-tiered"];
1228
- if (lower.indexOf("3.6-flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3.6-flash-high"];
1229
- if (lower.indexOf("flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3-flash"];
1230
- if (lower.indexOf("pro") !== -1) return MODEL_PRICING_CLIENT["gemini-3.1-pro"];
1224
+ if (lower.indexOf("claude") !== -1 && lower.indexOf("opus") !== -1) return MODEL_PRICING_CLIENT["claude-opus-4-6-thinking"];
1225
+ if (lower.indexOf("claude") !== -1 && lower.indexOf("sonnet") !== -1) return MODEL_PRICING_CLIENT["claude-sonnet-4-6"];
1226
+ if (lower.indexOf("gemini") !== -1) {
1227
+ if (lower.indexOf("3.8") !== -1 && lower.indexOf("flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3.8-flash-high"];
1228
+ if (lower.indexOf("3.7") !== -1 && lower.indexOf("flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3.7-flash-tiered"];
1229
+ if (lower.indexOf("3.6") !== -1 && lower.indexOf("flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3.6-flash-high"];
1230
+ if (lower.indexOf("flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3-flash"];
1231
+ if (lower.indexOf("pro") !== -1) return MODEL_PRICING_CLIENT["gemini-3.1-pro"];
1232
+ }
1233
+ if (lower.indexOf("gpt-oss") !== -1) return MODEL_PRICING_CLIENT["gpt-oss-120b-medium"];
1231
1234
  return null;
1232
1235
  }
1233
1236