tuxevil-rotator 3.3.0 → 3.3.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.3.2] - 2026-08-28
4
+
5
+ ### Fixed
6
+ - **Model-scoped Antigravity cooldowns**: `RESOURCE_EXHAUSTED` 429s now cool only the exhausted Claude or Gemini pool; sibling pools on the same account remain routable immediately ([#26](https://github.com/tuxevil/tuxevil-rotator/pull/26) by [@javargasm](https://github.com/javargasm)).
7
+ - **Explicit reset duration honored on `RESOURCE_EXHAUSTED`**: The rotator parses `Resets in Xh Ym Zs` from Antigravity error messages and applies that exact cooldown instead of the generic 30-minute cap. Falls back to 30 minutes when no duration is present ([#26](https://github.com/tuxevil/tuxevil-rotator/pull/26) by [@javargasm](https://github.com/javargasm)).
8
+ - **Persisted Antigravity pool deadlines survive restarts**: `claude` and `gemini` cooldown deadlines are no longer truncated to 30 minutes on startup; only generic model cooldowns are capped ([#26](https://github.com/tuxevil/tuxevil-rotator/pull/26) by [@javargasm](https://github.com/javargasm)).
9
+ - **Untouched 100% pools show idle instead of a fake countdown**: When Google reports `remainingFraction >= 1` the reset timestamp is discarded and the pool renders as `idle` with no timer ([#26](https://github.com/tuxevil/tuxevil-rotator/pull/26) by [@javargasm](https://github.com/javargasm)).
10
+ - **RAW POLL reconciliation of exhausted pool deadlines**: A successful quota poll reporting 0% with a valid future reset replaces the stale cooldown deadline for that pool; invalid, past, or unchanged resets are ignored ([#26](https://github.com/tuxevil/tuxevil-rotator/pull/26) by [@javargasm](https://github.com/javargasm)).
11
+ - **Serialized per-account quota polling with trailing repoll**: Overlapping `pollAccountQuota` calls for the same account queue a single trailing repoll instead of running concurrently; `pollAllQuotas` is now single-flighted ([#26](https://github.com/tuxevil/tuxevil-rotator/pull/26) by [@javargasm](https://github.com/javargasm)).
12
+ - **`gpt-oss:20b` kickstarts routed through Ollama**: On multi-provider accounts (Google + Ollama), the kickstart for the Ollama session pool is correctly sent to the Ollama endpoint with the Ollama API key ([#26](https://github.com/tuxevil/tuxevil-rotator/pull/26) by [@javargasm](https://github.com/javargasm)).
13
+ - **Kickstart actions hidden for disabled/flagged accounts**: The dashboard no longer renders `▶ Start` or `Start Idle Timers` buttons for accounts that are not eligible for kickstart ([#26](https://github.com/tuxevil/tuxevil-rotator/pull/26) by [@javargasm](https://github.com/javargasm)).
14
+ - **`gemini-3.7-flash-tiered` added to OpenCode integration docs**: Context window updated to 1,000,000 tokens; set as the recommended default model ([#26](https://github.com/tuxevil/tuxevil-rotator/pull/26) by [@javargasm](https://github.com/javargasm)).
15
+
16
+ ## [3.3.1] - 2026-08-27
17
+
18
+ ### Fixed
19
+ - **Admin token propagation on hosted login**: Propagate the configured admin token to the "Continue With Google" link on the `/login` landing page, preventing a 401 Unauthorized error when navigating to `/auth/antigravity/start` ([#25](https://github.com/tuxevil/tuxevil-rotator/pull/25) by [@CelestialCreator](https://github.com/CelestialCreator)).
20
+
3
21
  ## [3.3.0] - 2026-08-24
4
22
 
5
23
  ### Added
package/README.md CHANGED
@@ -339,11 +339,12 @@ To donate an authorized account for testing across supported providers, see [CON
339
339
 
340
340
  Thanks to these amazing people who have contributed to the project:
341
341
 
342
+ - **[@CelestialCreator](https://github.com/CelestialCreator)** (Akshay) — Fixed admin token propagation on the hosted login landing page (`/login` to `/auth/antigravity/start`). ([PR #25](https://github.com/tuxevil/tuxevil-rotator/pull/25))
342
343
  - **[@Codder-hermes](https://github.com/Codder-hermes)** — Fixed Claude Code tool-schema requests by stripping the unsupported JSON Schema `propertyNames` keyword for Gemini and Claude-via-Gemini routes, with regression coverage for both compatibility paths. ([PR #19](https://github.com/tuxevil/tuxevil-rotator/pull/19))
343
344
  - **[@CyR1en](https://github.com/CyR1en)** (Ethan Bacurio) — Added Gemini 3.6 Flash and Gemini 3.7 Flash model families, shared quota-pool routing, pricing, dashboard support, and regression coverage. ([PR #18](https://github.com/tuxevil/tuxevil-rotator/pull/18), [PR #21](https://github.com/tuxevil/tuxevil-rotator/pull/21))
344
345
  - **[@josenicomaia](https://github.com/josenicomaia)** (José Nicodemos Maia Neto) — Modularized the compatibility layer architecture, added multimodal tool response support, fixed streaming pass-through for tool executions, and added PostgreSQL storage and weighted pool quota forecasting. ([PR #8](https://github.com/tuxevil/tuxevil-rotator/pull/8), [PR #9](https://github.com/tuxevil/tuxevil-rotator/pull/9), [PR #11](https://github.com/tuxevil/tuxevil-rotator/pull/11), [PR #13](https://github.com/tuxevil/tuxevil-rotator/pull/13), [PR #14](https://github.com/tuxevil/tuxevil-rotator/pull/14))
345
346
  - **[@yashyadav711](https://github.com/yashyadav711)** (Yash) — Fixed Draft-2020-12 inline JSON-Schema union type mapping for Gemini tools support. ([PR #10](https://github.com/tuxevil/tuxevil-rotator/pull/10))
346
- - **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Queued multi-request Antigravity account pooling (5×5 concurrent streams), strict FIFO overflow queue, dashboard concurrency metrics, canonical project ID resolution, 429 quota resilience with account-scoped retry, synchronous leasing, snapshot-based token refresh with generation validation, provider-scoped token publication, spend-logger memory leak fix, atomic PostgreSQL CTE daily spend aggregation with idempotent retries, virtual-key cache bounding, Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, and compat test suite expansion. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7), [PR #22](https://github.com/tuxevil/tuxevil-rotator/pull/22), [PR #23](https://github.com/tuxevil/tuxevil-rotator/pull/23), [PR #24](https://github.com/tuxevil/tuxevil-rotator/pull/24))
347
+ - **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Queued multi-request Antigravity account pooling (5×5 concurrent streams), strict FIFO overflow queue, dashboard concurrency metrics, canonical project ID resolution, 429 quota resilience with account-scoped retry, synchronous leasing, snapshot-based token refresh with generation validation, provider-scoped token publication, spend-logger memory leak fix, atomic PostgreSQL CTE daily spend aggregation with idempotent retries, virtual-key cache bounding, Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, compat test suite expansion, model-scoped cooldowns, explicit Antigravity reset-duration parsing, idle pool normalization, RAW POLL deadline reconciliation, serialized per-account quota polling, and Ollama kickstart routing for multi-provider accounts. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7), [PR #22](https://github.com/tuxevil/tuxevil-rotator/pull/22), [PR #23](https://github.com/tuxevil/tuxevil-rotator/pull/23), [PR #24](https://github.com/tuxevil/tuxevil-rotator/pull/24), [PR #26](https://github.com/tuxevil/tuxevil-rotator/pull/26))
347
348
 
348
349
  ## Development
349
350
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "3.3.0",
3
+ "version": "3.3.2",
4
4
  "description": "Multi-provider, multi-account AI proxy rotator with per-model routing, real-time quota tracking, and infringement detection (Google Antigravity, Ollama Cloud)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -45,7 +45,7 @@
45
45
  "type": "git",
46
46
  "url": "git+https://github.com/tuxevil/tuxevil-rotator.git"
47
47
  },
48
- "author": "Sebasti\u00e1n Real (tuxevil)",
48
+ "author": "Sebastián Real (tuxevil)",
49
49
  "dependencies": {
50
50
  "pg": "^8.22.0",
51
51
  "tsx": "^4.22.4",
package/src/dashboard.ts CHANGED
@@ -281,17 +281,17 @@ export function serveKickstartApi(
281
281
  rotator.kickstartTimerForAccount(email, modelKey).then((result) => {
282
282
  res.writeHead(200, { "Content-Type": "application/json" });
283
283
  res.end(JSON.stringify(result));
284
- }).catch((err) => {
284
+ }).catch(() => {
285
285
  res.writeHead(500, { "Content-Type": "application/json" });
286
- res.end(JSON.stringify({ ok: false, error: String(err) }));
286
+ res.end(JSON.stringify({ ok: false, error: "Kickstart failed" }));
287
287
  });
288
288
  } else {
289
289
  rotator.kickstartAllFreshTimers(email).then((result) => {
290
290
  res.writeHead(200, { "Content-Type": "application/json" });
291
291
  res.end(JSON.stringify(result));
292
- }).catch((err) => {
292
+ }).catch(() => {
293
293
  res.writeHead(500, { "Content-Type": "application/json" });
294
- res.end(JSON.stringify({ ok: false, error: String(err), results: [] }));
294
+ res.end(JSON.stringify({ ok: false, error: "Kickstart failed", results: [] }));
295
295
  });
296
296
  }
297
297
  }
package/src/onboarding.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { getConfiguredAdminToken } from "./admin-auth.js";
2
3
  import { addAccountToConfig } from "./account-store.js";
3
4
  import { PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
4
5
  import {
@@ -231,11 +232,17 @@ function renderPage(title: string, body: string): string {
231
232
  export function serveLoginLanding(res: ServerResponse): void {
232
233
  const hostedReady = isHostedOAuthConfigured();
233
234
  const oauth = hostedReady ? getOAuthClientConfig() : null;
235
+ // The start route is admin-gated, so carry the token through — the page
236
+ // itself is only reachable with a valid token anyway.
237
+ const adminToken = getConfiguredAdminToken();
238
+ const startHref = adminToken
239
+ ? `/auth/antigravity/start?token=${encodeURIComponent(adminToken)}`
240
+ : "/auth/antigravity/start";
234
241
  const message = hostedReady
235
242
  ? `<p>This page starts the Antigravity sign-in flow and returns here automatically so the account can be added to this rotator.</p>
236
243
  <p class="mono">Configured callback: ${escapeHtml(oauth?.redirectUri)}</p>
237
244
  <div class="note">Signing in here grants this server a refresh token for the selected Google account. That allows the rotator to keep using that account until access is revoked.</div>
238
- <a class="cta" href="/auth/antigravity/start">Continue With Google</a>`
245
+ <a class="cta" href="${startHref}">Continue With Google</a>`
239
246
  : `<p>This server is not yet configured for hosted OAuth.</p>
240
247
  <p class="mono">Set ANTIGRAVITY_REDIRECT_URI, and usually ANTIGRAVITY_CLIENT_ID plus ANTIGRAVITY_CLIENT_SECRET, to a public callback URL registered with the OAuth client.</p>
241
248
  <div class="note error">The current redirect is still loopback-only, so the transparent public callback cannot complete yet.</div>`;
@@ -162,7 +162,10 @@ export const googleAntigravityAdapter: ProviderAdapter = {
162
162
  createStreamAccumulator: createGoogleStreamAccumulator,
163
163
 
164
164
  getKickstartModelForPool(quotaModelKey: string): string | undefined {
165
- return KICKSTART_MODEL_FOR_QUOTA_POOL[quotaModelKey];
165
+ return (
166
+ KICKSTART_MODEL_FOR_QUOTA_POOL[quotaModelKey] ??
167
+ KICKSTART_MODEL_FOR_QUOTA_POOL[resolveQuotaModelKey(quotaModelKey) ?? ""]
168
+ );
166
169
  },
167
170
 
168
171
  ownsModel(model: string): boolean {
@@ -39,7 +39,11 @@ export function extractQuotas(
39
39
  }
40
40
 
41
41
  if (modelInfo?.quotaInfo) {
42
- const resetTime = modelInfo.quotaInfo.resetTime ?? null;
42
+ const remainingFraction = modelInfo.quotaInfo.remainingFraction ?? 0;
43
+ // Google can publish a nominal reset for an untouched pool; no usage means
44
+ // there is no active quota window yet.
45
+ const resetTime =
46
+ remainingFraction >= 1 ? null : modelInfo.quotaInfo.resetTime ?? null;
43
47
  let timerType: ModelQuota["timerType"] = "fresh";
44
48
 
45
49
  if (resetTime) {
@@ -63,9 +67,7 @@ export function extractQuotas(
63
67
  quotas.push({
64
68
  modelKey: config.key,
65
69
  displayName: config.display,
66
- percentRemaining: Math.round(
67
- (modelInfo.quotaInfo.remainingFraction ?? 0) * 100,
68
- ),
70
+ percentRemaining: Math.round(remainingFraction * 100),
69
71
  resetTime,
70
72
  timerType,
71
73
  });
@@ -27,6 +27,8 @@ const OLLAMA_TIER_RANKING = {
27
27
  unknown: 4,
28
28
  };
29
29
 
30
+ const OLLAMA_KICKSTART_MODEL = "gpt-oss:20b";
31
+
30
32
  export const ollamaAdapter: ProviderAdapter = {
31
33
  id: "ollama",
32
34
  displayName: "Ollama Cloud",
@@ -74,11 +76,12 @@ export const ollamaAdapter: ProviderAdapter = {
74
76
 
75
77
  getKickstartModelForPool(quotaModelKey: string): string | undefined {
76
78
  // Only the session pool can be kickstarted for Ollama accounts.
77
- return quotaModelKey === "session" ? "gpt-oss:20b" : undefined;
79
+ return quotaModelKey === "session" ? OLLAMA_KICKSTART_MODEL : undefined;
78
80
  },
79
81
 
80
82
  ownsModel(model: string, context?: { ollamaModels?: Set<string> }): boolean {
81
- return context?.ollamaModels?.has(model) ?? false;
83
+ return model === OLLAMA_KICKSTART_MODEL ||
84
+ (context?.ollamaModels?.has(model) ?? false);
82
85
  },
83
86
 
84
87
  getPoolKey(): string {
package/src/proxy.ts CHANGED
@@ -150,6 +150,7 @@ import { applyConfigDefaults } from "./account-store.js";
150
150
  import {
151
151
  classifyRateLimitReason,
152
152
  parseRetryAfterMs,
153
+ RESOURCE_EXHAUSTED_FALLBACK_MS,
153
154
  } from "./rate-limit-parser.js";
154
155
  import { authenticateVirtualKey, sendAuthErrorResponse } from "./key-auth.js";
155
156
  import { logSpend } from "./spend-logger.js";
@@ -160,7 +161,6 @@ const GENERIC_UPSTREAM_ERROR = "Upstream request failed";
160
161
 
161
162
  const DEFAULT_STREAM_RECOVERY_MAX_RETRIES = 2;
162
163
  const MAX_COOLDOWN_MS = 30 * 60 * 1000; // 30 minutes max cooldown
163
- const RESOURCE_EXHAUSTED_COOLDOWN_MS = 30 * 60 * 1000; // Stop hammering provider-side daily/request buckets
164
164
  const STREAM_IDLE_TIMEOUT_MS = 2 * 60 * 1000; // Release account if a stream goes silent.
165
165
  const LARGE_CONTEXT_WARN_BYTES = 1 * 1024 * 1024;
166
166
 
@@ -299,13 +299,20 @@ export async function classifyUpstreamResponse(
299
299
  account: AccountRuntime,
300
300
  model: string,
301
301
  modelKey: string,
302
+ providerId = DEFAULT_PROVIDER,
302
303
  ): Promise<UpstreamAction> {
303
304
  if (response.status === 429) {
304
305
  const errorText = await response.text().catch(() => "");
305
306
  const rateLimitReason = classifyRateLimitReason(errorText, response.status);
306
307
  const providerResourceExhausted = rateLimitReason === "quota-exhausted";
307
308
  const cooldownMs = providerResourceExhausted
308
- ? RESOURCE_EXHAUSTED_COOLDOWN_MS
309
+ ? providerId === DEFAULT_PROVIDER
310
+ ? parseRetryAfterMs(
311
+ errorText,
312
+ response.headers,
313
+ RESOURCE_EXHAUSTED_FALLBACK_MS,
314
+ )
315
+ : RESOURCE_EXHAUSTED_FALLBACK_MS
309
316
  : capCooldown(parseRetryAfterMs(errorText, response.headers));
310
317
  return {
311
318
  kind: "rate-limited",
@@ -1248,6 +1255,7 @@ export async function withRotation<T>(
1248
1255
  account,
1249
1256
  model,
1250
1257
  modelKey,
1258
+ provider.id,
1251
1259
  );
1252
1260
 
1253
1261
  if (action.kind !== "success") {
@@ -1680,6 +1688,7 @@ async function handleProxyRequest(
1680
1688
  account,
1681
1689
  body.model,
1682
1690
  modelKey,
1691
+ provider.id,
1683
1692
  );
1684
1693
 
1685
1694
  if (action.kind !== "success") {
@@ -1,5 +1,7 @@
1
1
  export type RateLimitReason = "rate-limit" | "quota-exhausted" | "model-capacity" | "server-error" | "unknown";
2
2
 
3
+ export const RESOURCE_EXHAUSTED_FALLBACK_MS = 30 * 60 * 1000;
4
+
3
5
  function parseDurationToMs(errorText: string): number | null {
4
6
  const durationMatch = errorText.match(/(?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i);
5
7
  if (!durationMatch) return null;
@@ -7,7 +9,8 @@ function parseDurationToMs(errorText: string): number | null {
7
9
  const minutes = durationMatch[2] ? parseInt(durationMatch[2], 10) : 0;
8
10
  const seconds = parseFloat(durationMatch[3]);
9
11
  if (!Number.isFinite(seconds)) return null;
10
- return Math.ceil(((hours * 60 + minutes) * 60 + seconds) * 1000);
12
+ const durationMs = ((hours * 60 + minutes) * 60 + seconds) * 1000;
13
+ return Number.isFinite(durationMs) ? Math.ceil(durationMs) : null;
11
14
  }
12
15
 
13
16
  export function classifyRateLimitReason(errorText: string, status?: number): RateLimitReason {
@@ -54,7 +57,11 @@ export function classifyRateLimitReason(errorText: string, status?: number): Rat
54
57
  return "unknown";
55
58
  }
56
59
 
57
- export function parseRetryAfterMs(errorText: string, headers: Headers): number {
60
+ export function parseRetryAfterMs(
61
+ errorText: string,
62
+ headers: Headers,
63
+ fallbackMs = 60_000,
64
+ ): number {
58
65
  const retryAfter = headers.get("retry-after");
59
66
  if (retryAfter) {
60
67
  const seconds = Number(retryAfter);
@@ -123,5 +130,7 @@ export function parseRetryAfterMs(errorText: string, headers: Headers): number {
123
130
  const duration = parseDurationToMs(errorText);
124
131
  if (duration && duration > 0) return Math.ceil(duration + 1000);
125
132
 
126
- return 60_000;
133
+ return Number.isFinite(fallbackMs) && fallbackMs > 0
134
+ ? Math.ceil(fallbackMs)
135
+ : 60_000;
127
136
  }
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";
@@ -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
  }
@@ -25,29 +25,23 @@ function timerDisplayLabel(timerType) {
25
25
  return timerType === "fresh" ? "idle" : timerType;
26
26
  }
27
27
 
28
- // A pool is "idle" (worth kickstarting) when either:
29
- // 1. The server reports timerType === "fresh" (no active timer at all), or
30
- // 2. Google is showing a "rolling" timer: 100% quota AND remaining time is
31
- // very close to a full 5h or 7d window (the timer exists but hasn't been
32
- // touched yet — a kickstart request will start consuming from it).
33
- function isIdleForKickstart(q, now) {
34
- if (q.timerType === "fresh") return true;
35
- if (!q.resetTime || q.percentRemaining !== 100) return false;
36
- var remaining = new Date(q.resetTime).getTime() - now;
37
- if (remaining <= 0) return false;
38
- var isRolling5h = Math.abs(remaining - 5 * 3600000) < 600000;
39
- var isRolling7d = Math.abs(remaining - 7 * 86400000) < 600000;
40
- return isRolling5h || isRolling7d;
28
+ // A pool is "idle" (worth kickstarting) when it has no active timer running (fresh).
29
+ function isIdleForKickstart(q) {
30
+ return q.timerType === "fresh";
41
31
  }
42
32
 
43
33
  function isKickstartSupported(q) {
44
34
  if (!q) return false;
45
- if (q.providerId === "openai-codex") return false;
35
+ if (q.providerId === "openai-codex" || q.providerId === "opencode-zen") return false;
36
+ if (q.providerId === "ollama" && q.modelKey !== "session") return false;
46
37
  var key = String(q.modelKey || "");
47
38
  return (
48
39
  key !== "openai-codex" &&
49
40
  key !== "openai-codex-spark" &&
50
- key.indexOf("openai-codex:") !== 0
41
+ key.indexOf("openai-codex:") !== 0 &&
42
+ key !== "opencode-zen" &&
43
+ key.indexOf("opencode-zen:") !== 0 &&
44
+ key !== "weekly"
51
45
  );
52
46
  }
53
47
 
@@ -76,32 +70,44 @@ function renderQuotaBars(account) {
76
70
  var sortedQuota = quota.slice().sort(function (a, b) {
77
71
  return getQuotaItemProviderRank(a) - getQuotaItemProviderRank(b);
78
72
  });
79
- var now = Date.now();
73
+ var accountInactive = account.status === "disabled" || account.status === "flagged";
80
74
  var rows = sortedQuota
81
75
  .map(function (q) {
82
76
  var inFlightForModel = (account.inFlightByModel || {})[q.modelKey] || 0;
83
- var clearButton =
84
- inFlightForModel > 0
85
- ? '<button class="btn-clear-flight" title="Clear in-flight counter for ' +
86
- escapeHtml(q.displayName) +
87
- '" onclick="clearInFlight(\'' +
88
- jsString(account.email) +
89
- "', '" +
90
- jsString(q.modelKey) +
91
- "')\">" +
92
- "Clear</button>"
93
- : '<button class="btn-clear-flight" title="No in-flight requests for ' +
94
- escapeHtml(q.displayName) +
95
- '" disabled>Clear</button>';
96
- var idle = isKickstartSupported(q) && isIdleForKickstart(q, now);
97
- var kickstartBtn = "";
77
+ var idle =
78
+ !accountInactive && isKickstartSupported(q) && isIdleForKickstart(q);
79
+ var actionButton = "";
80
+ if (inFlightForModel > 0) {
81
+ actionButton =
82
+ '<button class="btn-clear-flight" title="Clear in-flight counter for ' +
83
+ escapeHtml(q.displayName) +
84
+ '" onclick="clearInFlight(\'' +
85
+ jsString(account.email) +
86
+ "', '" +
87
+ jsString(q.modelKey) +
88
+ "')\">" +
89
+ "Clear</button>";
90
+ } else if (idle) {
91
+ actionButton =
92
+ '<button class="btn-clear-flight" title="Send minimal request to start idle timer for ' +
93
+ escapeHtml(q.displayName) +
94
+ '" onclick="kickstartTimer(\'' +
95
+ jsString(account.email) +
96
+ "', '" +
97
+ jsString(q.modelKey) +
98
+ "')\">▶ Start</button>";
99
+ } else {
100
+ actionButton =
101
+ '<button class="btn-clear-flight" title="No in-flight requests for ' +
102
+ escapeHtml(q.displayName) +
103
+ '" disabled>Clear</button>';
104
+ }
98
105
  var color = quotaBarColor(q.percentRemaining);
99
106
  var timerClass = "timer-" + q.timerType;
100
107
  var resetLabel = "";
101
- if (idle && q.resetTime && q.timerType !== "fresh") {
102
- // Rolling idle timer already has resetTime set; show "idle" label
108
+ if (q.timerType === "fresh") {
103
109
  resetLabel = '<span style="color:var(--text-dim)">idle</span>';
104
- } else if (q.resetTime && q.timerType !== "fresh") {
110
+ } else if (q.resetTime) {
105
111
  var remaining = new Date(q.resetTime).getTime() - Date.now();
106
112
  if (remaining > 0) {
107
113
  resetLabel = formatDuration(remaining);
@@ -126,8 +132,7 @@ function renderQuotaBars(account) {
126
132
  (resetLabel || "--") +
127
133
  "</span>" +
128
134
  '<span class="quota-action">' +
129
- clearButton +
130
- kickstartBtn +
135
+ actionButton +
131
136
  "</span>" +
132
137
  "</div>"
133
138
  );
@@ -494,8 +499,10 @@ function renderAccounts(data) {
494
499
  ? "Use Global Fresh Policy"
495
500
  : "Allow Fresh On This Account") +
496
501
  "</button>" +
497
- ((a.quota || []).some(function (q) {
498
- return isKickstartSupported(q) && isIdleForKickstart(q, Date.now());
502
+ (a.status !== "disabled" &&
503
+ a.status !== "flagged" &&
504
+ (a.quota || []).some(function (q) {
505
+ return isKickstartSupported(q) && isIdleForKickstart(q);
499
506
  })
500
507
  ? '<button class="btn-enable" onclick="kickstartAllTimers(\'' +
501
508
  jsString(a.email) +
@@ -2809,6 +2816,16 @@ async function kickstartAllTimers(email) {
2809
2816
  alert("Kickstart failed: " + data.error);
2810
2817
  } else if (data.results && data.results.length === 0) {
2811
2818
  alert("No idle timers found for this account.");
2819
+ } else if (!data.ok) {
2820
+ var failed = (data.results || []).filter(function (r) {
2821
+ return !r.ok;
2822
+ });
2823
+ var details = failed
2824
+ .map(function (r) {
2825
+ return r.upstreamModel + " (status " + r.status + ")";
2826
+ })
2827
+ .join(", ");
2828
+ alert("Kickstart partially failed: " + (details || "unknown error"));
2812
2829
  }
2813
2830
  refresh();
2814
2831
  }
package/src/types.ts CHANGED
@@ -879,13 +879,11 @@ export const ANTIGRAVITY_ENDPOINTS = [
879
879
  ] as const;
880
880
 
881
881
  // Maps each quota pool key (Google quota API) to the cheapest upstream model
882
- // used for kickstart warmup requests. Gemini 3.6/3.5 Flash and Gemini 3.1 Pro
883
- // share the same upstream pool, so all map to gemini-3-flash.
882
+ // used for kickstart warmup requests. The pool key is the canonical family key
883
+ // from QUOTA_MODEL_KEYS (i.e. "claude" or "gemini"), not an altKey/request model name.
884
884
  export const KICKSTART_MODEL_FOR_QUOTA_POOL: Record<string, string> = {
885
- "claude-opus-4-6-thinking": "gpt-oss-120b-medium",
886
- "gemini-3.5-flash": "gemini-3-flash",
887
- "gemini-3.6-flash": "gemini-3-flash",
888
- "gemini-3.1-pro": "gemini-3-flash",
885
+ "claude": "gpt-oss-120b-medium",
886
+ "gemini": "gemini-3-flash",
889
887
  };
890
888
 
891
889
  export const QUOTA_API_URL =