tuxevil-rotator 3.5.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.
@@ -11,6 +11,7 @@ import {
11
11
  getModelSpec,
12
12
  isThinkingModel,
13
13
  } from "../../compat/model-specs.js";
14
+ import { dynamicCatalog } from "./dynamic-catalog.js";
14
15
  import {
15
16
  thoughtSignatureCache,
16
17
  getStoredResponse,
@@ -22,6 +23,32 @@ const compatLogger = logger.child("compat");
22
23
 
23
24
  const VALIDATION_LOG_MAX_CHARS = 200;
24
25
 
26
+ function normalizeFixedThinking(
27
+ modelSpec: ReturnType<typeof getModelSpec>,
28
+ requestedMaxOutputTokens: number | undefined,
29
+ ): { budget?: number; maxOutputTokens: number | undefined } {
30
+ const outputLimit = Math.max(1, Math.floor(modelSpec.maxOutputTokens));
31
+ const minimum = typeof modelSpec.minThinkingBudget === "number" &&
32
+ Number.isFinite(modelSpec.minThinkingBudget)
33
+ ? Math.max(0, Math.floor(modelSpec.minThinkingBudget))
34
+ : 0;
35
+ let budget = Math.max(
36
+ minimum,
37
+ Math.max(0, Math.floor(modelSpec.thinkingBudget)),
38
+ );
39
+ budget = Math.min(budget, outputLimit - 1);
40
+ if (budget < minimum) {
41
+ return { maxOutputTokens: requestedMaxOutputTokens };
42
+ }
43
+
44
+ let maxOutputTokens = requestedMaxOutputTokens;
45
+ if (!maxOutputTokens || maxOutputTokens <= budget) {
46
+ maxOutputTokens = Math.min(budget + 8192, outputLimit);
47
+ if (maxOutputTokens <= budget) maxOutputTokens = budget + 1;
48
+ }
49
+ return { budget, maxOutputTokens };
50
+ }
51
+
25
52
  export function logValidationFailure(scope: string, payload: unknown): void {
26
53
  const truncated = redactSensitive(JSON.stringify(payload));
27
54
  const clipped =
@@ -156,6 +183,7 @@ export interface CompatCompletion {
156
183
  toolCalls?: OpenAIToolCall[];
157
184
  rawResponse?: unknown;
158
185
  streamError?: string;
186
+ finishReason?: string;
159
187
  }
160
188
 
161
189
  export type AntigravityPart =
@@ -841,7 +869,6 @@ export function convertResponsesToChatRequest(
841
869
  * reasoning_effort. Matched case-insensitively against the exact ID only;
842
870
  * virtual siblings (e.g. `gemini-3.7-flash-tiered-high`) are excluded.
843
871
  */
844
- import { dynamicCatalog } from "./dynamic-catalog.js";
845
872
 
846
873
  export const TIERED_EFFORT_MODEL_ID = "gemini-3.7-flash-tiered";
847
874
  export const TIERED_EFFORT_MODEL_IDS = new Set([
@@ -1192,13 +1219,22 @@ export function openAIToAntigravityBody(
1192
1219
 
1193
1220
  let thinkingConfigObj: Record<string, unknown> | undefined;
1194
1221
  if (modelFamily === "claude" && isThinking && !forcesToolUse(input.tool_choice)) {
1195
- const tb = modelSpec.thinkingBudget;
1196
- thinkingConfigObj = { include_thoughts: true, thinking_budget: tb };
1197
- if (!maxOutputTokens || maxOutputTokens <= tb) {
1198
- maxOutputTokens = Math.min(tb + 8192, modelSpec.maxOutputTokens);
1199
- compatLogger.debug(
1200
- `Adjusted Claude maxOutputTokens → ${maxOutputTokens}`,
1201
- );
1222
+ if (modelSpec.thinkingBudget === -1) {
1223
+ thinkingConfigObj = { include_thoughts: true };
1224
+ } else {
1225
+ const normalized = normalizeFixedThinking(modelSpec, maxOutputTokens);
1226
+ if (normalized.budget !== undefined) {
1227
+ thinkingConfigObj = {
1228
+ include_thoughts: true,
1229
+ thinking_budget: normalized.budget,
1230
+ };
1231
+ }
1232
+ if (maxOutputTokens !== normalized.maxOutputTokens) {
1233
+ maxOutputTokens = normalized.maxOutputTokens;
1234
+ compatLogger.debug(
1235
+ `Adjusted Claude maxOutputTokens → ${maxOutputTokens}`,
1236
+ );
1237
+ }
1202
1238
  }
1203
1239
  } else if (isThinking && modelFamily !== "claude") {
1204
1240
  const tb = modelSpec.thinkingBudget;
@@ -1221,23 +1257,29 @@ export function openAIToAntigravityBody(
1221
1257
  };
1222
1258
  } else if (tb === -1) {
1223
1259
  thinkingConfigObj = { includeThoughts: true };
1260
+ if (maxOutputTokens !== undefined) {
1261
+ // Adaptive models spend from the output budget before emitting visible text.
1262
+ const targetTokens = Math.max(maxOutputTokens + 8192, 8192);
1263
+ maxOutputTokens = Math.min(targetTokens, modelSpec.maxOutputTokens);
1264
+ compatLogger.debug(
1265
+ `Adjusted adaptive Gemini maxOutputTokens → ${maxOutputTokens}`,
1266
+ );
1267
+ }
1224
1268
  } else {
1225
- thinkingConfigObj = { includeThoughts: true, thinkingBudget: tb };
1226
- }
1227
- if (tb !== -1 && (!maxOutputTokens || maxOutputTokens <= tb)) {
1228
- maxOutputTokens = Math.min(tb + 8192, modelSpec.maxOutputTokens);
1229
- compatLogger.debug(
1230
- `Adjusted Gemini maxOutputTokens → ${maxOutputTokens}`,
1231
- );
1269
+ const normalized = normalizeFixedThinking(modelSpec, maxOutputTokens);
1270
+ if (normalized.budget !== undefined) {
1271
+ thinkingConfigObj = {
1272
+ includeThoughts: true,
1273
+ thinkingBudget: normalized.budget,
1274
+ };
1275
+ }
1276
+ if (maxOutputTokens !== normalized.maxOutputTokens) {
1277
+ maxOutputTokens = normalized.maxOutputTokens;
1278
+ compatLogger.debug(
1279
+ `Adjusted Gemini maxOutputTokens → ${maxOutputTokens}`,
1280
+ );
1281
+ }
1232
1282
  }
1233
- } else if (input.reasoning_effort) {
1234
- const budgets: Record<string, number> = {
1235
- low: Math.round(modelSpec.thinkingBudget / 4),
1236
- medium: Math.round(modelSpec.thinkingBudget / 2),
1237
- high: modelSpec.thinkingBudget,
1238
- };
1239
- const b = budgets[input.reasoning_effort.toLowerCase()];
1240
- if (b) thinkingConfigObj = { includeThoughts: true, thinkingBudget: b };
1241
1283
  }
1242
1284
 
1243
1285
  const generationConfig: Record<string, unknown> = {
package/src/proxy.ts CHANGED
@@ -132,6 +132,13 @@ function routingModelKey(rotator: AccountRotator, model: string): string {
132
132
  }).resolveQuotaModelKeyForDisplay;
133
133
  return resolver?.call(rotator, model) ?? resolveQuotaModelKey(model) ?? model;
134
134
  }
135
+
136
+ function observedModelKey(rotator: AccountRotator, model: string): string {
137
+ const resolver = (rotator as unknown as {
138
+ resolveObservedModelKey?: (value: string) => string;
139
+ }).resolveObservedModelKey;
140
+ return resolver?.call(rotator, model) ?? resolveDisplayModelKey(model);
141
+ }
135
142
  import { startVersionChecker, performSelfUpdate } from "./version-check.js";
136
143
  import { startNotificationPoller } from "./notification-poller.js";
137
144
  import {
@@ -1173,7 +1180,7 @@ export async function withRotation<T>(
1173
1180
 
1174
1181
  const label = account.config.label || account.config.email;
1175
1182
  const modelKey = routingModelKey(rotator, model);
1176
- const displayModelKey = resolveDisplayModelKey(body.displayModel || model);
1183
+ const displayModelKey = observedModelKey(rotator, body.displayModel || model);
1177
1184
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1178
1185
  const requestStartMs = Date.now();
1179
1186
  let accountReleased = false;
@@ -1609,7 +1616,7 @@ async function handleProxyRequest(
1609
1616
 
1610
1617
  const label = account.config.label || account.config.email;
1611
1618
  const modelKey = rotator.resolveQuotaModelKeyForDisplay(body.model) ?? body.model; // quota routing
1612
- const displayModelKey = resolveDisplayModelKey(body.model); // metrics/logs
1619
+ const displayModelKey = observedModelKey(rotator, body.model); // metrics/logs
1613
1620
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1614
1621
  let accountReleased = false;
1615
1622
  const releaseCurrentAccount = (): void => {
package/src/rotator.ts CHANGED
@@ -90,11 +90,14 @@ import {
90
90
  } from "./rate-limit-parser.js";
91
91
  import {
92
92
  getAccountIdentity,
93
+ getCredentialGeneration,
94
+ getCredentialGenerationFingerprint,
93
95
  getProviderCredentialDetails,
94
96
  } from "./account-identity.js";
95
97
 
96
98
  export {
97
99
  getAccountIdentity,
100
+ getCredentialGeneration,
98
101
  getProviderCredentialDetails,
99
102
  } from "./account-identity.js";
100
103
 
@@ -154,18 +157,6 @@ export function areAccountIdentitiesCompatible(
154
157
  return true;
155
158
  }
156
159
 
157
- export function getCredentialGeneration(
158
- account: AccountRuntime | AccountConfig,
159
- providerId: string,
160
- ): string {
161
- const config = "config" in account ? account.config : account;
162
- const norm = normalizeAccountConfig(config);
163
- const cred = norm.credentials?.find((c) => c.provider === providerId);
164
- const details = getProviderCredentialDetails(norm, cred ?? { provider: providerId });
165
- if (!cred && !details.secret) return "none";
166
- return `${providerId}:${details.projectId}:${details.providerAccountId}:${details.secret}`;
167
- }
168
-
169
160
  const rotatorLogger = logger.child("rotator");
170
161
 
171
162
  function currentUtcDay(now = Date.now()): string {
@@ -359,9 +350,27 @@ export class AccountRotator {
359
350
  this.config = applyConfigDefaults(config);
360
351
  this.initAccounts();
361
352
  this.loadState();
353
+ this.reconcileDynamicCatalog();
362
354
  this.startQuotaPolling();
363
355
  }
364
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
+
365
374
  private initAccounts(): void {
366
375
  this.accounts = this.config.accounts.map((config) => ({
367
376
  config,
@@ -485,6 +494,17 @@ export class AccountRotator {
485
494
  }
486
495
 
487
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
+ );
488
508
  // Load per-model account assignments
489
509
  if (state.modelAccounts) {
490
510
  for (const [model, idx] of Object.entries(state.modelAccounts)) {
@@ -541,8 +561,9 @@ export class AccountRotator {
541
561
  saved.allowFreshWindowStartsOverride ?? false;
542
562
  }
543
563
  }
544
- // Cap generic stale cooldowns to 30 min max from now. Antigravity's
545
- // 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.
546
567
  const maxCooldown = 30 * 60 * 1000;
547
568
  const now = Date.now();
548
569
  for (const account of this.accounts) {
@@ -552,6 +573,8 @@ export class AccountRotator {
552
573
  if (
553
574
  model !== "claude" &&
554
575
  model !== "gemini" &&
576
+ (model === "__default__" ||
577
+ getProviderIdForPoolKey(model) !== DEFAULT_PROVIDER) &&
555
578
  cooldown > now + maxCooldown
556
579
  ) {
557
580
  account.cooldownsByModel[model] = now + maxCooldown;
@@ -565,6 +588,41 @@ export class AccountRotator {
565
588
  this.loadTokenUsage();
566
589
  }
567
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
+
568
626
  private loadTokenUsage(): void {
569
627
  try {
570
628
  const parsed = getCachedTokenUsage() as any;
@@ -621,6 +679,22 @@ export class AccountRotator {
621
679
  }
622
680
 
623
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
+ ),
624
698
  modelAccounts,
625
699
  modelRequestCounts,
626
700
  modelStickyAccounts,
@@ -805,6 +879,9 @@ export class AccountRotator {
805
879
  try {
806
880
  await this.ensureValidTokenForProvider(account, pid);
807
881
  await getProviderAdapter(pid).fetchQuota(account, quotaCtx);
882
+ if (pid === DEFAULT_PROVIDER) {
883
+ this.migratePersistedQuotaStateKeys();
884
+ }
808
885
  quotaPublished = true;
809
886
  } catch {
810
887
  // One invalid provider credential must not suppress sibling pools.
@@ -860,11 +937,7 @@ export class AccountRotator {
860
937
  void this.refreshOllamaCatalogOnce().catch(() => {});
861
938
 
862
939
  const available = this.accounts.filter((a) => !a.disabled && !a.flagged);
863
- dynamicCatalog.retainAccounts(
864
- available
865
- .filter((account) => hasCredential(account.config, DEFAULT_PROVIDER))
866
- .map(getAccountIdentity),
867
- );
940
+ this.reconcileDynamicCatalog();
868
941
  let quotaPublished = false;
869
942
  for (const account of available) {
870
943
  if (await this.pollAccountQuota(account)) {
@@ -1346,9 +1419,10 @@ export class AccountRotator {
1346
1419
  ignoreConcurrency = false,
1347
1420
  ): string | null {
1348
1421
  const projectId = this.getProjectIdForModel(account, modelKey);
1349
- if (this.isModelBreakerActive(modelKey, now))
1422
+ const quotaStateKey = this.resolveQuotaStateKey(modelKey);
1423
+ if (this.isModelBreakerActive(quotaStateKey, now))
1350
1424
  return "model circuit breaker active";
1351
- if (this.isProjectModelBreakerActive(projectId, modelKey, now))
1425
+ if (this.isProjectModelBreakerActive(projectId, quotaStateKey, now))
1352
1426
  return "project circuit breaker active";
1353
1427
  if (
1354
1428
  projectId &&
@@ -1427,7 +1501,8 @@ export class AccountRotator {
1427
1501
  const defaultCooldown = account.cooldownsByModel["__default__"] ?? 0;
1428
1502
  if (defaultCooldown > now)
1429
1503
  return { reason: "cooldown", detail: "default cooldown active" };
1430
- const modelCooldown = account.cooldownsByModel[modelKey] ?? 0;
1504
+ const modelCooldown =
1505
+ account.cooldownsByModel[this.resolveQuotaStateKey(modelKey)] ?? 0;
1431
1506
  if (modelCooldown > now)
1432
1507
  return { reason: "cooldown", detail: "model cooldown active" };
1433
1508
  // Ollama Cloud (pool key "session") imposes no per-account
@@ -2426,7 +2501,7 @@ export class AccountRotator {
2426
2501
  ): void {
2427
2502
  const now = new Date();
2428
2503
  const minuteKey = now.toISOString().slice(0, 16); // "2026-04-28T12:05"
2429
- const modelKey = model ? resolveDisplayModelKey(model) : "unknown";
2504
+ const modelKey = model ? this.resolveObservedModelKey(model) : "unknown";
2430
2505
 
2431
2506
  // Upsert minute bucket
2432
2507
  let bucket = this.tokenBuckets.minutes.find((b) => b.period === minuteKey);
@@ -2464,7 +2539,7 @@ export class AccountRotator {
2464
2539
  ttfbMs: number,
2465
2540
  totalMs: number,
2466
2541
  ): void {
2467
- const modelKey = model ? resolveDisplayModelKey(model) : "unknown";
2542
+ const modelKey = model ? this.resolveObservedModelKey(model) : "unknown";
2468
2543
  let records = this.latencyRecords.get(modelKey);
2469
2544
  if (!records) {
2470
2545
  records = [];
@@ -3035,6 +3110,7 @@ export class AccountRotator {
3035
3110
  account.consecutiveErrors++;
3036
3111
  if (account.consecutiveErrors >= 5) {
3037
3112
  account.disabled = true;
3113
+ this.reconcileDynamicCatalog();
3038
3114
  this.log(
3039
3115
  `${account.config.email}: DISABLED after ${account.consecutiveErrors} consecutive errors`,
3040
3116
  "error",
@@ -3058,6 +3134,7 @@ export class AccountRotator {
3058
3134
  account.consecutiveErrors = 0;
3059
3135
  account.lastError = null;
3060
3136
  account.cooldownsByModel = {};
3137
+ this.reconcileDynamicCatalog();
3061
3138
  await this.saveState();
3062
3139
  this.log(`${email}: re-enabled`);
3063
3140
  this.requestWaiterDrain();
@@ -3069,6 +3146,7 @@ export class AccountRotator {
3069
3146
  if (!account) return false;
3070
3147
  account.disabled = true;
3071
3148
  account.lastError = "Disabled by operator";
3149
+ this.reconcileDynamicCatalog();
3072
3150
  await this.saveState();
3073
3151
  this.log(`${email}: disabled by operator`, "warn");
3074
3152
  return true;
@@ -3082,6 +3160,7 @@ export class AccountRotator {
3082
3160
  if (!account) return false;
3083
3161
  account.flagged = true;
3084
3162
  account.lastError = reason;
3163
+ this.reconcileDynamicCatalog();
3085
3164
  await this.saveState();
3086
3165
  this.log(`${email}: quarantined by operator`, "warn");
3087
3166
  return true;
@@ -3094,6 +3173,7 @@ export class AccountRotator {
3094
3173
  account.flagged = false;
3095
3174
  account.consecutiveErrors = 0;
3096
3175
  account.lastError = null;
3176
+ this.reconcileDynamicCatalog();
3097
3177
  await this.saveState();
3098
3178
  this.log(`${email}: restored by operator`, "warn");
3099
3179
  this.requestWaiterDrain();
@@ -3111,6 +3191,7 @@ export class AccountRotator {
3111
3191
  (entry) => entry.email === email,
3112
3192
  );
3113
3193
  if (existing) Object.assign(existing, patch);
3194
+ this.reconcileDynamicCatalog();
3114
3195
  await saveAccountsConfig(this.config);
3115
3196
  await this.saveState();
3116
3197
  this.log(`${email}: metadata updated by operator`, "warn");
@@ -3383,6 +3464,7 @@ export class AccountRotator {
3383
3464
  account.providerTokens ??= {};
3384
3465
  account.providerTokens[providerId] = { accessToken: null, tokenExpires: 0 };
3385
3466
  account.lastError = reason;
3467
+ if (providerId === DEFAULT_PROVIDER) this.reconcileDynamicCatalog();
3386
3468
  this.log(`${account.config.email}: ${providerId} credential requires re-authentication`, "warn");
3387
3469
  this.scheduleStateSave();
3388
3470
  }
@@ -3417,7 +3499,8 @@ export class AccountRotator {
3417
3499
  const providerId = getProviderIdForPoolKey(modelKey);
3418
3500
  if (account.invalidProviders?.[providerId]) return false;
3419
3501
  if ((account.providerCooldowns?.[providerId] ?? 0) > now) return false;
3420
- const modelCooldown = account.cooldownsByModel[modelKey] ?? 0;
3502
+ const modelCooldown =
3503
+ account.cooldownsByModel[this.resolveQuotaStateKey(modelKey)] ?? 0;
3421
3504
  if (modelCooldown > now) return false;
3422
3505
  // Ollama Cloud (pool key "session") imposes no per-account concurrency
3423
3506
  // limit. Antigravity keeps it so long streams don't pile up on a
@@ -3442,6 +3525,7 @@ export class AccountRotator {
3442
3525
  account.lastError = reason;
3443
3526
  account.inFlightRequests = 0;
3444
3527
  account.inFlightByModel = {};
3528
+ this.reconcileDynamicCatalog();
3445
3529
  this.requestWaiterDrain();
3446
3530
  this.log(`${account.config.email}: FLAGGED - ${reason}`, "error");
3447
3531
  const triggerProtectivePause = options.triggerProtectivePause ?? true;
@@ -3495,10 +3579,11 @@ export class AccountRotator {
3495
3579
  account: AccountRuntime,
3496
3580
  modelKey: string,
3497
3581
  ): boolean {
3582
+ const accountId = getAccountIdentity(account);
3498
3583
  if (
3499
3584
  !isStaticAntigravityModel(modelKey) &&
3500
- dynamicCatalog.wasDiscovered(modelKey) &&
3501
- !dynamicCatalog.hasModelForAccount(getAccountIdentity(account), modelKey)
3585
+ dynamicCatalog.hasOwnershipForModel(modelKey) &&
3586
+ !dynamicCatalog.hasModelForAccount(accountId, modelKey)
3502
3587
  ) {
3503
3588
  return false;
3504
3589
  }
@@ -3513,15 +3598,24 @@ export class AccountRotator {
3513
3598
  return this.resolveRequestPoolKey(model);
3514
3599
  }
3515
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
+
3516
3606
  private resolveRequestPoolKey(model: string): string {
3517
3607
  return this.resolvePoolKeyForModel(model) ?? "__default__";
3518
3608
  }
3519
3609
 
3520
3610
  private resolvePoolKeyForModel(model: string): string | null {
3611
+ const normalizedModel = model.trim().toLowerCase();
3521
3612
  if (
3522
3613
  !isStaticAntigravityModel(model) &&
3523
3614
  dynamicCatalog.wasDiscovered(model)
3524
- ) return model.toLowerCase();
3615
+ ) return normalizedModel;
3616
+ if (this.hasRelevantQuotaStateForModel(normalizedModel, Date.now())) {
3617
+ return normalizedModel;
3618
+ }
3525
3619
  const context = {
3526
3620
  ollamaModels: this.ollamaModels,
3527
3621
  codexModels: this.codexModels,
@@ -3533,6 +3627,30 @@ export class AccountRotator {
3533
3627
  return resolveQuotaModelKey(model) ?? null;
3534
3628
  }
3535
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
+
3536
3654
  /** Map a candidate key (model name or pool key) to the account's pool key. */
3537
3655
  private resolvePoolKey(account: AccountRuntime, key: string): string {
3538
3656
  if (
@@ -3549,6 +3667,8 @@ export class AccountRotator {
3549
3667
  private resolveAccountPoolKey(account: AccountRuntime, key: string): string {
3550
3668
  const kickstartPool = QUOTA_POOL_FOR_KICKSTART_MODEL[key];
3551
3669
  if (kickstartPool) return this.resolvePoolKey(account, kickstartPool);
3670
+ const dynamicPool = dynamicCatalog.resolveQuotaPool(key);
3671
+ if (dynamicPool) return this.resolvePoolKey(account, dynamicPool);
3552
3672
  if (
3553
3673
  Object.values(QUOTA_POOL_FOR_KICKSTART_MODEL).includes(key) ||
3554
3674
  account.quota.some((quota) => quota.modelKey === key) ||
@@ -3587,8 +3707,9 @@ export class AccountRotator {
3587
3707
  const modelKey = model
3588
3708
  ? (this.resolvePoolKeyForModel(model) ?? resolveQuotaModelKey(model) ?? "__default__")
3589
3709
  : "__default__";
3710
+ const quotaStateKey = this.resolveQuotaStateKey(modelKey);
3590
3711
  const dailyResetAt = nextUtcDayStartMs(now);
3591
- const modelBreaker = this.modelBreakers[modelKey] ?? 0;
3712
+ const modelBreaker = this.modelBreakers[quotaStateKey] ?? 0;
3592
3713
  if (modelBreaker > now) retryTimes.push(modelBreaker);
3593
3714
  for (const account of this.accounts) {
3594
3715
  if (account.disabled || account.flagged) continue;
@@ -3604,14 +3725,14 @@ export class AccountRotator {
3604
3725
  if (this.isDailySafetyStopped(account, now))
3605
3726
  retryTimes.push(dailyResetAt);
3606
3727
  const cooldown = Math.max(
3607
- account.cooldownsByModel[modelKey] ?? 0,
3728
+ account.cooldownsByModel[quotaStateKey] ?? 0,
3608
3729
  account.cooldownsByModel.__default__ ?? 0,
3609
3730
  );
3610
3731
  if (cooldown > now) retryTimes.push(cooldown);
3611
3732
  const projectId = this.getProjectIdForModel(account, modelKey);
3612
3733
  if (projectId) {
3613
3734
  const projectBreaker =
3614
- this.projectModelBreakers[projectModelKey(projectId, modelKey)] ?? 0;
3735
+ this.projectModelBreakers[projectModelKey(projectId, quotaStateKey)] ?? 0;
3615
3736
  if (projectBreaker > now) retryTimes.push(projectBreaker);
3616
3737
  }
3617
3738
  if ((this.config.routingPolicy || "timer-first") === "hybrid") {
@@ -3882,6 +4003,7 @@ export class AccountRotator {
3882
4003
  const mergedAccounts = normalized.accounts.map(matchAndReuseAccount);
3883
4004
  this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
3884
4005
  this.accounts = mergedAccounts;
4006
+ this.reconcileDynamicCatalog();
3885
4007
  this.requestWaiterDrain();
3886
4008
  await saveAccountsConfig(this.config);
3887
4009
  await this.saveState();
@@ -3993,6 +4115,7 @@ export class AccountRotator {
3993
4115
  this.log(`${accountConfig.email}: account added via hosted login`);
3994
4116
  }
3995
4117
 
4118
+ this.reconcileDynamicCatalog();
3996
4119
  await saveAccountsConfig(this.config);
3997
4120
  await this.saveState();
3998
4121
  this.requestWaiterDrain();
@@ -4013,6 +4136,7 @@ export class AccountRotator {
4013
4136
  this.accounts.splice(idx, 1);
4014
4137
  const configIdx = this.config.accounts.findIndex((a) => a.email === email);
4015
4138
  if (configIdx >= 0) this.config.accounts.splice(configIdx, 1);
4139
+ this.reconcileDynamicCatalog();
4016
4140
 
4017
4141
  // Fix up modelState indices that may now be stale after the splice
4018
4142
  for (const [, mState] of this.modelState.entries()) {
@@ -1221,13 +1221,15 @@ 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
+ }
1231
1233
  if (lower.indexOf("gpt-oss") !== -1) return MODEL_PRICING_CLIENT["gpt-oss-120b-medium"];
1232
1234
  return null;
1233
1235
  }