tuxevil-rotator 3.3.1 → 3.4.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
@@ -83,9 +83,17 @@ import {
83
83
  getCachedTokenUsage,
84
84
  setCachedTokenUsage,
85
85
  } from "./db-store.js";
86
+ import {
87
+ classifyRateLimitReason,
88
+ parseRetryAfterMs,
89
+ RESOURCE_EXHAUSTED_FALLBACK_MS,
90
+ } from "./rate-limit-parser.js";
86
91
 
87
92
  function credentialFingerprint(secret?: string): string {
88
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]
89
97
  return createHash("sha256").update(secret).digest("hex").slice(0, 12);
90
98
  }
91
99
 
@@ -234,8 +242,9 @@ interface AccountRequestWaiter {
234
242
 
235
243
  // Reverse map: upstream model → the quota pool key it primarily represents (for deduplication).
236
244
  const QUOTA_POOL_FOR_KICKSTART_MODEL: Record<string, string> = {
237
- "gpt-oss-120b-medium": "claude-opus-4-6-thinking",
238
- "gemini-3-flash": "gemini-3.5-flash",
245
+ "gpt-oss-120b-medium": "claude",
246
+ "gemini-3-flash": "gemini",
247
+ "gpt-oss:20b": "session",
239
248
  };
240
249
 
241
250
  export class AccountRotator {
@@ -247,6 +256,9 @@ export class AccountRotator {
247
256
  private startTime = Date.now();
248
257
  private quotaPollTimer: ReturnType<typeof setInterval> | null = null;
249
258
  private quotaInitialPollTimer: ReturnType<typeof setTimeout> | null = null;
259
+ private quotaPolls = new WeakMap<AccountRuntime, Promise<boolean>>();
260
+ private quotaRepollRequested = new WeakSet<AccountRuntime>();
261
+ private quotaPollCycle: Promise<void> | null = null;
250
262
  private inFlightRefreshes = new WeakMap<AccountRuntime, Map<string, Promise<void>>>();
251
263
  private requestCursorIndex = -1;
252
264
  private requestWaiters: AccountRequestWaiter[] = [];
@@ -372,9 +384,6 @@ export class AccountRotator {
372
384
  }> = [];
373
385
  private routingDiagnostics: Record<string, RoutingModelDiagnostics> = {};
374
386
  private autoWarmupEnabled = false;
375
- // Tracks upstream models already warmed-up this poll cycle per account (email → Set<upstreamModel>).
376
- // Cleared at the start of each pollAllQuotas() to enforce the one-per-cycle guarantee.
377
- private warmupSentThisCycle = new Map<string, Set<string>>();
378
387
  // Debounced state writer: batches multiple saveState() calls within a 1s window
379
388
  // to a single disk write. Hot paths (markError, recordRequest, etc.) call
380
389
  // scheduleStateSave() instead of saveState() to avoid blocking the event loop.
@@ -576,14 +585,19 @@ export class AccountRotator {
576
585
  saved.allowFreshWindowStartsOverride ?? false;
577
586
  }
578
587
  }
579
- // Cap any stale cooldowns to 30 min max from now
588
+ // Cap generic stale cooldowns to 30 min max from now. Antigravity's
589
+ // explicit Claude/Gemini reset deadlines must survive restarts intact.
580
590
  const maxCooldown = 30 * 60 * 1000;
581
591
  const now = Date.now();
582
592
  for (const account of this.accounts) {
583
593
  for (const [model, cooldown] of Object.entries(
584
594
  account.cooldownsByModel,
585
595
  )) {
586
- if (cooldown > now + maxCooldown) {
596
+ if (
597
+ model !== "claude" &&
598
+ model !== "gemini" &&
599
+ cooldown > now + maxCooldown
600
+ ) {
587
601
  account.cooldownsByModel[model] = now + maxCooldown;
588
602
  }
589
603
  }
@@ -787,82 +801,125 @@ export class AccountRotator {
787
801
  account.lastPollByProvider = {};
788
802
  }
789
803
 
790
- private async pollAllQuotas(): Promise<void> {
791
- // Reset per-cycle warmup tracking so each poll cycle allows at most one warmup per upstream model per account.
792
- this.warmupSentThisCycle.clear();
804
+ pollAccountQuota(account: AccountRuntime): Promise<boolean> {
805
+ const inFlight = this.quotaPolls.get(account);
806
+ if (inFlight) {
807
+ this.quotaRepollRequested.add(account);
808
+ return inFlight;
809
+ }
810
+
811
+ const run = (async (): Promise<boolean> => {
812
+ let quotaPublished = false;
813
+ do {
814
+ this.quotaRepollRequested.delete(account);
815
+ quotaPublished =
816
+ (await this.pollAccountQuotaOnce(account)) || quotaPublished;
817
+ } while (this.quotaRepollRequested.has(account));
818
+ return quotaPublished;
819
+ })();
820
+
821
+ const tracked = run.finally(() => {
822
+ this.quotaPolls.delete(account);
823
+ });
824
+ this.quotaPolls.set(account, tracked);
825
+ return tracked;
826
+ }
827
+
828
+ private async pollAccountQuotaOnce(account: AccountRuntime): Promise<boolean> {
829
+ let quotaPublished = false;
830
+ try {
831
+ const quotaCtx: QuotaFetchContext = {
832
+ log: (message) => this.log(message),
833
+ markFlagged: (acc, reason, options) =>
834
+ this.markFlagged(acc, reason, options),
835
+ reportQuotaPollFlag: (acc, statusCode, errorText) =>
836
+ this.reportQuotaPollFlag(acc, statusCode, errorText),
837
+ markProviderInvalid: (acc, providerId, reason) =>
838
+ this.markProviderInvalid(acc, providerId, reason),
839
+ setProviderCooldown: (acc, providerId, durationMs) =>
840
+ this.setProviderCooldown(acc, providerId, durationMs),
841
+ };
842
+ // Parent-account model: poll quota for every provider credential
843
+ // the account holds (Google OAuth pools + Ollama usage pools).
844
+ const providerIds = new Set<string>(
845
+ (account.config.credentials ?? []).map((c) => c.provider),
846
+ );
847
+ if (providerIds.size === 0) providerIds.add(primaryProviderId(account.config));
848
+ for (const pid of providerIds) {
849
+ try {
850
+ await this.ensureValidTokenForProvider(account, pid);
851
+ await getProviderAdapter(pid).fetchQuota(account, quotaCtx);
852
+ quotaPublished = true;
853
+ } catch {
854
+ // One invalid provider credential must not suppress sibling pools.
855
+ }
856
+ }
857
+ } catch {
858
+ // Token refresh or quota fetch failed, skip this account
859
+ }
860
+
861
+ let cooldownChanged = false;
862
+ if (account.lastPollByProvider?.[DEFAULT_PROVIDER] !== undefined) {
863
+ const now = Date.now();
864
+ for (const quota of account.quota) {
865
+ if (
866
+ quota.providerId !== DEFAULT_PROVIDER ||
867
+ quota.percentRemaining !== 0 ||
868
+ !quota.resetTime
869
+ ) {
870
+ continue;
871
+ }
872
+ const resetAt = new Date(quota.resetTime).getTime();
873
+ if (
874
+ !Number.isFinite(resetAt) ||
875
+ resetAt <= now ||
876
+ account.cooldownsByModel[quota.modelKey] === resetAt
877
+ ) {
878
+ continue;
879
+ }
880
+ account.cooldownsByModel[quota.modelKey] = resetAt;
881
+ cooldownChanged = true;
882
+ }
883
+ }
884
+ if (cooldownChanged) {
885
+ this.scheduleStateSave();
886
+ this.requestWaiterDrain();
887
+ }
888
+
889
+ // Consolidated RAW POLL across all providers on this account:
890
+ // google first (Antigravity OAuth pools), then ollama (usage pools).
891
+ this.logConsolidatedPoll(account);
892
+ return quotaPublished;
893
+ }
894
+
895
+ private pollAllQuotas(): Promise<void> {
896
+ if (this.quotaPollCycle) return this.quotaPollCycle;
897
+ this.quotaPollCycle = this.pollAllQuotasOnce().finally(() => {
898
+ this.quotaPollCycle = null;
899
+ });
900
+ return this.quotaPollCycle;
901
+ }
902
+
903
+ private async pollAllQuotasOnce(): Promise<void> {
793
904
  void this.refreshOllamaCatalogOnce().catch(() => {});
794
905
 
795
906
  const available = this.accounts.filter((a) => !a.disabled && !a.flagged);
796
907
  let quotaPublished = false;
797
908
  for (const account of available) {
798
- try {
799
- const quotaCtx: QuotaFetchContext = {
800
- log: (message) => this.log(message),
801
- markFlagged: (acc, reason, options) =>
802
- this.markFlagged(acc, reason, options),
803
- reportQuotaPollFlag: (acc, statusCode, errorText) =>
804
- this.reportQuotaPollFlag(acc, statusCode, errorText),
805
- markProviderInvalid: (acc, providerId, reason) =>
806
- this.markProviderInvalid(acc, providerId, reason),
807
- setProviderCooldown: (acc, providerId, durationMs) =>
808
- this.setProviderCooldown(acc, providerId, durationMs),
809
- };
810
- // Parent-account model: poll quota for every provider credential
811
- // the account holds (Google OAuth pools + Ollama usage pools).
812
- const providerIds = new Set<string>(
813
- (account.config.credentials ?? []).map((c) => c.provider),
814
- );
815
- if (providerIds.size === 0) providerIds.add(primaryProviderId(account.config));
816
- for (const pid of providerIds) {
817
- try {
818
- await this.ensureValidTokenForProvider(account, pid);
819
- await getProviderAdapter(pid).fetchQuota(account, quotaCtx);
820
- quotaPublished = true;
821
- } catch {
822
- // One invalid provider credential must not suppress sibling pools.
823
- }
824
- }
825
- } catch {
826
- // Token refresh or quota fetch failed, skip this account
909
+ if (await this.pollAccountQuota(account)) {
910
+ quotaPublished = true;
827
911
  }
828
912
 
829
- // Consolidated RAW POLL across all providers on this account:
830
- // google first (Antigravity OAuth pools), then ollama (usage pools).
831
- this.logConsolidatedPoll(account);
832
-
833
- // Auto-warmup: send minimal kickstart requests for idle pools on accounts that have opted
834
- // in via allowFreshWindowStartsOverride, but only if the operator has enabled the global
835
- // auto-warmup toggle. "Idle" includes both fresh pools (no active timer) and rolling idle
836
- // pools (100% quota with resetTime very close to a full 5h or 7d window — timer exists but
837
- // untouched). Deduplicates by upstream model within this cycle.
913
+ // Auto-warmup reuses the bulk path so all successful kickstarts are
914
+ // followed by one account-level quota refresh, not one refresh per pool.
838
915
  if (this.autoWarmupEnabled && account.allowFreshWindowStartsOverride) {
839
- const idlePools = account.quota.filter(
840
- (q) =>
841
- this.isQuotaIdleForKickstart(q) &&
842
- this.getKickstartTarget(account, q.modelKey) !== null,
843
- );
844
- if (idlePools.length > 0) {
845
- const alreadySent =
846
- this.warmupSentThisCycle.get(account.config.email) ?? new Set<string>();
847
- const upstreamToQuotaKey = new Map<string, string>();
848
- for (const q of idlePools) {
849
- const target = this.getKickstartTarget(account, q.modelKey);
850
- if (!target) continue;
851
- const upstream = target.upstreamModel;
852
- if (!upstreamToQuotaKey.has(upstream)) {
853
- upstreamToQuotaKey.set(upstream, q.modelKey);
854
- }
855
- }
856
- for (const [upstream, quotaKey] of upstreamToQuotaKey) {
857
- if (!alreadySent.has(upstream)) {
858
- alreadySent.add(upstream);
859
- // Fire-and-forget — errors are handled internally by kickstartTimerForAccount
860
- void this.kickstartTimerForAccount(account.config.email, quotaKey).catch(
861
- () => {},
862
- );
863
- }
916
+ try {
917
+ const warmup = await this.kickstartAllFreshTimers(account.config.email);
918
+ if (warmup.results.some((result) => result.ok)) {
919
+ quotaPublished = true;
864
920
  }
865
- this.warmupSentThisCycle.set(account.config.email, alreadySent);
921
+ } catch {
922
+ // Warmup is opportunistic and must not abort the polling cycle.
866
923
  }
867
924
  }
868
925
  }
@@ -975,17 +1032,10 @@ export class AccountRotator {
975
1032
  return q?.timerType ?? "fresh";
976
1033
  }
977
1034
 
978
- // A pool is "idle for kickstart" when it has a fresh pool (no active timer)
979
- // OR a rolling idle timer (100% quota with resetTime very close to a full 5h or 7d
980
- // window — the timer exists but the quota is completely untouched). Sending a
981
- // minimal kickstart request against an idle pool starts the consumption clock.
1035
+ // A pool is "idle for kickstart" when it has a fresh pool (no active timer).
1036
+ // Sending a minimal kickstart request against an idle pool starts the consumption clock.
982
1037
  private isQuotaIdleForKickstart(q: ModelQuota): boolean {
983
- if (q.timerType === "fresh") return true;
984
- if (!q.resetTime || q.percentRemaining !== 100) return false;
985
- const remaining = new Date(q.resetTime).getTime() - Date.now();
986
- if (remaining <= 0) return false;
987
- const within = (target: number) => Math.abs(remaining - target) < 600_000;
988
- return within(5 * 3600 * 1000) || within(7 * 24 * 3600 * 1000);
1038
+ return q.timerType === "fresh";
989
1039
  }
990
1040
 
991
1041
  /**
@@ -996,22 +1046,28 @@ export class AccountRotator {
996
1046
  private getKickstartTarget(
997
1047
  account: AccountRuntime,
998
1048
  quotaModelKey: string,
999
- ): { providerId: string; adapter: ReturnType<typeof getProviderAdapter>; upstreamModel: string } | null {
1000
- const quota = account.quota.find((candidate) => candidate.modelKey === quotaModelKey);
1049
+ ): {
1050
+ poolKey: string;
1051
+ providerId: string;
1052
+ adapter: ReturnType<typeof getProviderAdapter>;
1053
+ upstreamModel: string;
1054
+ } | null {
1055
+ const poolKey = this.resolveAccountPoolKey(account, quotaModelKey);
1056
+ const quota = account.quota.find((candidate) => candidate.modelKey === poolKey);
1001
1057
  const providerId =
1002
1058
  quota?.providerId ??
1003
- (quotaModelKey === "session"
1059
+ (poolKey === "session"
1004
1060
  ? "ollama"
1005
- : quotaModelKey === CODEX_QUOTA_MODEL_KEY ||
1006
- quotaModelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
1061
+ : poolKey === CODEX_QUOTA_MODEL_KEY ||
1062
+ poolKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
1007
1063
  ? "openai-codex"
1008
1064
  : DEFAULT_PROVIDER);
1009
1065
  if (!hasCredential(account.config, providerId)) return null;
1010
1066
 
1011
1067
  const adapter = getProviderAdapter(providerId);
1012
- const upstreamModel = adapter.getKickstartModelForPool(quotaModelKey);
1068
+ const upstreamModel = adapter.getKickstartModelForPool(poolKey);
1013
1069
  if (!upstreamModel) return null;
1014
- return { providerId, adapter, upstreamModel };
1070
+ return { poolKey, providerId, adapter, upstreamModel };
1015
1071
  }
1016
1072
 
1017
1073
  // Timer priority for a specific model:
@@ -1344,13 +1400,25 @@ export class AccountRotator {
1344
1400
  now: number,
1345
1401
  activeForModels: string[],
1346
1402
  ): AccountStatus["status"] {
1347
- const inCooldownModels = Object.values(account.cooldownsByModel).filter(
1348
- (ts) => ts > now,
1349
- );
1403
+ const defaultCooldownActive =
1404
+ (account.cooldownsByModel.__default__ ?? 0) > now;
1405
+ const knownPools = new Set(account.quota.map((quota) => quota.modelKey));
1406
+ for (const [modelKey, cooldownUntil] of Object.entries(
1407
+ account.cooldownsByModel,
1408
+ )) {
1409
+ if (modelKey !== "__default__" && cooldownUntil > now) {
1410
+ knownPools.add(modelKey);
1411
+ }
1412
+ }
1413
+ const allKnownPoolsCooling =
1414
+ knownPools.size > 0 &&
1415
+ [...knownPools].every(
1416
+ (modelKey) => (account.cooldownsByModel[modelKey] ?? 0) > now,
1417
+ );
1350
1418
  if (account.flagged) return "flagged";
1351
1419
  if (account.disabled) return "disabled";
1352
1420
  if (account.consecutiveErrors > 0 && !account.disabled) return "error";
1353
- if (inCooldownModels.length > 0) return "cooldown";
1421
+ if (defaultCooldownActive || allKnownPoolsCooling) return "cooldown";
1354
1422
  if (this.isDailySafetyStopped(account, now)) return "exhausted";
1355
1423
  if (activeForModels.length > 0) return "active";
1356
1424
  return "ready";
@@ -2825,9 +2893,9 @@ export class AccountRotator {
2825
2893
  const lower = model.toLowerCase();
2826
2894
  if (lower.includes("opus")) pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
2827
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"];
2828
2897
  else if (lower.includes("3.7-flash")) pricing = MODEL_PRICING["gemini-3.7-flash-tiered"];
2829
2898
  else if (lower.includes("3.6-flash")) pricing = MODEL_PRICING["gemini-3.6-flash-high"];
2830
- else if (lower.includes("3.5-flash")) pricing = MODEL_PRICING["gemini-3.5-flash-high"];
2831
2899
  else if (lower.includes("flash")) pricing = MODEL_PRICING["gemini-3-flash"];
2832
2900
  else if (lower.includes("pro")) pricing = MODEL_PRICING["gemini-3.1-pro"];
2833
2901
  }
@@ -2883,7 +2951,7 @@ export class AccountRotator {
2883
2951
  ): void {
2884
2952
  const now = Date.now();
2885
2953
  const modelKey = model
2886
- ? (this.resolvePoolKeyForModel(model) ?? resolveQuotaModelKey(model) ?? "__default__")
2954
+ ? this.resolveAccountPoolKey(account, model)
2887
2955
  : "__default__";
2888
2956
  if (model && (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`) || isCodexRequestModel(model))) {
2889
2957
  this.setProviderCooldown(account, "openai-codex", cooldownMs);
@@ -2910,7 +2978,7 @@ export class AccountRotator {
2910
2978
  this.setProviderCooldown(account, "openai-codex", cooldownMs);
2911
2979
  return;
2912
2980
  }
2913
- const poolKey = model ? this.resolvePoolKeyForModel(model) : null;
2981
+ const poolKey = model ? this.resolveAccountPoolKey(account, model) : null;
2914
2982
  const isAccountScopedProvider =
2915
2983
  providerResourceExhausted ||
2916
2984
  (poolKey && (poolKey.startsWith("opencode-zen") || poolKey.startsWith("session")));
@@ -2923,7 +2991,7 @@ export class AccountRotator {
2923
2991
  return;
2924
2992
  }
2925
2993
  const modelKey = model
2926
- ? (this.resolvePoolKeyForModel(model) ?? resolveQuotaModelKey(model) ?? "__default__")
2994
+ ? this.resolveAccountPoolKey(account, model)
2927
2995
  : "__default__";
2928
2996
  const windowMs =
2929
2997
  this.config.projectCircuitBreakerWindowMs ?? 10 * 60 * 1000;
@@ -3509,6 +3577,21 @@ export class AccountRotator {
3509
3577
  return key;
3510
3578
  }
3511
3579
 
3580
+ /** Resolve upstream models and already-published quota keys to one account pool. */
3581
+ private resolveAccountPoolKey(account: AccountRuntime, key: string): string {
3582
+ const kickstartPool = QUOTA_POOL_FOR_KICKSTART_MODEL[key];
3583
+ if (kickstartPool) return this.resolvePoolKey(account, kickstartPool);
3584
+ if (
3585
+ Object.values(QUOTA_POOL_FOR_KICKSTART_MODEL).includes(key) ||
3586
+ account.quota.some((quota) => quota.modelKey === key) ||
3587
+ getProviderIdForPoolKey(key) !== DEFAULT_PROVIDER
3588
+ ) {
3589
+ return this.resolvePoolKey(account, key);
3590
+ }
3591
+ const modelPool = this.resolvePoolKeyForModel(key) ?? resolveQuotaModelKey(key);
3592
+ return this.resolvePoolKey(account, modelPool ?? "__default__");
3593
+ }
3594
+
3512
3595
  private isRoutableForModel(
3513
3596
  account: AccountRuntime,
3514
3597
  modelKey: string,
@@ -4246,6 +4329,7 @@ export class AccountRotator {
4246
4329
  async kickstartTimerForAccount(
4247
4330
  email: string,
4248
4331
  quotaModelKey: string,
4332
+ refreshQuota = true,
4249
4333
  ): Promise<{ ok: boolean; status: number; upstreamModel: string; error?: string }> {
4250
4334
  const account = this.accounts.find((a) => a.config.email === email);
4251
4335
  if (!account) {
@@ -4288,6 +4372,7 @@ export class AccountRotator {
4288
4372
  }
4289
4373
 
4290
4374
  const upstreamModel = target.upstreamModel;
4375
+ const poolKey = target.poolKey;
4291
4376
 
4292
4377
  const controller = new AbortController();
4293
4378
  const timeout = setTimeout(() => controller.abort(), 15_000);
@@ -4320,7 +4405,7 @@ export class AccountRotator {
4320
4405
  clearTimeout(timeout);
4321
4406
  } else {
4322
4407
  const body = JSON.stringify({
4323
- project: this.getProjectIdForModel(account, quotaModelKey),
4408
+ project: this.getProjectIdForModel(account, poolKey),
4324
4409
  model: upstreamModel,
4325
4410
  request: {
4326
4411
  contents: [{ role: "user", parts: [{ text: "." }] }],
@@ -4354,21 +4439,49 @@ export class AccountRotator {
4354
4439
  clearTimeout(timeout);
4355
4440
  }
4356
4441
 
4357
- // Consume and discard the response body to free the connection
4358
- try {
4359
- await response.body?.cancel();
4360
- } catch {
4361
- // ignore
4442
+ let errorText = "";
4443
+ if (response.status === 429) {
4444
+ errorText = await response.text().catch(() => "");
4445
+ } else {
4446
+ // Consume and discard the response body to free the connection.
4447
+ try {
4448
+ await response.body?.cancel();
4449
+ } catch {
4450
+ // ignore
4451
+ }
4362
4452
  }
4363
4453
 
4364
4454
  const label = account.config.label || account.config.email;
4365
4455
 
4366
4456
  if (response.status === 429) {
4367
- const cooldownMs = 60_000;
4368
- this.markExhausted(account, quotaModelKey, cooldownMs, "kickstart 429");
4369
- this.recordProvider429(account, quotaModelKey, cooldownMs);
4457
+ const providerResourceExhausted =
4458
+ classifyRateLimitReason(errorText, response.status) === "quota-exhausted";
4459
+ const cooldownMs = providerResourceExhausted
4460
+ ? target.providerId === DEFAULT_PROVIDER
4461
+ ? parseRetryAfterMs(
4462
+ errorText,
4463
+ response.headers,
4464
+ RESOURCE_EXHAUSTED_FALLBACK_MS,
4465
+ )
4466
+ : RESOURCE_EXHAUSTED_FALLBACK_MS
4467
+ : Math.min(
4468
+ parseRetryAfterMs(errorText, response.headers),
4469
+ RESOURCE_EXHAUSTED_FALLBACK_MS,
4470
+ );
4471
+ this.markExhausted(
4472
+ account,
4473
+ poolKey,
4474
+ cooldownMs,
4475
+ errorText || "kickstart 429",
4476
+ );
4477
+ this.recordProvider429(
4478
+ account,
4479
+ poolKey,
4480
+ cooldownMs,
4481
+ providerResourceExhausted,
4482
+ );
4370
4483
  this.log(
4371
- `${label} [${quotaModelKey}]: kickstart 429 — cooldown ${cooldownMs / 1000}s`,
4484
+ `${label} [${poolKey}]: kickstart 429 — cooldown ${cooldownMs / 1000}s`,
4372
4485
  "warn",
4373
4486
  );
4374
4487
  return { ok: false, status: 429, upstreamModel };
@@ -4389,20 +4502,28 @@ export class AccountRotator {
4389
4502
  }
4390
4503
 
4391
4504
  if (response.ok) {
4392
- this.recordRequest(account, quotaModelKey);
4505
+ this.recordRequest(account, poolKey);
4393
4506
  this.log(
4394
- `${label} [${quotaModelKey}]: kickstart sent via ${upstreamModel} — timer should start within the next quota poll`,
4507
+ `${label} [${poolKey}]: kickstart sent via ${upstreamModel} — ${refreshQuota ? "refreshing quota" : "bulk quota refresh pending"}`,
4395
4508
  );
4509
+ // Immediately re-poll the account quota so newly started resetTime and timerType
4510
+ // are captured and exposed without waiting for the background polling cycle.
4511
+ if (refreshQuota) {
4512
+ try {
4513
+ await this.pollAccountQuota(account);
4514
+ } catch {
4515
+ // non-fatal
4516
+ }
4517
+ }
4396
4518
  }
4397
4519
 
4398
4520
  return { ok: response.ok, status: response.status, upstreamModel };
4399
4521
  }
4400
4522
 
4401
4523
  /**
4402
- * Kickstart all quota pools that are currently idle (no active timer, or rolling
4403
- * idle with 100% quota and a fresh resetTime) for a given account. Deduplicates by
4404
- * upstream model so that pools sharing the same upstream (e.g. gemini-3.5-flash and
4405
- * gemini-3.1-pro → gemini-3-flash) only receive one request.
4524
+ * Kickstart all quota pools that are currently idle (no active timer)
4525
+ * for a given account. Deduplicates by upstream model so that pools
4526
+ * sharing the same upstream only receive one request.
4406
4527
  */
4407
4528
  async kickstartAllFreshTimers(email: string): Promise<{
4408
4529
  ok: boolean;
@@ -4450,10 +4571,22 @@ export class AccountRotator {
4450
4571
  // Use the primary quota pool key for this upstream (for recordRequest/markExhausted)
4451
4572
  const primaryQuotaKey =
4452
4573
  QUOTA_POOL_FOR_KICKSTART_MODEL[upstreamModel] ?? quotaPools[0];
4453
- const result = await this.kickstartTimerForAccount(email, primaryQuotaKey);
4574
+ const result = await this.kickstartTimerForAccount(
4575
+ email,
4576
+ primaryQuotaKey,
4577
+ false,
4578
+ );
4454
4579
  results.push({ quotaPools, upstreamModel, ok: result.ok, status: result.status });
4455
4580
  }
4456
4581
 
4582
+ if (results.some((result) => result.ok)) {
4583
+ try {
4584
+ await this.pollAccountQuota(account);
4585
+ } catch {
4586
+ // A failed refresh must not rewrite successful kickstart results.
4587
+ }
4588
+ }
4589
+
4457
4590
  const allOk = results.every((r) => r.ok);
4458
4591
  return { ok: allOk, results };
4459
4592
  }
@@ -260,12 +260,12 @@ export function calculateCost(model: string, promptTokens: number, completionTok
260
260
  pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
261
261
  } else if (lower.includes("sonnet")) {
262
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"];
263
265
  } else if (lower.includes("3.7-flash")) {
264
266
  pricing = MODEL_PRICING["gemini-3.7-flash-tiered"];
265
267
  } else if (lower.includes("3.6-flash")) {
266
268
  pricing = MODEL_PRICING["gemini-3.6-flash-high"];
267
- } else if (lower.includes("3.5-flash")) {
268
- pricing = MODEL_PRICING["gemini-3.5-flash-high"];
269
269
  } else if (lower.includes("flash")) {
270
270
  pricing = MODEL_PRICING["gemini-3-flash"];
271
271
  } else if (lower.includes("pro")) {
@@ -251,14 +251,15 @@ function fetchModelCatalog() {
251
251
  var FALLBACK_MODEL_CATALOG = [
252
252
  { id: "gemini-3.1-pro-low", owned_by: "tuxevil-rotator" },
253
253
  { id: "gemini-3.1-pro-high", owned_by: "tuxevil-rotator" },
254
- { id: "gemini-3.5-flash-medium", owned_by: "tuxevil-rotator" },
255
- { id: "gemini-3.5-flash-high", owned_by: "tuxevil-rotator" },
256
254
  { id: "gemini-3-flash", owned_by: "tuxevil-rotator" },
257
255
  { id: "gemini-3.6-flash-low", owned_by: "tuxevil-rotator" },
258
256
  { id: "gemini-3.6-flash-medium", owned_by: "tuxevil-rotator" },
259
257
  { id: "gemini-3.6-flash-high", owned_by: "tuxevil-rotator" },
260
258
  { id: "gemini-3.6-flash-tiered", owned_by: "tuxevil-rotator" },
261
259
  { id: "gemini-3.7-flash-tiered", owned_by: "tuxevil-rotator" },
260
+ { id: "gemini-3.8-flash-low", owned_by: "tuxevil-rotator" },
261
+ { id: "gemini-3.8-flash-medium", owned_by: "tuxevil-rotator" },
262
+ { id: "gemini-3.8-flash-high", owned_by: "tuxevil-rotator" },
262
263
  { id: "claude-sonnet-4-6", owned_by: "tuxevil-rotator" },
263
264
  { id: "claude-opus-4-6-thinking", owned_by: "tuxevil-rotator" },
264
265
  { id: "gpt-oss-120b-medium", owned_by: "tuxevil-rotator" },
@@ -531,4 +532,4 @@ if (document.readyState === "loading") {
531
532
  document.addEventListener("DOMContentLoaded", initKeysPage);
532
533
  } else {
533
534
  initKeysPage();
534
- }
535
+ }
@@ -271,8 +271,11 @@ document.addEventListener("click", function(e) {
271
271
  var availableKeys = [];
272
272
  var selectedKeyValues = [];
273
273
  var availableModels = [
274
+ { value: "gemini-3.8-flash-high", label: "gemini-3.8-flash-high" },
275
+ { value: "gemini-3.8-flash-medium", label: "gemini-3.8-flash-medium" },
276
+ { value: "gemini-3.8-flash-low", label: "gemini-3.8-flash-low" },
277
+ { value: "gemini-3.7-flash-tiered", label: "gemini-3.7-flash-tiered" },
274
278
  { value: "gemini-3.6-flash", label: "gemini-3.6-flash" },
275
- { value: "gemini-3.5-flash", label: "gemini-3.5-flash" },
276
279
  { value: "gemini-3.1-pro", label: "gemini-3.1-pro" },
277
280
  { value: "claude-sonnet-4-6", label: "claude-sonnet-4-6" },
278
281
  { value: "claude-opus-4-6-thinking", label: "claude-opus-4-6-thinking" },
@@ -794,4 +797,4 @@ if (document.readyState === "loading") {
794
797
  document.addEventListener("DOMContentLoaded", initLogsPage);
795
798
  } else {
796
799
  initLogsPage();
797
- }
800
+ }