tuxevil-rotator 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +773 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -0
  4. package/bin/pi-antigravity-rotator.js +27 -0
  5. package/bin/tuxevil-rotator.js +5 -0
  6. package/package.json +63 -0
  7. package/src/account-store.ts +542 -0
  8. package/src/admin-auth.ts +126 -0
  9. package/src/body-limit.ts +52 -0
  10. package/src/cli.ts +293 -0
  11. package/src/compat/cache.ts +38 -0
  12. package/src/compat/model-specs.ts +82 -0
  13. package/src/compat/schema-sanitizer.ts +284 -0
  14. package/src/compat.ts +2357 -0
  15. package/src/compression/index.ts +92 -0
  16. package/src/compression/lite.ts +210 -0
  17. package/src/compression/preservation.ts +183 -0
  18. package/src/compression/rtk/command-detector.ts +170 -0
  19. package/src/compression/rtk/deduplicator.ts +39 -0
  20. package/src/compression/rtk/filter-loader.ts +84 -0
  21. package/src/compression/rtk/filter-types.ts +25 -0
  22. package/src/compression/rtk/filters/aws.json +34 -0
  23. package/src/compression/rtk/filters/biome.json +35 -0
  24. package/src/compression/rtk/filters/build-eslint.json +37 -0
  25. package/src/compression/rtk/filters/build-typescript.json +33 -0
  26. package/src/compression/rtk/filters/build-vite.json +41 -0
  27. package/src/compression/rtk/filters/build-webpack.json +34 -0
  28. package/src/compression/rtk/filters/bundle-install.json +35 -0
  29. package/src/compression/rtk/filters/composer.json +81 -0
  30. package/src/compression/rtk/filters/curl.json +34 -0
  31. package/src/compression/rtk/filters/df.json +34 -0
  32. package/src/compression/rtk/filters/docker-build.json +78 -0
  33. package/src/compression/rtk/filters/docker-logs.json +42 -0
  34. package/src/compression/rtk/filters/docker-ps.json +33 -0
  35. package/src/compression/rtk/filters/dotnet.json +47 -0
  36. package/src/compression/rtk/filters/du.json +33 -0
  37. package/src/compression/rtk/filters/error-stacktrace.json +41 -0
  38. package/src/compression/rtk/filters/gcloud.json +34 -0
  39. package/src/compression/rtk/filters/generic-output.json +32 -0
  40. package/src/compression/rtk/filters/gh.json +98 -0
  41. package/src/compression/rtk/filters/git-branch.json +45 -0
  42. package/src/compression/rtk/filters/git-diff.json +33 -0
  43. package/src/compression/rtk/filters/git-log.json +33 -0
  44. package/src/compression/rtk/filters/git-status.json +40 -0
  45. package/src/compression/rtk/filters/golangci-lint.json +34 -0
  46. package/src/compression/rtk/filters/gradle.json +47 -0
  47. package/src/compression/rtk/filters/json-output.json +40 -0
  48. package/src/compression/rtk/filters/kubectl.json +99 -0
  49. package/src/compression/rtk/filters/make.json +38 -0
  50. package/src/compression/rtk/filters/mypy.json +34 -0
  51. package/src/compression/rtk/filters/npm-audit.json +43 -0
  52. package/src/compression/rtk/filters/npm-install.json +41 -0
  53. package/src/compression/rtk/filters/nx.json +34 -0
  54. package/src/compression/rtk/filters/pip.json +41 -0
  55. package/src/compression/rtk/filters/playwright.json +42 -0
  56. package/src/compression/rtk/filters/poetry-install.json +35 -0
  57. package/src/compression/rtk/filters/prettier.json +40 -0
  58. package/src/compression/rtk/filters/ps.json +34 -0
  59. package/src/compression/rtk/filters/rsync.json +33 -0
  60. package/src/compression/rtk/filters/rubocop.json +34 -0
  61. package/src/compression/rtk/filters/ruff.json +40 -0
  62. package/src/compression/rtk/filters/shell-find.json +33 -0
  63. package/src/compression/rtk/filters/shell-grep.json +37 -0
  64. package/src/compression/rtk/filters/shell-ls.json +33 -0
  65. package/src/compression/rtk/filters/ssh.json +43 -0
  66. package/src/compression/rtk/filters/systemctl-status.json +43 -0
  67. package/src/compression/rtk/filters/terraform-plan.json +34 -0
  68. package/src/compression/rtk/filters/test-cargo.json +42 -0
  69. package/src/compression/rtk/filters/test-go.json +41 -0
  70. package/src/compression/rtk/filters/test-jest.json +43 -0
  71. package/src/compression/rtk/filters/test-pytest.json +41 -0
  72. package/src/compression/rtk/filters/test-vitest.json +43 -0
  73. package/src/compression/rtk/filters/tofu-plan.json +34 -0
  74. package/src/compression/rtk/filters/turbo.json +34 -0
  75. package/src/compression/rtk/filters/uv-sync.json +35 -0
  76. package/src/compression/rtk/filters/wget.json +34 -0
  77. package/src/compression/rtk/index.ts +103 -0
  78. package/src/compression/rtk/line-filter.ts +124 -0
  79. package/src/compression/rtk/smart-truncate.ts +71 -0
  80. package/src/config-defaults.ts +93 -0
  81. package/src/config-normalize.ts +48 -0
  82. package/src/config-storage.ts +21 -0
  83. package/src/dashboard.ts +1169 -0
  84. package/src/db-store.ts +188 -0
  85. package/src/doctor.ts +115 -0
  86. package/src/env.ts +15 -0
  87. package/src/exposure.ts +17 -0
  88. package/src/fetch-with-retry.ts +93 -0
  89. package/src/idempotency.ts +137 -0
  90. package/src/index.ts +267 -0
  91. package/src/key-auth.ts +159 -0
  92. package/src/key-migrations.ts +84 -0
  93. package/src/logger.ts +92 -0
  94. package/src/login.ts +48 -0
  95. package/src/notification-poller.ts +155 -0
  96. package/src/onboarding.ts +754 -0
  97. package/src/paths.ts +153 -0
  98. package/src/providers/adapter.ts +131 -0
  99. package/src/providers/credential-helpers.ts +72 -0
  100. package/src/providers/google-antigravity/code-assist.ts +161 -0
  101. package/src/providers/google-antigravity/credentials.ts +24 -0
  102. package/src/providers/google-antigravity/forward.ts +424 -0
  103. package/src/providers/google-antigravity/index.ts +168 -0
  104. package/src/providers/google-antigravity/login.ts +285 -0
  105. package/src/providers/google-antigravity/oauth.ts +314 -0
  106. package/src/providers/google-antigravity/quota.ts +152 -0
  107. package/src/providers/google-antigravity/translators.ts +1663 -0
  108. package/src/providers/ollama/api-key-validation.ts +59 -0
  109. package/src/providers/ollama/credentials.ts +28 -0
  110. package/src/providers/ollama/forward.ts +306 -0
  111. package/src/providers/ollama/index.ts +85 -0
  112. package/src/providers/ollama/login.ts +55 -0
  113. package/src/providers/ollama/prediction.ts +188 -0
  114. package/src/providers/ollama/quota-poll-store.ts +160 -0
  115. package/src/providers/ollama/quota.ts +189 -0
  116. package/src/providers/ollama/translators.ts +256 -0
  117. package/src/providers/ollama/usage-windows.ts +48 -0
  118. package/src/providers/proxy-dispatcher.ts +269 -0
  119. package/src/providers/registry.ts +70 -0
  120. package/src/proxy.ts +2446 -0
  121. package/src/rate-limit-parser.ts +126 -0
  122. package/src/response-headers.ts +98 -0
  123. package/src/responses-store.ts +159 -0
  124. package/src/rotator.ts +3614 -0
  125. package/src/settings-repository.ts +327 -0
  126. package/src/spend-logger.ts +696 -0
  127. package/src/static/dashboard-keys.js +384 -0
  128. package/src/static/dashboard-logs.js +797 -0
  129. package/src/static/dashboard.css +2740 -0
  130. package/src/static/dashboard.js +3177 -0
  131. package/src/storage.ts +105 -0
  132. package/src/systemd-env.ts +214 -0
  133. package/src/telemetry.ts +384 -0
  134. package/src/token-encryption.ts +199 -0
  135. package/src/types.ts +897 -0
  136. package/src/validators.ts +218 -0
  137. package/src/version-check.ts +225 -0
  138. package/src/virtual-keys.ts +312 -0
  139. package/tools/telemetry-receiver/README.md +147 -0
  140. package/tools/telemetry-receiver/package.json +13 -0
  141. package/tools/telemetry-receiver/receiver.js +2334 -0
  142. package/tuxevil-rotator_logo.png +0 -0
package/src/rotator.ts ADDED
@@ -0,0 +1,3614 @@
1
+ // Account rotation and token management with per-model routing
2
+
3
+ import {
4
+ type AccountConfig,
5
+ type AccountRuntime,
6
+ type AccountStatus,
7
+ type AccountTier,
8
+ type Config,
9
+ type HealthScoreBreakdown,
10
+ type ModelQuota,
11
+ type ModelRotationState,
12
+ type PersistedState,
13
+ type RoutingAccountDiagnostic,
14
+ type RoutingModelDiagnostics,
15
+ type RoutingRejectionReason,
16
+ type StatusResponse,
17
+ type TokenBucket,
18
+ type TokenUsageData,
19
+ type TokenUsageTiered,
20
+ MODEL_PRICING,
21
+ MODEL_TIER_ACCESS,
22
+ QUOTA_USER_AGENT,
23
+ REQUEST_GOOG_API_CLIENT,
24
+ REQUEST_CLIENT_METADATA,
25
+ ANTIGRAVITY_ENDPOINTS,
26
+ KICKSTART_MODEL_FOR_QUOTA_POOL,
27
+ OLLAMA_TAGS_URL,
28
+ OLLAMA_USER_AGENT,
29
+ TAGS_CACHE_TTL_MS,
30
+ DEFAULT_QUOTA_POLL_INTERVAL_MS,
31
+ MAX_QUOTA_POLL_INTERVAL_MS,
32
+ MIN_QUOTA_POLL_INTERVAL_MS,
33
+ resolveQuotaModelKey,
34
+ resolveDisplayModelKey,
35
+ } from "./types.js";
36
+ import {
37
+ reportFlagEvent,
38
+ FLAG_PATTERNS,
39
+ type FlagEventData,
40
+ } from "./telemetry.js";
41
+ import {
42
+ applyConfigDefaults,
43
+ saveAccountsConfig,
44
+ removeAccountFromConfig,
45
+ } from "./account-store.js";
46
+ import { isHostedOAuthConfigured } from "./providers/google-antigravity/oauth.js";
47
+ import type { RequestBody } from "./proxy.js";
48
+ import { UsagePredictor, type ExhaustionPrediction } from "./providers/ollama/prediction.js";
49
+ import { fetchWithRetry } from "./fetch-with-retry.js";
50
+ import type { RequestInitWithDispatcher } from "./fetch-with-retry.js";
51
+ import { getOllamaApiKey } from "./providers/ollama/credentials.js";
52
+ import {
53
+ DEFAULT_PROVIDER,
54
+ getProviderAdapter,
55
+ getProviderForAccount,
56
+ hasCredential,
57
+ primaryProviderId,
58
+ } from "./providers/registry.js";
59
+ import type { QuotaFetchContext } from "./providers/adapter.js";
60
+ import { logger } from "./logger.js";
61
+ import { getAccountProxyDispatcher } from "./providers/proxy-dispatcher.js";
62
+ import { getUpdateInfo } from "./version-check.js";
63
+ import { getNotifications } from "./notification-poller.js";
64
+ import { getConfiguredAdminToken } from "./admin-auth.js";
65
+ import { getProxyExposureWarning } from "./exposure.js";
66
+ import {
67
+ getCachedState,
68
+ setCachedState,
69
+ getCachedTokenUsage,
70
+ setCachedTokenUsage,
71
+ } from "./db-store.js";
72
+
73
+ const rotatorLogger = logger.child("rotator");
74
+
75
+ function currentUtcDay(now = Date.now()): string {
76
+ return new Date(now).toISOString().slice(0, 10);
77
+ }
78
+
79
+ function nextUtcDayStartMs(now = Date.now()): number {
80
+ const date = new Date(now);
81
+ return Date.UTC(
82
+ date.getUTCFullYear(),
83
+ date.getUTCMonth(),
84
+ date.getUTCDate() + 1,
85
+ );
86
+ }
87
+
88
+ function projectModelKey(projectId: string, modelKey: string): string {
89
+ return `${projectId}::${modelKey}`;
90
+ }
91
+
92
+ // Reverse map: upstream model → the quota pool key it primarily represents (for deduplication).
93
+ const QUOTA_POOL_FOR_KICKSTART_MODEL: Record<string, string> = {
94
+ "gpt-oss-120b-medium": "claude-opus-4-6-thinking",
95
+ "gemini-3-flash": "gemini-3.5-flash",
96
+ };
97
+
98
+ export class AccountRotator {
99
+ private accounts: AccountRuntime[] = [];
100
+ // Per-model active account tracking
101
+ private modelState = new Map<string, ModelRotationState>();
102
+ // Fallback for requests where model can't be resolved
103
+ private defaultIndex = 0;
104
+ private startTime = Date.now();
105
+ private quotaPollTimer: ReturnType<typeof setInterval> | null = null;
106
+ private protectivePauseUntil = 0;
107
+ private protectivePauseReason: string | null = null;
108
+ private allowFreshWindowStarts = true;
109
+ private recentEvents: StatusResponse["recentEvents"] = [];
110
+ private static readonly RECENT_EVENT_LIMIT = 40;
111
+ private tokenBuckets: TokenUsageTiered = {
112
+ minutes: [],
113
+ hours: [],
114
+ days: [],
115
+ months: [],
116
+ };
117
+ private latencyRecords: Map<string, { ttfbMs: number; totalMs: number }[]> =
118
+ new Map();
119
+ private static readonly MAX_LATENCY_RECORDS = 200;
120
+ private requestLog: StatusResponse["requestLog"] = [];
121
+ private ollamaModels = new Set<string>();
122
+ private readonly usagePredictor = new UsagePredictor();
123
+ private lastOllamaCatalogFetch = 0;
124
+
125
+ setOllamaModels(models: string[]): void {
126
+ this.ollamaModels = new Set(models.map((m) => m.trim()).filter(Boolean));
127
+ }
128
+
129
+ getOllamaModels(): string[] {
130
+ return [...this.ollamaModels];
131
+ }
132
+
133
+ /** Fetch the Ollama Cloud catalog once at startup so provider-aware routing and /v1/models work before the first quota poll. */
134
+ primeOllamaCatalog(): Promise<void> {
135
+ return this.refreshOllamaCatalogOnce();
136
+ }
137
+
138
+ private async refreshOllamaCatalogOnce(): Promise<void> {
139
+ const now = Date.now();
140
+ if (now - this.lastOllamaCatalogFetch < TAGS_CACHE_TTL_MS) return;
141
+ const ollamaAccount = this.accounts.find(
142
+ (a) =>
143
+ hasCredential(a.config, "ollama") &&
144
+ !a.disabled &&
145
+ !a.flagged,
146
+ );
147
+ if (!ollamaAccount || typeof getOllamaApiKey(ollamaAccount.config) !== "string") {
148
+ return;
149
+ }
150
+ this.lastOllamaCatalogFetch = now;
151
+ try {
152
+ const response = await fetchWithRetry(OLLAMA_TAGS_URL, {
153
+ method: "GET",
154
+ headers: {
155
+ Authorization: `Bearer ${getOllamaApiKey(ollamaAccount.config) ?? ""}`,
156
+ "User-Agent": OLLAMA_USER_AGENT,
157
+ },
158
+ timeoutMs: 8000,
159
+ });
160
+ if (!response.ok) return;
161
+ const data = (await response.json()) as {
162
+ models?: Array<{ name?: string; model?: string }>;
163
+ };
164
+ const names = (data.models ?? [])
165
+ .map((m) => m.name ?? m.model ?? "")
166
+ .filter(Boolean);
167
+ if (names.length > 0) this.setOllamaModels(names);
168
+ } catch {
169
+ // Catalog refresh is non-fatal
170
+ }
171
+ }
172
+
173
+ private static readonly MAX_REQUEST_LOG = 200;
174
+ private safetyDay = currentUtcDay();
175
+ private projectRequests: Record<string, number> = {};
176
+ private projectModelBreakers: Record<string, number> = {};
177
+ private modelBreakers: Record<string, number> = {};
178
+ private provider429Events: Array<{
179
+ ts: number;
180
+ projectId: string;
181
+ modelKey: string;
182
+ account: string;
183
+ }> = [];
184
+ private routingDiagnostics: Record<string, RoutingModelDiagnostics> = {};
185
+ private autoWarmupEnabled = false;
186
+ // Tracks upstream models already warmed-up this poll cycle per account (email → Set<upstreamModel>).
187
+ // Cleared at the start of each pollAllQuotas() to enforce the one-per-cycle guarantee.
188
+ private warmupSentThisCycle = new Map<string, Set<string>>();
189
+ // Debounced state writer: batches multiple saveState() calls within a 1s window
190
+ // to a single disk write. Hot paths (markError, recordRequest, etc.) call
191
+ // scheduleStateSave() instead of saveState() to avoid blocking the event loop.
192
+ private stateSaveTimer: ReturnType<typeof setTimeout> | null = null;
193
+ private static readonly STATE_SAVE_DEBOUNCE_MS = 1_000;
194
+ private stateSaveInflight: Promise<void> | null = null;
195
+ private stateSavePending = false;
196
+ // Debounced token-usage writer: same pattern as state. Debounce window is
197
+ // longer (2s) because token-usage writes include the minute/hour/day
198
+ // consolidation pass and the JSON can be tens of KB.
199
+ private tokenUsageSaveTimer: ReturnType<typeof setTimeout> | null = null;
200
+ private static readonly TOKEN_USAGE_SAVE_DEBOUNCE_MS = 2_000;
201
+ private tokenUsageSaveInflight = false;
202
+ private tokenUsageSavePending = false;
203
+
204
+ constructor(private config: Config) {
205
+ this.config = applyConfigDefaults(config);
206
+ this.initAccounts();
207
+ this.loadState();
208
+ this.startQuotaPolling();
209
+ }
210
+
211
+ private initAccounts(): void {
212
+ this.accounts = this.config.accounts.map((config) => ({
213
+ config,
214
+ accessToken: null,
215
+ tokenExpires: 0,
216
+ requestsSinceRotation: 0,
217
+ totalRequests: 0,
218
+ cooldownsByModel: {},
219
+ quotaExhaustedAt: 0,
220
+ quota: [],
221
+ lastQuotaPoll: 0,
222
+ lastUsed: 0,
223
+ lastError: null,
224
+ consecutiveErrors: 0,
225
+ disabled: false,
226
+ flagged: false,
227
+ inFlightRequests: 0,
228
+ inFlightByModel: {},
229
+ allowFreshWindowStartsOverride: false,
230
+ dailyRequestCount: 0,
231
+ dailyRequestDay: currentUtcDay(),
232
+ healthScore: 1,
233
+ tokenBucket: {
234
+ tokens: Math.max(
235
+ 0,
236
+ Math.min(
237
+ this.config.tokenBucketInitialTokens ?? 50,
238
+ this.config.tokenBucketMaxTokens ?? 50,
239
+ ),
240
+ ),
241
+ lastRefillAt: Date.now(),
242
+ },
243
+ }));
244
+ this.refreshHealthScores();
245
+ }
246
+
247
+ private isTokenBucketEnabled(): boolean {
248
+ return !!this.config.tokenBucketEnabled;
249
+ }
250
+
251
+ private getTokenBucketCapacity(): number {
252
+ return Math.max(1, this.config.tokenBucketMaxTokens ?? 50);
253
+ }
254
+
255
+ private getTokenBucketRefillPerMinute(): number {
256
+ return Math.max(0.0001, this.config.tokenBucketRefillPerMinute ?? 6);
257
+ }
258
+
259
+ private refillTokenBucket(account: AccountRuntime, now: number): void {
260
+ const capacity = this.getTokenBucketCapacity();
261
+ if (!this.isTokenBucketEnabled()) {
262
+ account.tokenBucket.tokens = capacity;
263
+ account.tokenBucket.lastRefillAt = now;
264
+ return;
265
+ }
266
+ const elapsedMinutes =
267
+ Math.max(0, now - account.tokenBucket.lastRefillAt) / 60_000;
268
+ if (elapsedMinutes <= 0) return;
269
+ account.tokenBucket.tokens = Math.min(
270
+ capacity,
271
+ account.tokenBucket.tokens +
272
+ elapsedMinutes * this.getTokenBucketRefillPerMinute(),
273
+ );
274
+ account.tokenBucket.lastRefillAt = now;
275
+ }
276
+
277
+ private getTokenBucketSnapshot(
278
+ account: AccountRuntime,
279
+ now: number,
280
+ ): {
281
+ enabled: boolean;
282
+ tokens: number;
283
+ capacity: number;
284
+ nextRefillInMs: number;
285
+ } {
286
+ const capacity = this.getTokenBucketCapacity();
287
+ if (!this.isTokenBucketEnabled()) {
288
+ return { enabled: false, tokens: capacity, capacity, nextRefillInMs: 0 };
289
+ }
290
+ this.refillTokenBucket(account, now);
291
+ const tokens = Math.max(0, Math.min(capacity, account.tokenBucket.tokens));
292
+ if (tokens >= 1) {
293
+ return { enabled: true, tokens, capacity, nextRefillInMs: 0 };
294
+ }
295
+ const tokensNeeded = 1 - tokens;
296
+ const nextRefillInMs = Math.ceil(
297
+ (tokensNeeded / this.getTokenBucketRefillPerMinute()) * 60_000,
298
+ );
299
+ return {
300
+ enabled: true,
301
+ tokens,
302
+ capacity,
303
+ nextRefillInMs: Math.max(0, nextRefillInMs),
304
+ };
305
+ }
306
+
307
+ private consumeTokenBucket(account: AccountRuntime, now: number): boolean {
308
+ if (!this.isTokenBucketEnabled()) return true;
309
+ this.refillTokenBucket(account, now);
310
+ if (account.tokenBucket.tokens < 1) return false;
311
+ account.tokenBucket.tokens = Math.max(0, account.tokenBucket.tokens - 1);
312
+ account.tokenBucket.lastRefillAt = now;
313
+ return true;
314
+ }
315
+
316
+ private refundTokenBucket(account: AccountRuntime, now: number): void {
317
+ if (!this.isTokenBucketEnabled()) return;
318
+ this.refillTokenBucket(account, now);
319
+ account.tokenBucket.tokens = Math.min(
320
+ this.getTokenBucketCapacity(),
321
+ account.tokenBucket.tokens + 1,
322
+ );
323
+ account.tokenBucket.lastRefillAt = now;
324
+ }
325
+
326
+ private loadState(): void {
327
+ const state = getCachedState();
328
+ if (!state) {
329
+ this.loadTokenUsage();
330
+ return;
331
+ }
332
+
333
+ try {
334
+ // Load per-model account assignments
335
+ if (state.modelAccounts) {
336
+ for (const [model, idx] of Object.entries(state.modelAccounts)) {
337
+ this.modelState.set(model, {
338
+ activeAccountIndex: Math.min(idx, this.accounts.length - 1),
339
+ stickyAccountIndex:
340
+ state.modelStickyAccounts?.[model] !== undefined
341
+ ? Math.min(
342
+ state.modelStickyAccounts[model],
343
+ this.accounts.length - 1,
344
+ )
345
+ : undefined,
346
+ quotaAtRotationStart: -1,
347
+ requestsOnActiveAccount: state.modelRequestCounts?.[model] ?? 0,
348
+ });
349
+ }
350
+ }
351
+ // Legacy fallback
352
+ if (state.currentIndex !== undefined) {
353
+ this.defaultIndex = Math.min(
354
+ state.currentIndex,
355
+ this.accounts.length - 1,
356
+ );
357
+ }
358
+ this.protectivePauseUntil = state.protectivePauseUntil ?? 0;
359
+ this.protectivePauseReason = state.protectivePauseReason ?? null;
360
+ this.allowFreshWindowStarts = state.allowFreshWindowStarts ?? true;
361
+ this.autoWarmupEnabled = state.autoWarmupEnabled ?? false;
362
+ this.safetyDay = state.safety?.day ?? currentUtcDay();
363
+ this.projectRequests = state.safety?.projectRequests ?? {};
364
+ this.projectModelBreakers = state.safety?.projectModelBreakers ?? {};
365
+ this.modelBreakers = state.safety?.modelBreakers ?? {};
366
+ this.provider429Events = state.safety?.provider429Events ?? [];
367
+ this.rollDailySafetyIfNeeded(Date.now());
368
+
369
+ for (const account of this.accounts) {
370
+ const saved = state.accounts[account.config.email];
371
+ if (saved) {
372
+ account.totalRequests = saved.totalRequests;
373
+ account.dailyRequestCount = saved.dailyRequestCount ?? 0;
374
+ account.dailyRequestDay = saved.dailyRequestDay ?? currentUtcDay();
375
+ account.cooldownsByModel = saved.cooldownsByModel ?? {};
376
+ if (
377
+ saved.cooldownUntil !== undefined &&
378
+ Object.keys(account.cooldownsByModel).length === 0
379
+ ) {
380
+ // legacy migration: apply global cooldown to default
381
+ account.cooldownsByModel["__default__"] = saved.cooldownUntil;
382
+ }
383
+ account.quotaExhaustedAt = saved.quotaExhaustedAt;
384
+ account.disabled = saved.disabled;
385
+ account.flagged = saved.flagged ?? false;
386
+ account.allowFreshWindowStartsOverride =
387
+ saved.allowFreshWindowStartsOverride ?? false;
388
+ }
389
+ }
390
+ // Cap any stale cooldowns to 30 min max from now
391
+ const maxCooldown = 30 * 60 * 1000;
392
+ const now = Date.now();
393
+ for (const account of this.accounts) {
394
+ for (const [model, cooldown] of Object.entries(
395
+ account.cooldownsByModel,
396
+ )) {
397
+ if (cooldown > now + maxCooldown) {
398
+ account.cooldownsByModel[model] = now + maxCooldown;
399
+ }
400
+ }
401
+ }
402
+ this.log("Loaded persisted state");
403
+ } catch {
404
+ this.log("Could not load state, starting fresh");
405
+ }
406
+ this.loadTokenUsage();
407
+ }
408
+
409
+ private loadTokenUsage(): void {
410
+ try {
411
+ const parsed = getCachedTokenUsage() as any;
412
+
413
+ if (!parsed) return;
414
+
415
+ const normalize = (arr: any[]): TokenBucket[] =>
416
+ (arr || [])
417
+ .map((b: any) => ({
418
+ period: b.period ?? b.hour ?? "unknown",
419
+ inputTokens: Number(b.inputTokens || 0),
420
+ outputTokens: Number(b.outputTokens || 0),
421
+ requests: Number(b.requests || 0),
422
+ byModel: b.byModel || {},
423
+ }))
424
+ .filter((b: TokenBucket) => b.period && b.period !== "unknown");
425
+ if (Array.isArray(parsed)) {
426
+ // Migrate from flat array (old format)
427
+ this.tokenBuckets = {
428
+ minutes: normalize(parsed),
429
+ hours: [],
430
+ days: [],
431
+ months: [],
432
+ };
433
+ } else {
434
+ this.tokenBuckets = {
435
+ minutes: normalize(parsed.minutes || []),
436
+ hours: normalize(parsed.hours || []),
437
+ days: normalize(parsed.days || []),
438
+ months: normalize(parsed.months || []),
439
+ };
440
+ }
441
+ const total =
442
+ this.tokenBuckets.minutes.length +
443
+ this.tokenBuckets.hours.length +
444
+ this.tokenBuckets.days.length +
445
+ this.tokenBuckets.months.length;
446
+ this.log(`Loaded ${total} token usage buckets`);
447
+ } catch {
448
+ this.log("Could not load token usage, starting fresh");
449
+ }
450
+ }
451
+
452
+ async saveState(): Promise<void> {
453
+ const modelAccounts: Record<string, number> = {};
454
+ const modelRequestCounts: Record<string, number> = {};
455
+ const modelStickyAccounts: Record<string, number> = {};
456
+ for (const [model, state] of this.modelState.entries()) {
457
+ modelAccounts[model] = state.activeAccountIndex;
458
+ modelRequestCounts[model] = state.requestsOnActiveAccount;
459
+ if (state.stickyAccountIndex !== undefined) {
460
+ modelStickyAccounts[model] = state.stickyAccountIndex;
461
+ }
462
+ }
463
+
464
+ const state: PersistedState = {
465
+ modelAccounts,
466
+ modelRequestCounts,
467
+ modelStickyAccounts,
468
+ currentIndex: this.defaultIndex,
469
+ protectivePauseUntil: this.protectivePauseUntil,
470
+ protectivePauseReason: this.protectivePauseReason,
471
+ allowFreshWindowStarts: this.allowFreshWindowStarts,
472
+ autoWarmupEnabled: this.autoWarmupEnabled,
473
+ safety: {
474
+ day: this.safetyDay,
475
+ projectRequests: { ...this.projectRequests },
476
+ projectModelBreakers: { ...this.projectModelBreakers },
477
+ modelBreakers: { ...this.modelBreakers },
478
+ provider429Events: [...this.provider429Events],
479
+ },
480
+ accounts: {},
481
+ };
482
+ for (const account of this.accounts) {
483
+ state.accounts[account.config.email] = {
484
+ totalRequests: account.totalRequests,
485
+ dailyRequestCount: account.dailyRequestCount,
486
+ dailyRequestDay: account.dailyRequestDay,
487
+ cooldownsByModel: { ...account.cooldownsByModel },
488
+ quotaExhaustedAt: account.quotaExhaustedAt,
489
+ disabled: account.disabled,
490
+ flagged: account.flagged,
491
+ allowFreshWindowStartsOverride: account.allowFreshWindowStartsOverride,
492
+ };
493
+ }
494
+ try {
495
+ await setCachedState(state);
496
+ } catch (err) {
497
+ this.log(`Failed to save state: ${err}`, "error");
498
+ }
499
+ }
500
+
501
+ /**
502
+ * Schedule a debounced state save. Multiple calls within STATE_SAVE_DEBOUNCE_MS
503
+ * are coalesced into a single saveState() invocation. Hot paths (recordRequest,
504
+ * markError, etc.) should use this instead of saveState() to avoid blocking
505
+ * the event loop on every request.
506
+ *
507
+ * If a write is already in-flight when the timer fires, the next write is
508
+ * scheduled for after it completes.
509
+ */
510
+ scheduleStateSave(): void {
511
+ if (this.stateSaveTimer) return;
512
+ this.stateSaveTimer = setTimeout(() => {
513
+ this.stateSaveTimer = null;
514
+ void this.runScheduledStateSave();
515
+ }, AccountRotator.STATE_SAVE_DEBOUNCE_MS);
516
+ if (this.stateSaveTimer.unref) this.stateSaveTimer.unref();
517
+ }
518
+
519
+ private async runScheduledStateSave(): Promise<void> {
520
+ if (this.stateSaveInflight) {
521
+ // A write is already running. Re-schedule ourselves to run after it.
522
+ this.stateSavePending = true;
523
+ await this.stateSaveInflight;
524
+ return;
525
+ }
526
+ const write = this.saveState();
527
+ this.stateSaveInflight = write;
528
+ try {
529
+ await write;
530
+ } finally {
531
+ this.stateSaveInflight = null;
532
+ if (this.stateSavePending) {
533
+ this.stateSavePending = false;
534
+ this.scheduleStateSave();
535
+ }
536
+ }
537
+ }
538
+
539
+ /**
540
+ * Force-flush any pending state writes. Called by SIGTERM/SIGINT handlers
541
+ * in index.ts to minimise data loss on shutdown.
542
+ */
543
+ async flushPendingStateSave(): Promise<void> {
544
+ if (this.stateSaveTimer) {
545
+ clearTimeout(this.stateSaveTimer);
546
+ this.stateSaveTimer = null;
547
+ }
548
+ if (this.stateSaveInflight) await this.stateSaveInflight;
549
+ this.stateSavePending = false;
550
+ await this.saveState();
551
+ }
552
+
553
+ // =========================================================================
554
+ // Quota Polling
555
+ // =========================================================================
556
+
557
+ private startQuotaPolling(): void {
558
+ const configuredIntervalMs = this.config.quotaPollIntervalMs;
559
+ const intervalMs =
560
+ Number.isFinite(configuredIntervalMs) &&
561
+ configuredIntervalMs >= MIN_QUOTA_POLL_INTERVAL_MS &&
562
+ configuredIntervalMs <= MAX_QUOTA_POLL_INTERVAL_MS
563
+ ? Math.floor(configuredIntervalMs)
564
+ : DEFAULT_QUOTA_POLL_INTERVAL_MS;
565
+ this.log(`Quota polling every ${Math.round(intervalMs / 1000)}s`);
566
+
567
+ // Initial poll (delayed 2s to allow token refresh first)
568
+ setTimeout(() => this.pollAllQuotas(), 2000);
569
+
570
+ this.quotaPollTimer = setInterval(() => this.pollAllQuotas(), intervalMs);
571
+ }
572
+
573
+ stopQuotaPolling(): void {
574
+ if (this.quotaPollTimer) {
575
+ clearInterval(this.quotaPollTimer);
576
+ this.quotaPollTimer = null;
577
+ }
578
+ }
579
+
580
+ /**
581
+ * Emit one consolidated RAW POLL line per quota cycle, with Antigravity
582
+ * pools first and Ollama (usage) pools last. Per-provider strings are
583
+ * collected into `account.lastPollByProvider` by each adapter.
584
+ */
585
+ private logConsolidatedPoll(account: AccountRuntime): void {
586
+ const stash = account.lastPollByProvider;
587
+ if (!stash) return;
588
+ const ordered = ["google-antigravity", "ollama"]
589
+ .filter((pid) => stash[pid])
590
+ .map((pid) => `${pid}: ${stash[pid]}`);
591
+ if (ordered.length > 0) {
592
+ this.log(`RAW POLL ${account.config.email} -> ${ordered.join(" | ")}`);
593
+ }
594
+ account.lastPollByProvider = {};
595
+ }
596
+
597
+ private async pollAllQuotas(): Promise<void> {
598
+ // Reset per-cycle warmup tracking so each poll cycle allows at most one warmup per upstream model per account.
599
+ this.warmupSentThisCycle.clear();
600
+ void this.refreshOllamaCatalogOnce().catch(() => {});
601
+
602
+ const available = this.accounts.filter((a) => !a.disabled && !a.flagged);
603
+ for (const account of available) {
604
+ try {
605
+ await this.ensureValidToken(account);
606
+ const quotaCtx: QuotaFetchContext = {
607
+ log: (message) => this.log(message),
608
+ markFlagged: (acc, reason, options) =>
609
+ this.markFlagged(acc, reason, options),
610
+ reportQuotaPollFlag: (acc, statusCode, errorText) =>
611
+ this.reportQuotaPollFlag(acc, statusCode, errorText),
612
+ };
613
+ // Parent-account model: poll quota for every provider credential
614
+ // the account holds (Google OAuth pools + Ollama usage pools).
615
+ const providerIds = new Set<string>(
616
+ (account.config.credentials ?? []).map((c) => c.provider),
617
+ );
618
+ if (providerIds.size === 0) providerIds.add(primaryProviderId(account.config));
619
+ for (const pid of providerIds) {
620
+ await getProviderAdapter(pid).fetchQuota(account, quotaCtx);
621
+ }
622
+ } catch {
623
+ // Token refresh or quota fetch failed, skip this account
624
+ }
625
+
626
+ // Consolidated RAW POLL across all providers on this account:
627
+ // google first (Antigravity OAuth pools), then ollama (usage pools).
628
+ this.logConsolidatedPoll(account);
629
+
630
+ // Auto-warmup: send minimal kickstart requests for idle pools on accounts that have opted
631
+ // in via allowFreshWindowStartsOverride, but only if the operator has enabled the global
632
+ // auto-warmup toggle. "Idle" includes both fresh pools (no active timer) and rolling idle
633
+ // pools (100% quota with resetTime very close to a full 5h or 7d window — timer exists but
634
+ // untouched). Deduplicates by upstream model within this cycle.
635
+ if (this.autoWarmupEnabled && account.allowFreshWindowStartsOverride) {
636
+ const idlePools = account.quota.filter((q) => this.isQuotaIdleForKickstart(q));
637
+ if (idlePools.length > 0) {
638
+ const alreadySent =
639
+ this.warmupSentThisCycle.get(account.config.email) ?? new Set<string>();
640
+ const upstreamToQuotaKey = new Map<string, string>();
641
+ for (const q of idlePools) {
642
+ // Dispatch warmup by pool owner: the session pool belongs to
643
+ // Ollama; every other pool key is a Google OAuth pool.
644
+ const warmupAdapter =
645
+ q.modelKey === "session"
646
+ ? getProviderAdapter("ollama")
647
+ : getProviderForAccount(account.config);
648
+ const upstream =
649
+ warmupAdapter.getKickstartModelForPool(q.modelKey) ?? q.modelKey;
650
+ if (!upstreamToQuotaKey.has(upstream)) {
651
+ upstreamToQuotaKey.set(upstream, q.modelKey);
652
+ }
653
+ }
654
+ for (const [upstream, quotaKey] of upstreamToQuotaKey) {
655
+ if (!alreadySent.has(upstream)) {
656
+ alreadySent.add(upstream);
657
+ // Fire-and-forget — errors are handled internally by kickstartTimerForAccount
658
+ void this.kickstartTimerForAccount(account.config.email, quotaKey).catch(
659
+ () => {},
660
+ );
661
+ }
662
+ }
663
+ this.warmupSentThisCycle.set(account.config.email, alreadySent);
664
+ }
665
+ }
666
+ }
667
+
668
+ if (this.isProtectivePauseActive(Date.now())) {
669
+ return;
670
+ }
671
+
672
+ // Check per-model quota-based rotation
673
+ if (this.config.rotateOnQuotaDrop > 0) {
674
+ for (const [modelKey, mState] of this.modelState.entries()) {
675
+ const account = this.accounts[mState.activeAccountIndex];
676
+ if (!account) continue;
677
+
678
+ const modelQuota = this.getModelQuota(account, modelKey);
679
+ if (modelQuota < 0) continue; // No data yet
680
+
681
+ if (mState.quotaAtRotationStart < 0) {
682
+ // First reading for this rotation
683
+ mState.quotaAtRotationStart = modelQuota;
684
+ this.log(
685
+ `${account.config.label || account.config.email} [${modelKey}]: baseline quota ${modelQuota}%`,
686
+ );
687
+ } else {
688
+ const drop = mState.quotaAtRotationStart - modelQuota;
689
+ if (drop >= this.config.rotateOnQuotaDrop) {
690
+ // Only rotate if there's a healthy account to rotate to
691
+ const hasHealthy = this.accounts.some(
692
+ (a, idx) =>
693
+ idx !== mState.activeAccountIndex &&
694
+ this.isRoutableForModel(a, modelKey, Date.now()),
695
+ );
696
+ if (hasHealthy) {
697
+ this.log(
698
+ `${account.config.label || account.config.email} [${modelKey}]: quota dropped ${drop}% (${mState.quotaAtRotationStart}% -> ${modelQuota}%), rotating`,
699
+ );
700
+ await this.rotateModel(modelKey);
701
+ } else {
702
+ this.log(
703
+ `${account.config.label || account.config.email} [${modelKey}]: quota dropped ${drop}% but no healthy accounts available, staying`,
704
+ );
705
+ mState.quotaAtRotationStart = modelQuota; // Reset baseline
706
+ }
707
+ }
708
+ }
709
+ }
710
+ }
711
+ }
712
+
713
+ private reportQuotaPollFlag(
714
+ account: AccountRuntime,
715
+ statusCode: number,
716
+ errorText: string,
717
+ ): void {
718
+ const modelKey = account.quota[0]?.modelKey ?? "quota-poll";
719
+ const ctx = this.getFlagContext(account, modelKey);
720
+ const lower = errorText.toLowerCase();
721
+ const matchedPatterns = FLAG_PATTERNS.filter((p) => lower.includes(p));
722
+ reportFlagEvent({
723
+ flagHttpStatus: statusCode,
724
+ flagPatternsMatched: matchedPatterns.length > 0 ? matchedPatterns : [],
725
+ model: "quota-poll",
726
+ timerType: ctx.timerType as FlagEventData["timerType"],
727
+ accountQuotaPercent: ctx.accountQuotaPercent,
728
+ wasProAccount: ctx.wasProAccount,
729
+ accountTotalRequests: account.totalRequests,
730
+ accountRequestsLastHour: ctx.accountRequestsLastHour,
731
+ accountConcurrentAtFlag: account.inFlightRequests,
732
+ poolSize: ctx.poolSize,
733
+ poolHealthyCount: ctx.poolHealthyCount,
734
+ protectivePauseTriggered: false,
735
+ uptimeSeconds: ctx.uptimeSeconds,
736
+ timeSinceLastFlagSeconds: -1,
737
+ });
738
+ }
739
+
740
+ // Get quota % for a specific model on an account. Returns -1 if no data.
741
+ private getModelQuota(account: AccountRuntime, modelKey: string): number {
742
+ const q = account.quota.find((q) => q.modelKey === modelKey);
743
+ return q ? q.percentRemaining : -1;
744
+ }
745
+
746
+ // Get timer type for a specific model on an account
747
+ private getModelTimerType(
748
+ account: AccountRuntime,
749
+ modelKey: string,
750
+ ): "fresh" | "5h" | "7d" {
751
+ const q = account.quota.find((q) => q.modelKey === modelKey);
752
+ return q?.timerType ?? "fresh";
753
+ }
754
+
755
+ // A pool is "idle for kickstart" when it has a fresh pool (no active timer)
756
+ // OR a rolling idle timer (100% quota with resetTime very close to a full 5h or 7d
757
+ // window — the timer exists but the quota is completely untouched). Sending a
758
+ // minimal kickstart request against an idle pool starts the consumption clock.
759
+ private isQuotaIdleForKickstart(q: ModelQuota): boolean {
760
+ if (q.timerType === "fresh") return true;
761
+ if (!q.resetTime || q.percentRemaining !== 100) return false;
762
+ const remaining = new Date(q.resetTime).getTime() - Date.now();
763
+ if (remaining <= 0) return false;
764
+ const within = (target: number) => Math.abs(remaining - target) < 600_000;
765
+ return within(5 * 3600 * 1000) || within(7 * 24 * 3600 * 1000);
766
+ }
767
+
768
+ // Timer priority for a specific model:
769
+ // 1 (highest) = 5h timer -> only class with hard quota loss if underused before reset
770
+ // 2 = 7d timer -> already ticking, keep those long windows moving
771
+ // 3 (lowest) = fresh -> no visible timer is running yet
772
+ private getModelTimerPriority(
773
+ account: AccountRuntime,
774
+ modelKey: string,
775
+ ): number {
776
+ const type = this.getModelTimerType(account, modelKey);
777
+ if (type === "5h") return 1;
778
+ if (type === "7d") return 2;
779
+ return 3;
780
+ }
781
+
782
+ private isFreshWindowAllowed(
783
+ account: AccountRuntime,
784
+ modelKey: string,
785
+ ): boolean {
786
+ if (this.allowFreshWindowStarts) return true;
787
+ if (account.allowFreshWindowStartsOverride) return true;
788
+ return this.getModelTimerType(account, modelKey) !== "fresh";
789
+ }
790
+
791
+ private isEffectiveFreshWindowAllowed(account: AccountRuntime): boolean {
792
+ return (
793
+ this.allowFreshWindowStarts || account.allowFreshWindowStartsOverride
794
+ );
795
+ }
796
+
797
+ private isTimedWindow(account: AccountRuntime, modelKey: string): boolean {
798
+ return this.getModelTimerType(account, modelKey) !== "fresh";
799
+ }
800
+
801
+ private hasTimedCandidate(
802
+ modelKey: string,
803
+ now: number,
804
+ excludeIdx: number = -1,
805
+ ): boolean {
806
+ return this.accounts.some((account, idx) => {
807
+ if (idx === excludeIdx) return false;
808
+ if (!this.isAvailableForModel(account, modelKey, now)) return false;
809
+ if (this.getModelQuota(account, modelKey) === 0) return false;
810
+ return this.isTimedWindow(account, modelKey);
811
+ });
812
+ }
813
+
814
+ private isQuotaAwarePolicy(
815
+ policy: Config["routingPolicy"] = this.config.routingPolicy,
816
+ ): boolean {
817
+ return policy === "sequential-quota" || policy === "sticky-quota";
818
+ }
819
+
820
+ private pickBestModelAccount(
821
+ modelKey: string,
822
+ now: number,
823
+ excludeIdx: number = -1,
824
+ ): AccountRuntime | null {
825
+ let best: AccountRuntime | null = null;
826
+ let bestMetrics: {
827
+ priority: number;
828
+ quota: number;
829
+ tier: number;
830
+ health: number;
831
+ distance: number;
832
+ tokenRatio: number;
833
+ hybridScore: number;
834
+ } | null = null;
835
+ const policy = this.config.routingPolicy || "timer-first";
836
+
837
+ const candidateIndices =
838
+ policy === "sequential-quota"
839
+ ? Array.from({ length: this.accounts.length }, (_, offset) =>
840
+ excludeIdx >= 0
841
+ ? (excludeIdx + 1 + offset) % this.accounts.length
842
+ : offset,
843
+ )
844
+ : Array.from({ length: this.accounts.length }, (_, i) => i);
845
+
846
+ for (const i of candidateIndices) {
847
+ if (i === excludeIdx) continue;
848
+ const account = this.accounts[i];
849
+ if (!this.isProviderEligibleForKey(account, modelKey)) continue;
850
+ if (!this.isAvailableForModel(account, modelKey, now)) continue;
851
+
852
+ const quota = this.getModelQuota(account, modelKey);
853
+ if (quota === 0) continue;
854
+ if (!this.isFreshWindowAllowed(account, modelKey)) continue;
855
+
856
+ const priority = this.getModelTimerPriority(account, modelKey);
857
+ const tier = this.getTierRank(account);
858
+ const health = account.healthScore;
859
+ const distance =
860
+ excludeIdx >= 0
861
+ ? (i - excludeIdx + this.accounts.length) % this.accounts.length
862
+ : i + 1;
863
+ const tokenSnapshot = this.getTokenBucketSnapshot(account, now);
864
+ const tokenRatio =
865
+ tokenSnapshot.capacity > 0
866
+ ? tokenSnapshot.tokens / tokenSnapshot.capacity
867
+ : 0;
868
+ if (
869
+ policy === "hybrid" &&
870
+ tokenSnapshot.enabled &&
871
+ tokenSnapshot.tokens < 1
872
+ )
873
+ continue;
874
+ if (policy === "sequential-quota") return account;
875
+ const metrics = {
876
+ priority,
877
+ quota,
878
+ tier,
879
+ health,
880
+ distance,
881
+ tokenRatio,
882
+ hybridScore: this.calculateHybridScore(
883
+ priority,
884
+ quota,
885
+ tier,
886
+ health,
887
+ tokenRatio,
888
+ distance,
889
+ ),
890
+ };
891
+ if (
892
+ !bestMetrics ||
893
+ this.compareRoutingCandidate(metrics, bestMetrics, policy)
894
+ ) {
895
+ best = account;
896
+ bestMetrics = metrics;
897
+ }
898
+ }
899
+
900
+ return best;
901
+ }
902
+
903
+ private countModelAssignment(modelKey: string): void {
904
+ const state = this.modelState.get(modelKey);
905
+ if (state) {
906
+ state.requestsOnActiveAccount++;
907
+ this.scheduleStateSave();
908
+ }
909
+ }
910
+
911
+ private shouldRotateBeforeRequest(
912
+ account: AccountRuntime,
913
+ modelKey: string,
914
+ state: ModelRotationState | null,
915
+ ): boolean {
916
+ return (
917
+ !!state &&
918
+ this.shouldUseRequestCountRotation(account, modelKey) &&
919
+ state.requestsOnActiveAccount >= this.config.requestsPerRotation
920
+ );
921
+ }
922
+
923
+ private async rotateModelForRequest(
924
+ modelKey: string,
925
+ now: number = Date.now(),
926
+ excludeIdx?: number,
927
+ ): Promise<AccountRuntime | null> {
928
+ const account = await this.rotateModel(modelKey, now, excludeIdx);
929
+ if (account) {
930
+ this.countModelAssignment(modelKey);
931
+ }
932
+ return account;
933
+ }
934
+
935
+ private rollDailySafetyIfNeeded(now: number): void {
936
+ const day = currentUtcDay(now);
937
+ if (this.safetyDay === day) return;
938
+ this.safetyDay = day;
939
+ this.projectRequests = {};
940
+ for (const account of this.accounts) {
941
+ account.dailyRequestDay = day;
942
+ account.dailyRequestCount = 0;
943
+ }
944
+ }
945
+
946
+ private getAccountDailyCount(account: AccountRuntime, now: number): number {
947
+ const day = currentUtcDay(now);
948
+ if (account.dailyRequestDay !== day) {
949
+ account.dailyRequestDay = day;
950
+ account.dailyRequestCount = 0;
951
+ }
952
+ return account.dailyRequestCount;
953
+ }
954
+
955
+ private getProjectDailyCount(projectId: string, now: number): number {
956
+ this.rollDailySafetyIfNeeded(now);
957
+ return this.projectRequests[projectId] ?? 0;
958
+ }
959
+
960
+ private getDailySafetyRejection(
961
+ account: AccountRuntime,
962
+ now: number,
963
+ ): {
964
+ reason: "daily-account-stop" | "daily-project-stop";
965
+ detail: string;
966
+ } | null {
967
+ const resetIso = new Date(nextUtcDayStartMs(now)).toISOString();
968
+ const accountCount = this.getAccountDailyCount(account, now);
969
+ const accountLimit = this.config.dailyAccountStopRequests ?? 350;
970
+ if (accountCount >= accountLimit) {
971
+ return {
972
+ reason: "daily-account-stop",
973
+ detail: `daily account budget exhausted (${accountCount}/${accountLimit} upstream attempts; resets at ${resetIso})`,
974
+ };
975
+ }
976
+
977
+ const projectCount = this.getProjectDailyCount(account.config.projectId ?? "",
978
+ now,
979
+ );
980
+ const projectLimit = this.config.dailyProjectStopRequests ?? 1200;
981
+ if (projectCount >= projectLimit) {
982
+ return {
983
+ reason: "daily-project-stop",
984
+ detail: `daily project budget exhausted (${projectCount}/${projectLimit} upstream attempts; resets at ${resetIso})`,
985
+ };
986
+ }
987
+
988
+ return null;
989
+ }
990
+
991
+ private isDailySafetyStopped(account: AccountRuntime, now: number): boolean {
992
+ return this.getDailySafetyRejection(account, now) !== null;
993
+ }
994
+
995
+ private getProjectInFlight(modelKey: string, projectId: string): number {
996
+ return this.accounts
997
+ .filter((account) => account.config.projectId === projectId)
998
+ .reduce(
999
+ (sum, account) => sum + (account.inFlightByModel[modelKey] ?? 0),
1000
+ 0,
1001
+ );
1002
+ }
1003
+
1004
+ private isProjectModelBreakerActive(
1005
+ projectId: string,
1006
+ modelKey: string,
1007
+ now: number,
1008
+ ): boolean {
1009
+ const until =
1010
+ this.projectModelBreakers[projectModelKey(projectId, modelKey)] ?? 0;
1011
+ if (until <= now) {
1012
+ if (until > 0)
1013
+ delete this.projectModelBreakers[projectModelKey(projectId, modelKey)];
1014
+ return false;
1015
+ }
1016
+ return true;
1017
+ }
1018
+
1019
+ private isModelBreakerActive(modelKey: string, now: number): boolean {
1020
+ const until = this.modelBreakers[modelKey] ?? 0;
1021
+ if (until <= now) {
1022
+ if (until > 0) delete this.modelBreakers[modelKey];
1023
+ return false;
1024
+ }
1025
+ return true;
1026
+ }
1027
+
1028
+ private getUnavailableReasonForModel(
1029
+ account: AccountRuntime,
1030
+ modelKey: string,
1031
+ now: number,
1032
+ ): string | null {
1033
+ if (this.isModelBreakerActive(modelKey, now))
1034
+ return "model circuit breaker active";
1035
+ if (
1036
+ this.isProjectModelBreakerActive(account.config.projectId ?? "", modelKey, now)
1037
+ )
1038
+ return "project circuit breaker active";
1039
+ if (
1040
+ this.getProjectInFlight(modelKey, account.config.projectId ?? "") >=
1041
+ (this.config.maxConcurrentRequestsPerProjectModel ?? 1)
1042
+ )
1043
+ return "project concurrency limit reached";
1044
+ const dailySafety = this.getDailySafetyRejection(account, now);
1045
+ if (dailySafety) return dailySafety.detail;
1046
+ return null;
1047
+ }
1048
+
1049
+ private getAccountStatusForUi(
1050
+ account: AccountRuntime,
1051
+ now: number,
1052
+ activeForModels: string[],
1053
+ ): AccountStatus["status"] {
1054
+ const inCooldownModels = Object.values(account.cooldownsByModel).filter(
1055
+ (ts) => ts > now,
1056
+ );
1057
+ if (account.flagged) return "flagged";
1058
+ if (account.disabled) return "disabled";
1059
+ if (account.consecutiveErrors > 0 && !account.disabled) return "error";
1060
+ if (inCooldownModels.length > 0) return "cooldown";
1061
+ if (this.isDailySafetyStopped(account, now)) return "exhausted";
1062
+ if (activeForModels.length > 0) return "active";
1063
+ return "ready";
1064
+ }
1065
+
1066
+ private mapRoutingRejection(reason: string): {
1067
+ reason: RoutingRejectionReason;
1068
+ detail: string;
1069
+ } {
1070
+ if (reason === "model circuit breaker active")
1071
+ return { reason: "model-breaker", detail: reason };
1072
+ if (reason === "project circuit breaker active")
1073
+ return { reason: "project-breaker", detail: reason };
1074
+ if (reason === "project concurrency limit reached")
1075
+ return { reason: "project-concurrency", detail: reason };
1076
+ if (reason.startsWith("daily account budget exhausted"))
1077
+ return { reason: "daily-account-stop", detail: reason };
1078
+ if (reason.startsWith("daily project budget exhausted"))
1079
+ return { reason: "daily-project-stop", detail: reason };
1080
+ return { reason: "cooldown", detail: reason };
1081
+ }
1082
+
1083
+ private getRoutingRejectionForModel(
1084
+ account: AccountRuntime,
1085
+ modelKey: string,
1086
+ now: number,
1087
+ policy: Config["routingPolicy"],
1088
+ ): { reason: RoutingRejectionReason; detail: string } | null {
1089
+ if (account.disabled)
1090
+ return { reason: "disabled", detail: "account disabled" };
1091
+ if (account.flagged)
1092
+ return { reason: "flagged", detail: "account quarantined or flagged" };
1093
+ if (!this.isProviderEligibleForKey(account, modelKey))
1094
+ return {
1095
+ reason: "provider-ineligible",
1096
+ detail: "account lacks a credential for this provider pool",
1097
+ };
1098
+ const defaultCooldown = account.cooldownsByModel["__default__"] ?? 0;
1099
+ if (defaultCooldown > now)
1100
+ return { reason: "cooldown", detail: "default cooldown active" };
1101
+ const modelCooldown = account.cooldownsByModel[modelKey] ?? 0;
1102
+ if (modelCooldown > now)
1103
+ return { reason: "cooldown", detail: "model cooldown active" };
1104
+ // Ollama Cloud (pool key "session") imposes no per-account
1105
+ // concurrency limit — the in-flight check would otherwise wedge
1106
+ // long-running streams while the same model on another account is
1107
+ // still serving. Antigravity keeps the per-account limit.
1108
+ if (
1109
+ modelKey !== "session" &&
1110
+ (account.inFlightByModel[modelKey] ?? 0) >=
1111
+ (this.config.maxConcurrentRequestsPerAccount ?? 1)
1112
+ ) {
1113
+ return {
1114
+ reason: "account-concurrency",
1115
+ detail: "account concurrency limit reached",
1116
+ };
1117
+ }
1118
+ const unavailable = this.getUnavailableReasonForModel(
1119
+ account,
1120
+ modelKey,
1121
+ now,
1122
+ );
1123
+ if (unavailable) return this.mapRoutingRejection(unavailable);
1124
+ if (this.getModelQuota(account, modelKey) === 0)
1125
+ return {
1126
+ reason: "quota-zero",
1127
+ detail: "quota is exhausted for this model",
1128
+ };
1129
+ if (!this.isFreshWindowAllowed(account, modelKey))
1130
+ return {
1131
+ reason: "fresh-window-blocked",
1132
+ detail: "fresh window is blocked by operator policy",
1133
+ };
1134
+ if (policy === "hybrid") {
1135
+ const snapshot = this.getTokenBucketSnapshot(account, now);
1136
+ if (snapshot.enabled && snapshot.tokens < 1) {
1137
+ return {
1138
+ reason: "token-bucket-empty",
1139
+ detail: "local token bucket is empty",
1140
+ };
1141
+ }
1142
+ }
1143
+ return null;
1144
+ }
1145
+
1146
+ private summarizeRoutingRejections(
1147
+ diagnostics: RoutingAccountDiagnostic[],
1148
+ ): string[] {
1149
+ const priority: RoutingRejectionReason[] = [
1150
+ "model-breaker",
1151
+ "project-breaker",
1152
+ "daily-account-stop",
1153
+ "daily-project-stop",
1154
+ "cooldown",
1155
+ "account-concurrency",
1156
+ "project-concurrency",
1157
+ "token-bucket-empty",
1158
+ "fresh-window-blocked",
1159
+ "quota-zero",
1160
+ "provider-ineligible",
1161
+ "flagged",
1162
+ "disabled",
1163
+ ];
1164
+ const grouped = new Map<RoutingRejectionReason, Map<string, number>>();
1165
+
1166
+ for (const entry of diagnostics) {
1167
+ if (!entry.rejectedReason) continue;
1168
+ const details =
1169
+ grouped.get(entry.rejectedReason) ?? new Map<string, number>();
1170
+ const detail = entry.rejectedDetail || entry.rejectedReason;
1171
+ details.set(detail, (details.get(detail) ?? 0) + 1);
1172
+ grouped.set(entry.rejectedReason, details);
1173
+ }
1174
+
1175
+ const orderedReasons = [
1176
+ ...priority.filter((reason) => grouped.has(reason)),
1177
+ ...Array.from(grouped.keys()).filter(
1178
+ (reason) => !priority.includes(reason),
1179
+ ),
1180
+ ];
1181
+ const summaries: string[] = [];
1182
+ for (const reason of orderedReasons) {
1183
+ const details = grouped.get(reason);
1184
+ if (!details) continue;
1185
+ for (const [detail, count] of details.entries()) {
1186
+ summaries.push(`${count} account${count === 1 ? "" : "s"}: ${detail}`);
1187
+ }
1188
+ }
1189
+
1190
+ return summaries;
1191
+ }
1192
+
1193
+ private compareRoutingCandidate(
1194
+ candidate: {
1195
+ priority: number;
1196
+ quota: number;
1197
+ tier: number;
1198
+ health: number;
1199
+ distance: number;
1200
+ tokenRatio: number;
1201
+ hybridScore: number;
1202
+ },
1203
+ best: {
1204
+ priority: number;
1205
+ quota: number;
1206
+ tier: number;
1207
+ health: number;
1208
+ distance: number;
1209
+ tokenRatio: number;
1210
+ hybridScore: number;
1211
+ },
1212
+ policy: Config["routingPolicy"],
1213
+ ): boolean {
1214
+ if (policy === "sequential-quota") {
1215
+ return candidate.distance < best.distance;
1216
+ }
1217
+ if (policy === "hybrid") {
1218
+ return (
1219
+ candidate.hybridScore > best.hybridScore ||
1220
+ (candidate.hybridScore === best.hybridScore &&
1221
+ candidate.priority < best.priority) ||
1222
+ (candidate.hybridScore === best.hybridScore &&
1223
+ candidate.priority === best.priority &&
1224
+ candidate.distance < best.distance)
1225
+ );
1226
+ }
1227
+ if (policy === "tier-first") {
1228
+ return (
1229
+ candidate.tier < best.tier ||
1230
+ (candidate.tier === best.tier && candidate.quota > best.quota) ||
1231
+ (candidate.tier === best.tier &&
1232
+ candidate.quota === best.quota &&
1233
+ candidate.priority < best.priority) ||
1234
+ (candidate.tier === best.tier &&
1235
+ candidate.quota === best.quota &&
1236
+ candidate.priority === best.priority &&
1237
+ candidate.health > best.health) ||
1238
+ (candidate.tier === best.tier &&
1239
+ candidate.quota === best.quota &&
1240
+ candidate.priority === best.priority &&
1241
+ candidate.health === best.health &&
1242
+ candidate.tokenRatio > best.tokenRatio) ||
1243
+ (candidate.tier === best.tier &&
1244
+ candidate.quota === best.quota &&
1245
+ candidate.priority === best.priority &&
1246
+ candidate.health === best.health &&
1247
+ candidate.tokenRatio === best.tokenRatio &&
1248
+ candidate.distance < best.distance)
1249
+ );
1250
+ }
1251
+ if (policy === "quota-first") {
1252
+ return (
1253
+ candidate.quota > best.quota ||
1254
+ (candidate.quota === best.quota &&
1255
+ candidate.priority < best.priority) ||
1256
+ (candidate.quota === best.quota &&
1257
+ candidate.priority === best.priority &&
1258
+ candidate.tier < best.tier) ||
1259
+ (candidate.quota === best.quota &&
1260
+ candidate.priority === best.priority &&
1261
+ candidate.tier === best.tier &&
1262
+ candidate.health > best.health) ||
1263
+ (candidate.quota === best.quota &&
1264
+ candidate.priority === best.priority &&
1265
+ candidate.tier === best.tier &&
1266
+ candidate.health === best.health &&
1267
+ candidate.tokenRatio > best.tokenRatio) ||
1268
+ (candidate.quota === best.quota &&
1269
+ candidate.priority === best.priority &&
1270
+ candidate.tier === best.tier &&
1271
+ candidate.health === best.health &&
1272
+ candidate.tokenRatio === best.tokenRatio &&
1273
+ candidate.distance < best.distance)
1274
+ );
1275
+ }
1276
+ return (
1277
+ candidate.priority < best.priority ||
1278
+ (candidate.priority === best.priority && candidate.quota > best.quota) ||
1279
+ (candidate.priority === best.priority &&
1280
+ candidate.quota === best.quota &&
1281
+ candidate.tier < best.tier) ||
1282
+ (candidate.priority === best.priority &&
1283
+ candidate.quota === best.quota &&
1284
+ candidate.tier === best.tier &&
1285
+ candidate.health > best.health) ||
1286
+ (candidate.priority === best.priority &&
1287
+ candidate.quota === best.quota &&
1288
+ candidate.tier === best.tier &&
1289
+ candidate.health === best.health &&
1290
+ candidate.tokenRatio > best.tokenRatio) ||
1291
+ (candidate.priority === best.priority &&
1292
+ candidate.quota === best.quota &&
1293
+ candidate.tier === best.tier &&
1294
+ candidate.health === best.health &&
1295
+ candidate.tokenRatio === best.tokenRatio &&
1296
+ candidate.distance < best.distance)
1297
+ );
1298
+ }
1299
+
1300
+ private calculateHybridScore(
1301
+ priority: number,
1302
+ quota: number,
1303
+ tier: number,
1304
+ health: number,
1305
+ tokenRatio: number,
1306
+ distance: number,
1307
+ ): number {
1308
+ const timerScore = (4 - priority) * 35;
1309
+ const quotaScore = Math.max(0, quota) * 0.7;
1310
+ const tierScore = Math.max(0, 4 - tier) * 13.5;
1311
+ const healthScore = Math.max(0, Math.min(1, health)) * 25;
1312
+ const tokenScore = Math.max(0, Math.min(1, tokenRatio)) * 20;
1313
+ const lruScore = Math.max(0, 10 - distance);
1314
+ return Number(
1315
+ (
1316
+ timerScore +
1317
+ quotaScore +
1318
+ tierScore +
1319
+ healthScore +
1320
+ tokenScore +
1321
+ lruScore
1322
+ ).toFixed(3),
1323
+ );
1324
+ }
1325
+
1326
+ private buildRoutingDiagnostics(
1327
+ modelKey: string,
1328
+ now: number,
1329
+ ): RoutingModelDiagnostics {
1330
+ const policy = this.config.routingPolicy || "timer-first";
1331
+ let selectedEmail: string | null = null;
1332
+ let selectedScore = -Infinity;
1333
+ let selectedMetrics: {
1334
+ priority: number;
1335
+ quota: number;
1336
+ tier: number;
1337
+ health: number;
1338
+ distance: number;
1339
+ tokenRatio: number;
1340
+ hybridScore: number;
1341
+ } | null = null;
1342
+ const diagnostics: RoutingAccountDiagnostic[] = [];
1343
+
1344
+ for (let i = 0; i < this.accounts.length; i++) {
1345
+ const account = this.accounts[i];
1346
+ const activeForModels: string[] = [];
1347
+ for (const [model, mState] of this.modelState.entries()) {
1348
+ if (
1349
+ this.accounts[mState.activeAccountIndex] === account &&
1350
+ this.isRoutableForModel(account, model, now)
1351
+ )
1352
+ activeForModels.push(model);
1353
+ }
1354
+ const status = this.getAccountStatusForUi(account, now, activeForModels);
1355
+ const rejection = this.getRoutingRejectionForModel(
1356
+ account,
1357
+ modelKey,
1358
+ now,
1359
+ policy,
1360
+ );
1361
+ const snapshot = this.getTokenBucketSnapshot(account, now);
1362
+ const priority = rejection
1363
+ ? null
1364
+ : this.getModelTimerPriority(account, modelKey);
1365
+ const quota = rejection ? null : this.getModelQuota(account, modelKey);
1366
+ const tierRank = this.getTierRank(account);
1367
+ const distance = i + 1;
1368
+ const healthBreakdown = this.getHealthScoreBreakdown(account);
1369
+ const tokenRatio =
1370
+ snapshot.capacity > 0 ? snapshot.tokens / snapshot.capacity : 0;
1371
+ const hybridScore =
1372
+ rejection || priority === null || quota === null
1373
+ ? null
1374
+ : this.calculateHybridScore(
1375
+ priority,
1376
+ quota,
1377
+ tierRank,
1378
+ healthBreakdown.score,
1379
+ tokenRatio,
1380
+ distance,
1381
+ );
1382
+
1383
+ diagnostics.push({
1384
+ email: account.config.email,
1385
+ label: account.config.label || account.config.email,
1386
+ status,
1387
+ score: hybridScore,
1388
+ timerPriority: priority,
1389
+ quota,
1390
+ tier: account.config.tier || "unknown",
1391
+ healthScore: healthBreakdown.score,
1392
+ healthBreakdown,
1393
+ distance: rejection ? null : distance,
1394
+ tokenBucket: snapshot,
1395
+ rejectedReason: rejection?.reason ?? null,
1396
+ rejectedDetail: rejection?.detail ?? null,
1397
+ });
1398
+
1399
+ if (
1400
+ rejection ||
1401
+ priority === null ||
1402
+ quota === null ||
1403
+ hybridScore === null
1404
+ )
1405
+ continue;
1406
+ const metrics = {
1407
+ priority,
1408
+ quota,
1409
+ tier: tierRank,
1410
+ health: healthBreakdown.score,
1411
+ distance,
1412
+ tokenRatio,
1413
+ hybridScore,
1414
+ };
1415
+ if (
1416
+ !selectedMetrics ||
1417
+ this.compareRoutingCandidate(metrics, selectedMetrics, policy)
1418
+ ) {
1419
+ selectedMetrics = metrics;
1420
+ selectedScore = hybridScore;
1421
+ selectedEmail = account.config.email;
1422
+ }
1423
+ }
1424
+
1425
+ const availableCandidates = diagnostics.filter(
1426
+ (entry) => !entry.rejectedReason,
1427
+ ).length;
1428
+ const rejectedCandidates = diagnostics.length - availableCandidates;
1429
+ let reason = selectedEmail
1430
+ ? `Best route is ${selectedEmail} using ${policy}.`
1431
+ : "No routable account is available for this model.";
1432
+ if (!selectedEmail) {
1433
+ const reasons = this.summarizeRoutingRejections(diagnostics).slice(0, 5);
1434
+ if (reasons.length > 0) reason += ` ${reasons.join("; ")}.`;
1435
+ } else if (policy === "hybrid") {
1436
+ reason = `Best route is ${selectedEmail} using hybrid score ${selectedScore.toFixed(1)}.`;
1437
+ }
1438
+
1439
+ return {
1440
+ modelKey,
1441
+ policy,
1442
+ selectedEmail,
1443
+ reason,
1444
+ availableCandidates,
1445
+ rejectedCandidates,
1446
+ accounts: diagnostics,
1447
+ };
1448
+ }
1449
+
1450
+ // =========================================================================
1451
+ // Account Selection (per-model)
1452
+ // =========================================================================
1453
+
1454
+ // Get the active account for a specific model.
1455
+ // model is the raw model name from the request body.
1456
+ async getActiveAccount(model?: string): Promise<AccountRuntime | null> {
1457
+ const now = Date.now();
1458
+ if (this.accounts.length === 0) return null;
1459
+ if (this.isProtectivePauseActive(now)) return null;
1460
+
1461
+ const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
1462
+ const state = modelKey ? this.modelState.get(modelKey) : null;
1463
+ const idx = state?.activeAccountIndex ?? this.defaultIndex;
1464
+ const current = this.accounts[idx];
1465
+
1466
+ if (
1467
+ modelKey &&
1468
+ !state &&
1469
+ current &&
1470
+ this.isQuotaAwarePolicy() &&
1471
+ this.isRoutableForModel(current, modelKey, now)
1472
+ ) {
1473
+ // Seed the preference on the first request as well. Without this, a
1474
+ // default account that later enters cooldown would be indistinguishable
1475
+ // from an account that was never preferred and could not be restored.
1476
+ this.modelState.set(modelKey, {
1477
+ activeAccountIndex: idx,
1478
+ stickyAccountIndex: idx,
1479
+ quotaAtRotationStart: this.getModelQuota(current, modelKey),
1480
+ requestsOnActiveAccount: 0,
1481
+ });
1482
+ this.scheduleStateSave();
1483
+ }
1484
+
1485
+ if (modelKey && state) {
1486
+ const restored = await this.restorePreferredModelAccount(
1487
+ modelKey,
1488
+ now,
1489
+ state,
1490
+ idx,
1491
+ );
1492
+ if (restored) return restored;
1493
+ }
1494
+
1495
+ if (current && modelKey && !this.isProviderEligibleForKey(current, modelKey)) {
1496
+ this.log(
1497
+ `${current.config.label || current.config.email}: provider mismatch for model, rotating`,
1498
+ "warn",
1499
+ );
1500
+ return this.rotateModelForRequest(modelKey, now, idx);
1501
+ }
1502
+ if (
1503
+ current &&
1504
+ (!modelKey
1505
+ ? this.isAvailable(current, now)
1506
+ : this.isAvailableForModel(current, modelKey, now))
1507
+ ) {
1508
+ // Check if this account has quota for the requested model
1509
+ if (modelKey) {
1510
+ if (this.shouldRotateBeforeRequest(current, modelKey, state ?? null)) {
1511
+ this.log(
1512
+ `${current.config.label || current.config.email} [${modelKey}]: hit rotation threshold (${this.config.requestsPerRotation})`,
1513
+ );
1514
+ const rotated = await this.rotateModelForRequest(modelKey, now, idx);
1515
+ if (rotated) {
1516
+ current.requestsSinceRotation = 0;
1517
+ return rotated;
1518
+ }
1519
+ this.log(
1520
+ `${current.config.label || current.config.email} [${modelKey}]: threshold reached but no replacement is available, staying on current account`,
1521
+ "warn",
1522
+ );
1523
+ }
1524
+ const quota = this.getModelQuota(current, modelKey);
1525
+ if (quota === 0) {
1526
+ this.log(
1527
+ `${current.config.label || current.config.email} [${modelKey}]: 0% quota, skipping`,
1528
+ );
1529
+ return this.rotateModelForRequest(modelKey);
1530
+ }
1531
+ if (!this.isFreshWindowAllowed(current, modelKey)) {
1532
+ const label = current.config.label || current.config.email;
1533
+ this.log(
1534
+ this.hasTimedCandidate(modelKey, now, idx)
1535
+ ? `${label} [${modelKey}]: skipping fresh window because fresh starts are disabled and timed buckets are available`
1536
+ : `${label} [${modelKey}]: fresh window blocked by operator toggle`,
1537
+ "warn",
1538
+ );
1539
+ return this.rotateModelForRequest(modelKey);
1540
+ }
1541
+ if ((this.config.routingPolicy || "timer-first") === "hybrid") {
1542
+ const tokenSnapshot = this.getTokenBucketSnapshot(current, now);
1543
+ if (tokenSnapshot.enabled && tokenSnapshot.tokens < 1) {
1544
+ this.log(
1545
+ `${current.config.label || current.config.email} [${modelKey}]: local token bucket is empty, rotating to another candidate`,
1546
+ "warn",
1547
+ );
1548
+ return this.rotateModelForRequest(modelKey, now, idx);
1549
+ }
1550
+ }
1551
+ }
1552
+ this.startRequest(current, modelKey ?? undefined);
1553
+ try {
1554
+ await this.ensureValidToken(current);
1555
+ if (modelKey) this.countModelAssignment(modelKey);
1556
+ return current;
1557
+ } catch (err) {
1558
+ this.refundTokenBucket(current, Date.now());
1559
+ this.finishRequest(current, modelKey ?? undefined);
1560
+ throw err;
1561
+ }
1562
+ }
1563
+
1564
+ // Current unavailable, or no per-model assignment yet
1565
+ if (modelKey) {
1566
+ return this.rotateModelForRequest(modelKey, now, state ? idx : -1);
1567
+ }
1568
+ return this.rotateDefault();
1569
+ }
1570
+
1571
+ private async restorePreferredModelAccount(
1572
+ modelKey: string,
1573
+ now: number,
1574
+ state: ModelRotationState,
1575
+ activeIndex: number,
1576
+ ): Promise<AccountRuntime | null> {
1577
+ if (!this.isQuotaAwarePolicy()) return null;
1578
+ const preferredIndex = state.stickyAccountIndex;
1579
+ if (
1580
+ preferredIndex === undefined ||
1581
+ preferredIndex === activeIndex ||
1582
+ preferredIndex < 0 ||
1583
+ preferredIndex >= this.accounts.length
1584
+ ) {
1585
+ return null;
1586
+ }
1587
+
1588
+ const preferred = this.accounts[preferredIndex];
1589
+ if (this.getModelQuota(preferred, modelKey) === 0) {
1590
+ // A zero quota is a permanent hand-off for this rotation cycle. The
1591
+ // next selected account becomes the new preference in rotateModel().
1592
+ state.stickyAccountIndex = undefined;
1593
+ this.scheduleStateSave();
1594
+ return null;
1595
+ }
1596
+ if (!this.isRoutableForModel(preferred, modelKey, now)) return null;
1597
+
1598
+ this.log(
1599
+ `[${modelKey}] Restoring preferred account ${preferred.config.label || preferred.config.email} after temporary fallback`,
1600
+ );
1601
+ const restored = await this.activateModelAccount(
1602
+ modelKey,
1603
+ preferred,
1604
+ preferredIndex,
1605
+ );
1606
+ this.countModelAssignment(modelKey);
1607
+ return restored;
1608
+ }
1609
+
1610
+ // Rotate a specific model to the best available account.
1611
+ async rotateModel(
1612
+ modelKey: string,
1613
+ now: number = Date.now(),
1614
+ excludeIdx: number = this.modelState.get(modelKey)?.activeAccountIndex ??
1615
+ -1,
1616
+ ): Promise<AccountRuntime | null> {
1617
+ const best = this.pickBestModelAccount(modelKey, now, excludeIdx);
1618
+
1619
+ if (best) {
1620
+ const previous = this.modelState.get(modelKey);
1621
+ let stickyAccountIndex: number | undefined;
1622
+ if (this.isQuotaAwarePolicy() && previous) {
1623
+ const preferredIndex = previous.stickyAccountIndex;
1624
+ const preferred =
1625
+ preferredIndex === undefined
1626
+ ? undefined
1627
+ : this.accounts[preferredIndex];
1628
+ if (
1629
+ preferredIndex !== undefined &&
1630
+ preferred &&
1631
+ this.getModelQuota(preferred, modelKey) !== 0 &&
1632
+ (preferredIndex !== previous.activeAccountIndex ||
1633
+ !this.isAvailableForModel(preferred, modelKey, now))
1634
+ ) {
1635
+ // Keep the original account as the preference while a cooldown,
1636
+ // breaker, or concurrency limit forces a temporary fallback.
1637
+ stickyAccountIndex = preferredIndex;
1638
+ }
1639
+ }
1640
+ const quota = this.getModelQuota(best, modelKey);
1641
+ const timerType = this.getModelTimerType(best, modelKey);
1642
+ this.log(
1643
+ `[${modelKey}] Rotated to ${best.config.label || best.config.email} [${timerType}] (quota: ${quota >= 0 ? quota + "%" : "unknown"})`,
1644
+ );
1645
+ return this.activateModelAccount(modelKey, best, stickyAccountIndex);
1646
+ }
1647
+
1648
+ if (
1649
+ !this.allowFreshWindowStarts &&
1650
+ this.accounts.some((account, idx) => {
1651
+ if (idx === excludeIdx) return false;
1652
+ if (!this.isAvailableForModel(account, modelKey, now)) return false;
1653
+ if (this.getModelQuota(account, modelKey) === 0) return false;
1654
+ return this.getModelTimerType(account, modelKey) === "fresh";
1655
+ })
1656
+ ) {
1657
+ this.log(
1658
+ `[${modelKey}] Fresh windows are available but blocked by operator toggle; keeping routing on existing timed buckets only`,
1659
+ "warn",
1660
+ );
1661
+ return null;
1662
+ }
1663
+
1664
+ const shortestCooldown = this.accounts.reduce<number | null>(
1665
+ (bestRemaining, account) => {
1666
+ if (account.disabled || account.flagged) return bestRemaining;
1667
+ const defaultCooldown = account.cooldownsByModel["__default__"] ?? 0;
1668
+ if (defaultCooldown <= now) return bestRemaining;
1669
+ const remaining = defaultCooldown - now;
1670
+ if (bestRemaining === null || remaining < bestRemaining)
1671
+ return remaining;
1672
+ return bestRemaining;
1673
+ },
1674
+ null,
1675
+ );
1676
+
1677
+ if (shortestCooldown !== null) {
1678
+ this.log(
1679
+ `[${modelKey}] All accounts exhausted. Waiting ${Math.ceil(shortestCooldown / 1000)}s for cooldown`,
1680
+ );
1681
+ } else {
1682
+ const diagnostics = this.buildRoutingDiagnostics(modelKey, now);
1683
+ this.routingDiagnostics[modelKey] = diagnostics;
1684
+ this.log(
1685
+ `[${modelKey}] All accounts disabled or unavailable: ${diagnostics.reason}`,
1686
+ "warn",
1687
+ );
1688
+ }
1689
+ return null;
1690
+ }
1691
+
1692
+ private async activateModelAccount(
1693
+ modelKey: string,
1694
+ account: AccountRuntime,
1695
+ stickyAccountIndex?: number,
1696
+ ): Promise<AccountRuntime> {
1697
+ const newIdx = this.accounts.indexOf(account);
1698
+ const quota = this.getModelQuota(account, modelKey);
1699
+ this.modelState.set(modelKey, {
1700
+ activeAccountIndex: newIdx,
1701
+ stickyAccountIndex: this.isQuotaAwarePolicy()
1702
+ ? stickyAccountIndex ?? newIdx
1703
+ : undefined,
1704
+ quotaAtRotationStart: quota,
1705
+ requestsOnActiveAccount: 0,
1706
+ });
1707
+ await this.saveState();
1708
+ this.startRequest(account, modelKey);
1709
+ try {
1710
+ await this.ensureValidToken(account);
1711
+ return account;
1712
+ } catch (err) {
1713
+ this.refundTokenBucket(account, Date.now());
1714
+ this.finishRequest(account, modelKey);
1715
+ throw err;
1716
+ }
1717
+ }
1718
+
1719
+ // Fallback rotation when model can't be resolved
1720
+ private async rotateDefault(
1721
+ now: number = Date.now(),
1722
+ ): Promise<AccountRuntime | null> {
1723
+ let best: AccountRuntime | null = null;
1724
+
1725
+ for (let i = 0; i < this.accounts.length; i++) {
1726
+ if (i === this.defaultIndex) continue;
1727
+ const account = this.accounts[i];
1728
+ if (this.isAvailable(account, now)) {
1729
+ best = account;
1730
+ break;
1731
+ }
1732
+ }
1733
+
1734
+ if (best) {
1735
+ this.defaultIndex = this.accounts.indexOf(best);
1736
+ this.log(
1737
+ `[default] Rotated to ${best.config.label || best.config.email}`,
1738
+ );
1739
+ await this.saveState();
1740
+ this.startRequest(best);
1741
+ try {
1742
+ await this.ensureValidToken(best);
1743
+ return best;
1744
+ } catch (err) {
1745
+ this.refundTokenBucket(best, Date.now());
1746
+ this.finishRequest(best);
1747
+ throw err;
1748
+ }
1749
+ }
1750
+
1751
+ const shortestCooldown = this.accounts.reduce<number | null>(
1752
+ (bestRemaining, account) => {
1753
+ if (account.disabled || account.flagged) return bestRemaining;
1754
+ const defaultCooldown = account.cooldownsByModel["__default__"] ?? 0;
1755
+ if (defaultCooldown <= now) return bestRemaining;
1756
+ const remaining = defaultCooldown - now;
1757
+ if (bestRemaining === null || remaining < bestRemaining)
1758
+ return remaining;
1759
+ return bestRemaining;
1760
+ },
1761
+ null,
1762
+ );
1763
+
1764
+ if (shortestCooldown !== null) {
1765
+ this.log(
1766
+ `[default] All accounts exhausted. Waiting ${Math.ceil(shortestCooldown / 1000)}s for cooldown`,
1767
+ );
1768
+ } else {
1769
+ this.log("[default] All accounts disabled or unavailable");
1770
+ }
1771
+ return null;
1772
+ }
1773
+
1774
+ // Force rotation for a model (called from proxy on 429 etc.)
1775
+ async rotateToNext(model?: string): Promise<AccountRuntime | null> {
1776
+ if (this.isProtectivePauseActive(Date.now())) return null;
1777
+ const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
1778
+ return modelKey ? this.rotateModel(modelKey) : this.rotateDefault();
1779
+ }
1780
+
1781
+ // Record a successful request. Returns true if rotation is needed.
1782
+ recordRequest(account: AccountRuntime, model?: string): boolean {
1783
+ account.requestsSinceRotation++;
1784
+ account.totalRequests++;
1785
+ account.lastUsed = Date.now();
1786
+ account.consecutiveErrors = 0;
1787
+ account.lastError = null;
1788
+
1789
+ const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
1790
+ const state = modelKey ? this.modelState.get(modelKey) : null;
1791
+ const shouldRotate =
1792
+ !!modelKey &&
1793
+ !!state &&
1794
+ this.accounts[state.activeAccountIndex] === account &&
1795
+ this.shouldUseRequestCountRotation(account, modelKey) &&
1796
+ state.requestsOnActiveAccount >= this.config.requestsPerRotation;
1797
+
1798
+ this.scheduleStateSave();
1799
+ if (shouldRotate) {
1800
+ this.log(
1801
+ `${account.config.label || account.config.email} [${modelKey}]: hit rotation threshold (${state.requestsOnActiveAccount}/${this.config.requestsPerRotation})`,
1802
+ );
1803
+ }
1804
+ return shouldRotate;
1805
+ }
1806
+
1807
+ // Record token usage from a completed request
1808
+ recordTokenUsage(
1809
+ model: string | undefined,
1810
+ inputTokens: number,
1811
+ outputTokens: number,
1812
+ ): void {
1813
+ const now = new Date();
1814
+ const minuteKey = now.toISOString().slice(0, 16); // "2026-04-28T12:05"
1815
+ const modelKey = model ? resolveDisplayModelKey(model) : "unknown";
1816
+
1817
+ // Upsert minute bucket
1818
+ let bucket = this.tokenBuckets.minutes.find((b) => b.period === minuteKey);
1819
+ if (!bucket) {
1820
+ bucket = {
1821
+ period: minuteKey,
1822
+ inputTokens: 0,
1823
+ outputTokens: 0,
1824
+ requests: 0,
1825
+ byModel: {},
1826
+ };
1827
+ this.tokenBuckets.minutes.push(bucket);
1828
+ }
1829
+ bucket.inputTokens += inputTokens;
1830
+ bucket.outputTokens += outputTokens;
1831
+ bucket.requests += 1;
1832
+ if (!bucket.byModel[modelKey]) {
1833
+ bucket.byModel[modelKey] = {
1834
+ inputTokens: 0,
1835
+ outputTokens: 0,
1836
+ requests: 0,
1837
+ };
1838
+ }
1839
+ bucket.byModel[modelKey].inputTokens += inputTokens;
1840
+ bucket.byModel[modelKey].outputTokens += outputTokens;
1841
+ bucket.byModel[modelKey].requests += 1;
1842
+
1843
+ // Lazy consolidation
1844
+ this.consolidateTokenBuckets(now);
1845
+ this.scheduleTokenUsageSave();
1846
+ }
1847
+
1848
+ recordLatency(
1849
+ model: string | undefined,
1850
+ ttfbMs: number,
1851
+ totalMs: number,
1852
+ ): void {
1853
+ const modelKey = model ? resolveDisplayModelKey(model) : "unknown";
1854
+ let records = this.latencyRecords.get(modelKey);
1855
+ if (!records) {
1856
+ records = [];
1857
+ this.latencyRecords.set(modelKey, records);
1858
+ }
1859
+ records.push({ ttfbMs, totalMs });
1860
+ if (records.length > AccountRotator.MAX_LATENCY_RECORDS) {
1861
+ records.splice(0, records.length - AccountRotator.MAX_LATENCY_RECORDS);
1862
+ }
1863
+ }
1864
+
1865
+ getLatencyStats(): Record<
1866
+ string,
1867
+ {
1868
+ ttfb: { p50: number; p95: number };
1869
+ total: { p50: number; p95: number };
1870
+ count: number;
1871
+ }
1872
+ > {
1873
+ const stats: Record<
1874
+ string,
1875
+ {
1876
+ ttfb: { p50: number; p95: number };
1877
+ total: { p50: number; p95: number };
1878
+ count: number;
1879
+ }
1880
+ > = {};
1881
+ for (const [model, records] of this.latencyRecords) {
1882
+ if (records.length === 0) continue;
1883
+ const ttfbs = records.map((r) => r.ttfbMs).sort((a, b) => a - b);
1884
+ const totals = records.map((r) => r.totalMs).sort((a, b) => a - b);
1885
+ stats[model] = {
1886
+ ttfb: {
1887
+ p50: ttfbs[Math.floor(ttfbs.length * 0.5)],
1888
+ p95: ttfbs[Math.floor(ttfbs.length * 0.95)],
1889
+ },
1890
+ total: {
1891
+ p50: totals[Math.floor(totals.length * 0.5)],
1892
+ p95: totals[Math.floor(totals.length * 0.95)],
1893
+ },
1894
+ count: records.length,
1895
+ };
1896
+ }
1897
+ return stats;
1898
+ }
1899
+
1900
+ recordRequestLog(entry: {
1901
+ model: string;
1902
+ account: string;
1903
+ statusCode: number;
1904
+ ttfbMs: number;
1905
+ totalMs: number;
1906
+ inputTokens: number;
1907
+ outputTokens: number;
1908
+ }): void {
1909
+ const ollamaAccount = this.accounts.find(
1910
+ (a) =>
1911
+ hasCredential(a.config, "ollama") &&
1912
+ (a.config.email === entry.account ||
1913
+ a.config.label === entry.account),
1914
+ );
1915
+ if (ollamaAccount && entry.statusCode >= 200 && entry.statusCode < 300) {
1916
+ this.usagePredictor.recordUsage(
1917
+ ollamaAccount.config.email,
1918
+ entry.model,
1919
+ entry.inputTokens,
1920
+ entry.outputTokens,
1921
+ );
1922
+ }
1923
+ this.requestLog.unshift({
1924
+ timestamp: Date.now(),
1925
+ ...entry,
1926
+ });
1927
+ if (this.requestLog.length > AccountRotator.MAX_REQUEST_LOG) {
1928
+ this.requestLog.length = AccountRotator.MAX_REQUEST_LOG;
1929
+ }
1930
+ }
1931
+
1932
+ getPredictionSummary(): Record<string, ExhaustionPrediction> {
1933
+ const result: Record<string, ExhaustionPrediction> = {};
1934
+ const now = Date.now();
1935
+ for (const account of this.accounts) {
1936
+ if (!hasCredential(account.config, "ollama")) continue;
1937
+ const session = account.quota.find((q) => q.modelKey === "session");
1938
+ const weekly = account.quota.find((q) => q.modelKey === "weekly");
1939
+ if (
1940
+ !session ||
1941
+ !weekly ||
1942
+ !Number.isFinite(session.usageRaw) ||
1943
+ !Number.isFinite(weekly.usageRaw)
1944
+ ) {
1945
+ continue;
1946
+ }
1947
+ const model = this.getOllamaModels()[0] ?? "gpt-oss:20b";
1948
+ result[account.config.email] = this.usagePredictor.predict(
1949
+ account.config.email,
1950
+ model,
1951
+ session.usageRaw ?? 0,
1952
+ weekly.usageRaw ?? 0,
1953
+ now,
1954
+ );
1955
+ }
1956
+ return result;
1957
+ }
1958
+
1959
+ private consolidateTokenBuckets(now: Date): void {
1960
+ const nowMs = now.getTime();
1961
+ const KEEP_MINUTES_MS = 12 * 3600 * 1000; // keep 12h of minutes
1962
+ const KEEP_HOURS_MS = 60 * 86400 * 1000; // keep 60d of hours
1963
+ const KEEP_DAYS_MS = 60 * 86400 * 1000; // keep 60d of days
1964
+
1965
+ // Helper: parse period string to epoch ms (approximate, enough for cutoff)
1966
+ const periodToMs = (p: string): number =>
1967
+ new Date(p.length <= 7 ? p + "-01" : p).getTime();
1968
+
1969
+ // Minutes older than 2h → consolidate into hours, keep rest
1970
+ const minuteCutoff = nowMs - KEEP_MINUTES_MS;
1971
+ const staleMinutes = this.tokenBuckets.minutes.filter(
1972
+ (b) => periodToMs(b.period) < minuteCutoff,
1973
+ );
1974
+ if (staleMinutes.length > 0) {
1975
+ const byHour = new Map<string, TokenBucket>();
1976
+ for (const m of staleMinutes) {
1977
+ const hKey = m.period.slice(0, 13);
1978
+ let h = byHour.get(hKey);
1979
+ if (!h) {
1980
+ h = {
1981
+ period: hKey,
1982
+ inputTokens: 0,
1983
+ outputTokens: 0,
1984
+ requests: 0,
1985
+ byModel: {},
1986
+ };
1987
+ byHour.set(hKey, h);
1988
+ }
1989
+ this.mergeBucket(h, m);
1990
+ }
1991
+ for (const [hKey, consolidated] of byHour) {
1992
+ const existing = this.tokenBuckets.hours.find((b) => b.period === hKey);
1993
+ if (existing) {
1994
+ this.mergeBucket(existing, consolidated);
1995
+ } else {
1996
+ this.tokenBuckets.hours.push(consolidated);
1997
+ }
1998
+ }
1999
+ this.tokenBuckets.minutes = this.tokenBuckets.minutes.filter(
2000
+ (b) => periodToMs(b.period) >= minuteCutoff,
2001
+ );
2002
+ }
2003
+
2004
+ // Hours older than 48h → consolidate into days
2005
+ const hourCutoff = nowMs - KEEP_HOURS_MS;
2006
+ const staleHours = this.tokenBuckets.hours.filter(
2007
+ (b) => periodToMs(b.period) < hourCutoff,
2008
+ );
2009
+ if (staleHours.length > 0) {
2010
+ const byDay = new Map<string, TokenBucket>();
2011
+ for (const h of staleHours) {
2012
+ const dKey = h.period.slice(0, 10);
2013
+ let d = byDay.get(dKey);
2014
+ if (!d) {
2015
+ d = {
2016
+ period: dKey,
2017
+ inputTokens: 0,
2018
+ outputTokens: 0,
2019
+ requests: 0,
2020
+ byModel: {},
2021
+ };
2022
+ byDay.set(dKey, d);
2023
+ }
2024
+ this.mergeBucket(d, h);
2025
+ }
2026
+ for (const [dKey, consolidated] of byDay) {
2027
+ const existing = this.tokenBuckets.days.find((b) => b.period === dKey);
2028
+ if (existing) {
2029
+ this.mergeBucket(existing, consolidated);
2030
+ } else {
2031
+ this.tokenBuckets.days.push(consolidated);
2032
+ }
2033
+ }
2034
+ this.tokenBuckets.hours = this.tokenBuckets.hours.filter(
2035
+ (b) => periodToMs(b.period) >= hourCutoff,
2036
+ );
2037
+ }
2038
+
2039
+ // Days older than 60d → consolidate into months
2040
+ const dayCutoff = nowMs - KEEP_DAYS_MS;
2041
+ const staleDays = this.tokenBuckets.days.filter(
2042
+ (b) => periodToMs(b.period) < dayCutoff,
2043
+ );
2044
+ if (staleDays.length > 0) {
2045
+ const byMonth = new Map<string, TokenBucket>();
2046
+ for (const d of staleDays) {
2047
+ const mKey = d.period.slice(0, 7);
2048
+ let mo = byMonth.get(mKey);
2049
+ if (!mo) {
2050
+ mo = {
2051
+ period: mKey,
2052
+ inputTokens: 0,
2053
+ outputTokens: 0,
2054
+ requests: 0,
2055
+ byModel: {},
2056
+ };
2057
+ byMonth.set(mKey, mo);
2058
+ }
2059
+ this.mergeBucket(mo, d);
2060
+ }
2061
+ for (const [mKey, consolidated] of byMonth) {
2062
+ const existing = this.tokenBuckets.months.find(
2063
+ (b) => b.period === mKey,
2064
+ );
2065
+ if (existing) {
2066
+ this.mergeBucket(existing, consolidated);
2067
+ } else {
2068
+ this.tokenBuckets.months.push(consolidated);
2069
+ }
2070
+ }
2071
+ this.tokenBuckets.days = this.tokenBuckets.days.filter(
2072
+ (b) => periodToMs(b.period) >= dayCutoff,
2073
+ );
2074
+ }
2075
+ }
2076
+
2077
+ private mergeBucket(target: TokenBucket, source: TokenBucket): void {
2078
+ target.inputTokens += source.inputTokens;
2079
+ target.outputTokens += source.outputTokens;
2080
+ target.requests += source.requests;
2081
+ for (const [model, data] of Object.entries(source.byModel)) {
2082
+ if (!target.byModel[model]) {
2083
+ target.byModel[model] = {
2084
+ inputTokens: 0,
2085
+ outputTokens: 0,
2086
+ requests: 0,
2087
+ };
2088
+ }
2089
+ target.byModel[model].inputTokens += data.inputTokens;
2090
+ target.byModel[model].outputTokens += data.outputTokens;
2091
+ target.byModel[model].requests += data.requests;
2092
+ }
2093
+ }
2094
+
2095
+ private getTierRank(account: AccountRuntime): number {
2096
+ const tier = account.config.tier || "unknown";
2097
+ if (tier === "ultra") return 0;
2098
+ if (tier === "pro") return 1;
2099
+ if (tier === "plus") return 2;
2100
+ if (tier === "free") return 3;
2101
+ return 4;
2102
+ }
2103
+
2104
+ private refreshHealthScores(): void {
2105
+ for (const account of this.accounts) {
2106
+ account.healthScore = this.getHealthScoreBreakdown(account).score;
2107
+ }
2108
+ }
2109
+
2110
+ private getHealthScoreBreakdown(
2111
+ account: AccountRuntime,
2112
+ ): HealthScoreBreakdown {
2113
+ const quotaAverage =
2114
+ account.quota.length > 0
2115
+ ? account.quota.reduce(
2116
+ (sum, quota) => sum + quota.percentRemaining,
2117
+ 0,
2118
+ ) / account.quota.length
2119
+ : 50;
2120
+ const errorPenalty = Math.min(0.5, account.consecutiveErrors * 0.1);
2121
+ const cooldownPenalty =
2122
+ Object.keys(account.cooldownsByModel).length > 0 ? 0.1 : 0;
2123
+ const availabilityPenalty = account.flagged
2124
+ ? 1
2125
+ : account.disabled
2126
+ ? 0.75
2127
+ : 0;
2128
+ const score = Number(
2129
+ Math.max(
2130
+ 0,
2131
+ Math.min(
2132
+ 1,
2133
+ quotaAverage / 100 -
2134
+ errorPenalty -
2135
+ cooldownPenalty -
2136
+ availabilityPenalty,
2137
+ ),
2138
+ ).toFixed(4),
2139
+ );
2140
+ return {
2141
+ quotaComponent: quotaAverage / 100,
2142
+ errorPenalty,
2143
+ cooldownPenalty,
2144
+ availabilityPenalty,
2145
+ score,
2146
+ };
2147
+ }
2148
+
2149
+ private async saveTokenUsage(): Promise<void> {
2150
+ try {
2151
+ await setCachedTokenUsage(this.tokenBuckets);
2152
+ } catch {
2153
+ /* best effort */
2154
+ }
2155
+ }
2156
+
2157
+ /**
2158
+ * Schedule a debounced token-usage save. Same coalescing pattern as
2159
+ * scheduleStateSave: multiple calls within TOKEN_USAGE_SAVE_DEBOUNCE_MS
2160
+ * collapse into a single write. recordTokenUsage() calls this instead of
2161
+ * saveTokenUsage() to avoid blocking the event loop on every request.
2162
+ */
2163
+ scheduleTokenUsageSave(): void {
2164
+ if (this.tokenUsageSaveTimer) return;
2165
+ this.tokenUsageSaveTimer = setTimeout(() => {
2166
+ this.tokenUsageSaveTimer = null;
2167
+ void this.runScheduledTokenUsageSave();
2168
+ }, AccountRotator.TOKEN_USAGE_SAVE_DEBOUNCE_MS);
2169
+ if (this.tokenUsageSaveTimer.unref) this.tokenUsageSaveTimer.unref();
2170
+ }
2171
+
2172
+ private async runScheduledTokenUsageSave(): Promise<void> {
2173
+ if (this.tokenUsageSaveInflight) {
2174
+ this.tokenUsageSavePending = true;
2175
+ return;
2176
+ }
2177
+ this.tokenUsageSaveInflight = true;
2178
+ try {
2179
+ await this.saveTokenUsage();
2180
+ } finally {
2181
+ this.tokenUsageSaveInflight = false;
2182
+ if (this.tokenUsageSavePending) {
2183
+ this.tokenUsageSavePending = false;
2184
+ this.scheduleTokenUsageSave();
2185
+ }
2186
+ }
2187
+ }
2188
+
2189
+ /**
2190
+ * Force-flush any pending token-usage write. Called by SIGTERM/SIGINT in
2191
+ * index.ts to minimise data loss on shutdown.
2192
+ */
2193
+ async flushPendingTokenUsageSave(): Promise<void> {
2194
+ if (this.tokenUsageSaveTimer) {
2195
+ clearTimeout(this.tokenUsageSaveTimer);
2196
+ this.tokenUsageSaveTimer = null;
2197
+ }
2198
+ await this.saveTokenUsage();
2199
+ }
2200
+
2201
+ getTokenUsage(): TokenUsageData {
2202
+ // Buckets are hierarchical rollups: minutes → hours → days → months.
2203
+ // A minute period that has already been rolled into an hour bucket must
2204
+ // NOT be counted again. Same logic applies to hours→days and days→months.
2205
+ const hourPeriods = new Set(this.tokenBuckets.hours.map((b) => b.period));
2206
+ const dayPeriods = new Set(this.tokenBuckets.days.map((b) => b.period));
2207
+ const monthPeriods = new Set(this.tokenBuckets.months.map((b) => b.period));
2208
+
2209
+ const minutesFiltered = this.tokenBuckets.minutes.filter(
2210
+ (b) => !hourPeriods.has(b.period.slice(0, 13)),
2211
+ );
2212
+ const hoursFiltered = this.tokenBuckets.hours.filter(
2213
+ (b) => !dayPeriods.has(b.period.slice(0, 10)),
2214
+ );
2215
+ const daysFiltered = this.tokenBuckets.days.filter(
2216
+ (b) => !monthPeriods.has(b.period.slice(0, 7)),
2217
+ );
2218
+
2219
+ const all = [
2220
+ ...minutesFiltered,
2221
+ ...hoursFiltered,
2222
+ ...daysFiltered,
2223
+ ...this.tokenBuckets.months,
2224
+ ];
2225
+ let totalInputTokens = 0;
2226
+ let totalOutputTokens = 0;
2227
+ let totalRequests = 0;
2228
+ const modelTotals: Record<string, { input: number; output: number }> = {};
2229
+ for (const b of all) {
2230
+ totalInputTokens += b.inputTokens;
2231
+ totalOutputTokens += b.outputTokens;
2232
+ totalRequests += b.requests;
2233
+ for (const [model, data] of Object.entries(b.byModel)) {
2234
+ if (!modelTotals[model]) modelTotals[model] = { input: 0, output: 0 };
2235
+ modelTotals[model].input += data.inputTokens;
2236
+ modelTotals[model].output += data.outputTokens;
2237
+ }
2238
+ }
2239
+
2240
+ // Calculate savings
2241
+ let totalUsd = 0;
2242
+ const byModel: TokenUsageData["savings"]["byModel"] = {};
2243
+ for (const [model, totals] of Object.entries(modelTotals)) {
2244
+ let pricing = MODEL_PRICING[model];
2245
+ if (!pricing) {
2246
+ const lower = model.toLowerCase();
2247
+ if (lower.includes("opus")) pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
2248
+ else if (lower.includes("sonnet")) pricing = MODEL_PRICING["claude-sonnet-4-6"];
2249
+ else if (lower.includes("3.6-flash")) pricing = MODEL_PRICING["gemini-3.6-flash-high"];
2250
+ else if (lower.includes("3.5-flash")) pricing = MODEL_PRICING["gemini-3.5-flash-high"];
2251
+ else if (lower.includes("flash")) pricing = MODEL_PRICING["gemini-3-flash"];
2252
+ else if (lower.includes("pro")) pricing = MODEL_PRICING["gemini-3.1-pro"];
2253
+ }
2254
+ if (!pricing) continue;
2255
+ const inputUsd = (totals.input / 1_000_000) * pricing.inputPer1M;
2256
+ const outputUsd = (totals.output / 1_000_000) * pricing.outputPer1M;
2257
+ byModel[model] = { inputUsd, outputUsd, totalUsd: inputUsd + outputUsd };
2258
+ totalUsd += inputUsd + outputUsd;
2259
+ }
2260
+
2261
+ // Build tokensByModel with raw counts (from deduplicated buckets)
2262
+ const tokensByModel: Record<
2263
+ string,
2264
+ { input: number; output: number; requests: number }
2265
+ > = {};
2266
+ for (const [model, t] of Object.entries(modelTotals)) {
2267
+ tokensByModel[model] = { input: t.input, output: t.output, requests: 0 };
2268
+ }
2269
+ for (const b of all) {
2270
+ for (const [model, data] of Object.entries(b.byModel)) {
2271
+ if (tokensByModel[model])
2272
+ tokensByModel[model].requests += data.requests;
2273
+ }
2274
+ }
2275
+
2276
+ return {
2277
+ minutes: this.tokenBuckets.minutes
2278
+ .slice()
2279
+ .sort((a, b) => a.period.localeCompare(b.period)),
2280
+ hours: this.tokenBuckets.hours
2281
+ .slice()
2282
+ .sort((a, b) => a.period.localeCompare(b.period)),
2283
+ days: this.tokenBuckets.days
2284
+ .slice()
2285
+ .sort((a, b) => a.period.localeCompare(b.period)),
2286
+ months: this.tokenBuckets.months
2287
+ .slice()
2288
+ .sort((a, b) => a.period.localeCompare(b.period)),
2289
+ totalInputTokens,
2290
+ totalOutputTokens,
2291
+ totalRequests,
2292
+ tokensByModel,
2293
+ savings: { totalUsd, byModel },
2294
+ };
2295
+ }
2296
+
2297
+ // Mark an account as exhausted (429 or quota exceeded)
2298
+ markExhausted(
2299
+ account: AccountRuntime,
2300
+ model: string | undefined,
2301
+ cooldownMs: number,
2302
+ errorText?: string,
2303
+ ): void {
2304
+ const now = Date.now();
2305
+ const modelKey = model
2306
+ ? (resolveQuotaModelKey(model) ?? "__default__")
2307
+ : "__default__";
2308
+ account.cooldownsByModel[modelKey] = now + cooldownMs;
2309
+ account.quotaExhaustedAt = now;
2310
+
2311
+ const errorDetail = errorText ? ` | ${errorText}` : "";
2312
+ this.log(
2313
+ `${account.config.label || account.config.email} [${modelKey}]: EXHAUSTED, cooldown ${Math.ceil(cooldownMs / 1000)}s${errorDetail}`,
2314
+ "warn",
2315
+ );
2316
+ this.scheduleStateSave();
2317
+ }
2318
+
2319
+ recordProvider429(
2320
+ account: AccountRuntime,
2321
+ model: string | undefined,
2322
+ cooldownMs: number,
2323
+ providerResourceExhausted = false,
2324
+ ): void {
2325
+ const now = Date.now();
2326
+ if (providerResourceExhausted) {
2327
+ // Account-level daily/weekly quota exhaustion is not a model outage:
2328
+ // the account already gets an individual cooldown from markExhausted,
2329
+ // so it must not arm the project or model circuit breaker and block
2330
+ // healthy accounts that still have quota.
2331
+ return;
2332
+ }
2333
+ const modelKey = model
2334
+ ? (resolveQuotaModelKey(model) ?? "__default__")
2335
+ : "__default__";
2336
+ const windowMs =
2337
+ this.config.projectCircuitBreakerWindowMs ?? 10 * 60 * 1000;
2338
+ const threshold = this.config.projectCircuitBreaker429Threshold ?? 3;
2339
+ const breakerCooldownMs =
2340
+ this.config.projectCircuitBreakerCooldownMs ?? 60 * 60 * 1000;
2341
+ const projectId = account.config.projectId ?? "";
2342
+ this.provider429Events = this.provider429Events
2343
+ .filter((event) => now - event.ts <= windowMs)
2344
+ .concat({ ts: now, projectId, modelKey, account: account.config.email });
2345
+ const uniqueAccounts = new Set(
2346
+ this.provider429Events
2347
+ .filter(
2348
+ (event) =>
2349
+ event.projectId === projectId && event.modelKey === modelKey,
2350
+ )
2351
+ .map((event) => event.account),
2352
+ );
2353
+ const modelUniqueAccounts = new Set(
2354
+ this.provider429Events
2355
+ .filter((event) => event.modelKey === modelKey)
2356
+ .map((event) => event.account),
2357
+ );
2358
+ if (uniqueAccounts.size >= threshold) {
2359
+ const until = now + Math.max(cooldownMs, breakerCooldownMs);
2360
+ this.projectModelBreakers[projectModelKey(projectId, modelKey)] = until;
2361
+ this.log(
2362
+ `[${modelKey}] Project circuit breaker active for projectId=${projectId} after ${uniqueAccounts.size} accounts hit 429; cooldown ${Math.ceil((until - now) / 1000)}s`,
2363
+ "warn",
2364
+ );
2365
+ }
2366
+ const modelThreshold =
2367
+ this.config.modelCircuitBreaker429Threshold ?? threshold;
2368
+ if (modelUniqueAccounts.size >= modelThreshold) {
2369
+ const until =
2370
+ now +
2371
+ Math.max(
2372
+ cooldownMs,
2373
+ this.config.modelCircuitBreakerCooldownMs ?? 6 * 60 * 60 * 1000,
2374
+ );
2375
+ this.modelBreakers[modelKey] = until;
2376
+ this.log(
2377
+ `[${modelKey}] Model circuit breaker active after ${modelUniqueAccounts.size} unique accounts hit provider 429; cooldown ${Math.ceil((until - now) / 1000)}s`,
2378
+ "warn",
2379
+ );
2380
+ }
2381
+ void this.saveState();
2382
+ }
2383
+
2384
+ recordUpstreamAttempt(account: AccountRuntime): void {
2385
+ const now = Date.now();
2386
+ this.rollDailySafetyIfNeeded(now);
2387
+ this.getAccountDailyCount(account, now);
2388
+ account.dailyRequestCount++;
2389
+ this.projectRequests[account.config.projectId ?? ""] =
2390
+ (this.projectRequests[account.config.projectId ?? ""] ?? 0) + 1;
2391
+ this.scheduleStateSave();
2392
+ }
2393
+
2394
+ getSafetyJitterMs(account: AccountRuntime): number {
2395
+ const now = Date.now();
2396
+ const accountSlow =
2397
+ this.getAccountDailyCount(account, now) >=
2398
+ (this.config.dailyAccountSlowRequests ?? 250);
2399
+ const projectSlow =
2400
+ this.getProjectDailyCount(account.config.projectId ?? "", now) >=
2401
+ (this.config.dailyProjectSlowRequests ?? 900);
2402
+ if (!accountSlow && !projectSlow) return 0;
2403
+ const min = this.config.slowModeJitterMinMs ?? 8_000;
2404
+ const max = Math.max(min, this.config.slowModeJitterMaxMs ?? 25_000);
2405
+ return Math.floor(min + Math.random() * (max - min + 1));
2406
+ }
2407
+
2408
+ getGlobalDelayMs(): number {
2409
+ return this.config.globalRequestDelayMs ?? 0;
2410
+ }
2411
+
2412
+ markError(account: AccountRuntime, error: string): void {
2413
+ account.lastError = error;
2414
+ account.consecutiveErrors++;
2415
+ if (account.consecutiveErrors >= 5) {
2416
+ account.disabled = true;
2417
+ this.log(
2418
+ `${account.config.email}: DISABLED after ${account.consecutiveErrors} consecutive errors`,
2419
+ "error",
2420
+ );
2421
+ }
2422
+ this.scheduleStateSave();
2423
+ }
2424
+
2425
+ async enableAccount(email: string): Promise<boolean> {
2426
+ const account = this.accounts.find((a) => a.config.email === email);
2427
+ if (!account) return false;
2428
+ if (account.flagged) {
2429
+ this.log(
2430
+ `${email}: refused re-enable because account is flagged; resolve the provider block first`,
2431
+ "warn",
2432
+ );
2433
+ return false;
2434
+ }
2435
+ account.disabled = false;
2436
+ account.flagged = false;
2437
+ account.consecutiveErrors = 0;
2438
+ account.lastError = null;
2439
+ account.cooldownsByModel = {};
2440
+ await this.saveState();
2441
+ this.log(`${email}: re-enabled`);
2442
+ return true;
2443
+ }
2444
+
2445
+ async disableAccount(email: string): Promise<boolean> {
2446
+ const account = this.accounts.find((a) => a.config.email === email);
2447
+ if (!account) return false;
2448
+ account.disabled = true;
2449
+ account.lastError = "Disabled by operator";
2450
+ await this.saveState();
2451
+ this.log(`${email}: disabled by operator`, "warn");
2452
+ return true;
2453
+ }
2454
+
2455
+ async quarantineAccount(
2456
+ email: string,
2457
+ reason = "Quarantined by operator",
2458
+ ): Promise<boolean> {
2459
+ const account = this.accounts.find((a) => a.config.email === email);
2460
+ if (!account) return false;
2461
+ account.flagged = true;
2462
+ account.lastError = reason;
2463
+ await this.saveState();
2464
+ this.log(`${email}: quarantined by operator`, "warn");
2465
+ return true;
2466
+ }
2467
+
2468
+ async restoreAccount(email: string): Promise<boolean> {
2469
+ const account = this.accounts.find((a) => a.config.email === email);
2470
+ if (!account) return false;
2471
+ account.disabled = false;
2472
+ account.flagged = false;
2473
+ account.consecutiveErrors = 0;
2474
+ account.lastError = null;
2475
+ await this.saveState();
2476
+ this.log(`${email}: restored by operator`, "warn");
2477
+ return true;
2478
+ }
2479
+
2480
+ async updateAccountMetadata(
2481
+ email: string,
2482
+ patch: Partial<AccountConfig>,
2483
+ ): Promise<boolean> {
2484
+ const account = this.accounts.find((a) => a.config.email === email);
2485
+ if (!account) return false;
2486
+ account.config = { ...account.config, ...patch };
2487
+ const existing = this.config.accounts.find(
2488
+ (entry) => entry.email === email,
2489
+ );
2490
+ if (existing) Object.assign(existing, patch);
2491
+ await saveAccountsConfig(this.config);
2492
+ await this.saveState();
2493
+ this.log(`${email}: metadata updated by operator`, "warn");
2494
+ return true;
2495
+ }
2496
+
2497
+ async setAllowFreshWindowStarts(enabled: boolean): Promise<boolean> {
2498
+ if (this.allowFreshWindowStarts === enabled) return false;
2499
+ this.allowFreshWindowStarts = enabled;
2500
+ await this.saveState();
2501
+ this.log(
2502
+ enabled
2503
+ ? "Operator enabled fresh window starts; the rotator may seed new timer windows again"
2504
+ : "Operator disabled fresh window starts; the rotator will only use buckets whose timers are already running",
2505
+ "warn",
2506
+ );
2507
+ return true;
2508
+ }
2509
+
2510
+ async setAccountAllowFreshWindowStartsOverride(
2511
+ email: string,
2512
+ enabled: boolean,
2513
+ ): Promise<boolean> {
2514
+ const account = this.accounts.find((a) => a.config.email === email);
2515
+ if (!account) return false;
2516
+ if (account.allowFreshWindowStartsOverride === enabled) return true;
2517
+ account.allowFreshWindowStartsOverride = enabled;
2518
+ await this.saveState();
2519
+ this.log(
2520
+ enabled
2521
+ ? `${email}: operator override enabled fresh window starts for this account`
2522
+ : `${email}: operator override cleared; this account now follows the global fresh-window policy`,
2523
+ "warn",
2524
+ );
2525
+ return true;
2526
+ }
2527
+
2528
+ async setAutoWarmup(enabled: boolean): Promise<boolean> {
2529
+ if (this.autoWarmupEnabled === enabled) return false;
2530
+ this.autoWarmupEnabled = enabled;
2531
+ await this.saveState();
2532
+ this.log(
2533
+ enabled
2534
+ ? "Operator enabled auto-warmup; accounts with fresh-window override will automatically receive minimal kickstart requests on each quota poll"
2535
+ : "Operator disabled auto-warmup; no automatic kickstart requests will be sent",
2536
+ "warn",
2537
+ );
2538
+ return true;
2539
+ }
2540
+
2541
+ async clearModelBreaker(modelKey: string): Promise<boolean> {
2542
+ const now = Date.now();
2543
+ const hasModelBreaker = (this.modelBreakers[modelKey] ?? 0) > now;
2544
+ const hadAny = hasModelBreaker;
2545
+ delete this.modelBreakers[modelKey];
2546
+ // Also clear all project-level breakers for this model
2547
+ for (const key of Object.keys(this.projectModelBreakers)) {
2548
+ if (key.endsWith(`:${modelKey}`)) {
2549
+ delete this.projectModelBreakers[key];
2550
+ }
2551
+ }
2552
+ // Clear the 429 event window so the breaker doesn't immediately re-fire
2553
+ this.provider429Events = this.provider429Events.filter(
2554
+ (e) => e.modelKey !== modelKey,
2555
+ );
2556
+ await this.saveState();
2557
+ this.log(`[${modelKey}] Operator manually cleared circuit breaker`, "warn");
2558
+ return hadAny;
2559
+ }
2560
+
2561
+ async clearAllBreakers(): Promise<number> {
2562
+ const count =
2563
+ Object.keys(this.modelBreakers).length +
2564
+ Object.keys(this.projectModelBreakers).length;
2565
+ this.modelBreakers = {};
2566
+ this.projectModelBreakers = {};
2567
+ this.provider429Events = [];
2568
+ await this.saveState();
2569
+ this.log(
2570
+ `Operator cleared all circuit breakers (${count} entries)`,
2571
+ "warn",
2572
+ );
2573
+ return count;
2574
+ }
2575
+
2576
+ clearInFlightRequests(email: string, modelKey?: string): boolean {
2577
+ const account = this.accounts.find((a) => a.config.email === email);
2578
+ if (!account) return false;
2579
+ if (modelKey) {
2580
+ const previous = account.inFlightByModel[modelKey] ?? 0;
2581
+ account.inFlightByModel[modelKey] = 0;
2582
+ this.recalculateInFlightRequests(account);
2583
+ this.log(
2584
+ `${email}: operator cleared ${previous} in-flight request(s) for ${modelKey}`,
2585
+ "warn",
2586
+ );
2587
+ return true;
2588
+ }
2589
+ const previous = account.inFlightRequests;
2590
+ account.inFlightRequests = 0;
2591
+ account.inFlightByModel = {};
2592
+ this.log(
2593
+ `${email}: operator cleared ${previous} in-flight request(s)`,
2594
+ "warn",
2595
+ );
2596
+ return true;
2597
+ }
2598
+
2599
+ async ensureValidToken(account: AccountRuntime): Promise<void> {
2600
+ const adapter = getProviderForAccount(account.config);
2601
+ try {
2602
+ await adapter.ensureValidToken(account);
2603
+ } catch (err) {
2604
+ const msg = err instanceof Error ? err.message : String(err);
2605
+ if (msg.startsWith("Token refresh failed")) {
2606
+ this.markError(account, msg);
2607
+ throw err;
2608
+ }
2609
+ const wrapped = `Token refresh error: ${msg}`;
2610
+ this.markError(account, wrapped);
2611
+ throw new Error(wrapped, { cause: err });
2612
+ }
2613
+ }
2614
+
2615
+ private isAvailable(account: AccountRuntime, now: number): boolean {
2616
+ if (account.disabled) return false;
2617
+ if (account.flagged) return false;
2618
+ const defaultCooldown = account.cooldownsByModel["__default__"] ?? 0;
2619
+ if (defaultCooldown > now) return false;
2620
+ return true;
2621
+ }
2622
+
2623
+ private isAvailableForModel(
2624
+ account: AccountRuntime,
2625
+ modelKey: string,
2626
+ now: number,
2627
+ ): boolean {
2628
+ if (!this.isAvailable(account, now)) return false;
2629
+ const modelCooldown = account.cooldownsByModel[modelKey] ?? 0;
2630
+ if (modelCooldown > now) return false;
2631
+ // Ollama Cloud (pool key "session") imposes no per-account concurrency
2632
+ // limit. Antigravity keeps it so long streams don't pile up on a
2633
+ // single account while siblings sit idle.
2634
+ if (
2635
+ modelKey !== "session" &&
2636
+ (account.inFlightByModel[modelKey] ?? 0) >=
2637
+ (this.config.maxConcurrentRequestsPerAccount ?? 1)
2638
+ )
2639
+ return false;
2640
+ if (this.getUnavailableReasonForModel(account, modelKey, now)) return false;
2641
+ return true;
2642
+ }
2643
+
2644
+ // Mark an account as flagged for infringement/abuse. Immediately excluded from rotation.
2645
+ markFlagged(
2646
+ account: AccountRuntime,
2647
+ reason: string,
2648
+ options: { triggerProtectivePause?: boolean } = {},
2649
+ ): void {
2650
+ account.flagged = true;
2651
+ account.lastError = reason;
2652
+ account.inFlightRequests = 0;
2653
+ account.inFlightByModel = {};
2654
+ this.log(`${account.config.email}: FLAGGED - ${reason}`, "error");
2655
+ const triggerProtectivePause = options.triggerProtectivePause ?? true;
2656
+ if (triggerProtectivePause && this.shouldTriggerProtectivePause(reason)) {
2657
+ this.protectivePauseUntil =
2658
+ Date.now() + (this.config.protectivePauseMs ?? 6 * 60 * 60 * 1000);
2659
+ this.protectivePauseReason = `${account.config.email}: ${reason}`;
2660
+ this.log(
2661
+ `Protective pause enabled for ${Math.ceil((this.protectivePauseUntil - Date.now()) / 1000)}s after serious provider flag`,
2662
+ "warn",
2663
+ );
2664
+ }
2665
+ this.scheduleStateSave();
2666
+ }
2667
+
2668
+ startRequest(account: AccountRuntime, modelKey?: string): void {
2669
+ const key = modelKey ?? "__default__";
2670
+ // Ollama Cloud imposes no per-account concurrency limit, so its
2671
+ // requests must not activate in-flight tracking at all (pool key
2672
+ // "session" and raw ollama model names from benchmark probes).
2673
+ if (key === "session" || this.ollamaModels.has(key)) {
2674
+ this.consumeTokenBucket(account, Date.now());
2675
+ return;
2676
+ }
2677
+ account.inFlightByModel[key] = (account.inFlightByModel[key] ?? 0) + 1;
2678
+ this.recalculateInFlightRequests(account);
2679
+ this.consumeTokenBucket(account, Date.now());
2680
+ }
2681
+
2682
+ finishRequest(account: AccountRuntime, modelKey?: string): void {
2683
+ const key = modelKey ?? "__default__";
2684
+ if (key === "session" || this.ollamaModels.has(key)) return;
2685
+ account.inFlightByModel[key] = Math.max(
2686
+ 0,
2687
+ (account.inFlightByModel[key] ?? 0) - 1,
2688
+ );
2689
+ if (account.inFlightByModel[key] === 0) delete account.inFlightByModel[key];
2690
+ this.recalculateInFlightRequests(account);
2691
+ }
2692
+
2693
+ private recalculateInFlightRequests(account: AccountRuntime): void {
2694
+ account.inFlightRequests = Object.values(account.inFlightByModel).reduce(
2695
+ (sum, count) => sum + count,
2696
+ 0,
2697
+ );
2698
+ }
2699
+
2700
+ private isProviderEligibleForKey(
2701
+ account: AccountRuntime,
2702
+ modelKey: string,
2703
+ ): boolean {
2704
+ if (modelKey === "session") {
2705
+ return hasCredential(account.config, "ollama");
2706
+ }
2707
+ // Google pools (claude/gemini) require a google credential. A dual
2708
+ // account (google + ollama) must stay eligible here — it can serve both.
2709
+ return hasCredential(account.config, DEFAULT_PROVIDER);
2710
+ }
2711
+
2712
+ /** Public pool-key resolution for quota routing display/logging. */
2713
+ resolveQuotaModelKeyForDisplay(model: string): string | null {
2714
+ return this.resolvePoolKeyForModel(model);
2715
+ }
2716
+
2717
+ private resolvePoolKeyForModel(model: string): string | null {
2718
+ if (this.ollamaModels.has(model)) return "session";
2719
+ return resolveQuotaModelKey(model) ?? null;
2720
+ }
2721
+
2722
+ /** Map a candidate key (model name or pool key) to the account's pool key. */
2723
+ private resolvePoolKey(account: AccountRuntime, key: string): string {
2724
+ if (
2725
+ hasCredential(account.config, "ollama") &&
2726
+ key !== "session" &&
2727
+ this.ollamaModels.has(key)
2728
+ ) {
2729
+ return "session";
2730
+ }
2731
+ return key;
2732
+ }
2733
+
2734
+ private isRoutableForModel(
2735
+ account: AccountRuntime,
2736
+ modelKey: string,
2737
+ now: number,
2738
+ ): boolean {
2739
+ modelKey = this.resolvePoolKey(account, modelKey);
2740
+ if (!this.isProviderEligibleForKey(account, modelKey)) return false;
2741
+ if (!this.isAvailableForModel(account, modelKey, now)) return false;
2742
+ if (this.getModelQuota(account, modelKey) === 0) return false;
2743
+ if (!this.isFreshWindowAllowed(account, modelKey)) return false;
2744
+ if ((this.config.routingPolicy || "timer-first") === "hybrid") {
2745
+ const tokenSnapshot = this.getTokenBucketSnapshot(account, now);
2746
+ if (tokenSnapshot.enabled && tokenSnapshot.tokens < 1) return false;
2747
+ }
2748
+ return true;
2749
+ }
2750
+
2751
+ getRetryAfterMs(model?: string): number {
2752
+ const now = Date.now();
2753
+ const retryTimes: number[] = [];
2754
+ if (this.protectivePauseUntil > now)
2755
+ retryTimes.push(this.protectivePauseUntil);
2756
+ const modelKey = model
2757
+ ? (resolveQuotaModelKey(model) ?? "__default__")
2758
+ : "__default__";
2759
+ const dailyResetAt = nextUtcDayStartMs(now);
2760
+ const modelBreaker = this.modelBreakers[modelKey] ?? 0;
2761
+ if (modelBreaker > now) retryTimes.push(modelBreaker);
2762
+ for (const account of this.accounts) {
2763
+ if (account.disabled || account.flagged) continue;
2764
+ if (this.isDailySafetyStopped(account, now))
2765
+ retryTimes.push(dailyResetAt);
2766
+ const cooldown = Math.max(
2767
+ account.cooldownsByModel[modelKey] ?? 0,
2768
+ account.cooldownsByModel.__default__ ?? 0,
2769
+ );
2770
+ if (cooldown > now) retryTimes.push(cooldown);
2771
+ const projectBreaker =
2772
+ this.projectModelBreakers[
2773
+ projectModelKey(account.config.projectId ?? "", modelKey)
2774
+ ] ?? 0;
2775
+ if (projectBreaker > now) retryTimes.push(projectBreaker);
2776
+ if ((this.config.routingPolicy || "timer-first") === "hybrid") {
2777
+ const tokenSnapshot = this.getTokenBucketSnapshot(account, now);
2778
+ if (
2779
+ tokenSnapshot.enabled &&
2780
+ tokenSnapshot.tokens < 1 &&
2781
+ tokenSnapshot.nextRefillInMs > 0
2782
+ ) {
2783
+ retryTimes.push(now + tokenSnapshot.nextRefillInMs);
2784
+ }
2785
+ }
2786
+ }
2787
+ if (retryTimes.length === 0) return 0;
2788
+ return Math.max(1000, Math.min(...retryTimes) - now);
2789
+ }
2790
+
2791
+ getStatus(): StatusResponse {
2792
+ const now = Date.now();
2793
+ this.refreshHealthScores();
2794
+
2795
+ // Build per-model active account map from accounts that can actually serve now.
2796
+ const activeAccounts: Record<string, string> = {};
2797
+ for (const [model, mState] of this.modelState.entries()) {
2798
+ const account = this.accounts[mState.activeAccountIndex];
2799
+ if (account && this.isRoutableForModel(account, model, now)) {
2800
+ activeAccounts[model] = account.config.email;
2801
+ }
2802
+ }
2803
+
2804
+ const accounts: AccountStatus[] = this.accounts.map((a) => {
2805
+ // Determine which models this account is active for
2806
+ const activeForModels: string[] = [];
2807
+ for (const [model, mState] of this.modelState.entries()) {
2808
+ if (
2809
+ this.accounts[mState.activeAccountIndex] === a &&
2810
+ this.isRoutableForModel(a, model, now)
2811
+ ) {
2812
+ activeForModels.push(model);
2813
+ }
2814
+ }
2815
+ const status = this.getAccountStatusForUi(a, now, activeForModels);
2816
+ const tokenBucket = this.getTokenBucketSnapshot(a, now);
2817
+
2818
+ return {
2819
+ email: a.config.email,
2820
+ provider:
2821
+ (a.config.credentials ?? []).map((c) => c.provider).join("+") ||
2822
+ a.config.provider ||
2823
+ "google-antigravity",
2824
+ label: a.config.label || a.config.email,
2825
+ status,
2826
+ activeForModels,
2827
+ requestsSinceRotation: a.requestsSinceRotation,
2828
+ totalRequests: a.totalRequests,
2829
+ dailyRequestCount: this.getAccountDailyCount(a, now),
2830
+ dailyAccountStopRequests: this.config.dailyAccountStopRequests ?? 350,
2831
+ dailyProjectRequestCount: this.getProjectDailyCount(a.config.projectId ?? "",
2832
+ now,
2833
+ ),
2834
+ dailyProjectStopRequests: this.config.dailyProjectStopRequests ?? 1200,
2835
+ cooldownsByModel: a.cooldownsByModel,
2836
+ lastUsed: a.lastUsed,
2837
+ lastError: a.lastError,
2838
+ consecutiveErrors: a.consecutiveErrors,
2839
+ hasValidToken: !!(a.accessToken && a.tokenExpires > now),
2840
+ quota: a.quota,
2841
+ inFlightRequests: a.inFlightRequests,
2842
+ inFlightByModel: a.inFlightByModel,
2843
+ proDetected: a.config.type === "pro",
2844
+ tier: a.config.tier || "unknown",
2845
+ healthScore: a.healthScore,
2846
+ tokenBucket,
2847
+ allowFreshWindowStartsOverride: a.allowFreshWindowStartsOverride,
2848
+ effectiveFreshWindowStartsAllowed:
2849
+ this.isEffectiveFreshWindowAllowed(a),
2850
+ };
2851
+ });
2852
+
2853
+ const routingHealth = this.getRoutingHealth(now, accounts);
2854
+ const knownModels = new Set<string>();
2855
+ for (const model of this.modelState.keys()) knownModels.add(model);
2856
+ for (const model of Object.keys(this.modelBreakers)) knownModels.add(model);
2857
+ for (const key of Object.keys(this.projectModelBreakers)) {
2858
+ const model = key.split("::")[1];
2859
+ if (model) knownModels.add(model);
2860
+ }
2861
+ for (const account of this.accounts) {
2862
+ for (const quota of account.quota) knownModels.add(quota.modelKey);
2863
+ for (const cooldownModel of Object.keys(account.cooldownsByModel)) {
2864
+ if (cooldownModel !== "__default__") knownModels.add(cooldownModel);
2865
+ }
2866
+ }
2867
+ const routingDiagnostics: Record<string, RoutingModelDiagnostics> = {};
2868
+ for (const modelKey of knownModels) {
2869
+ routingDiagnostics[modelKey] = this.buildRoutingDiagnostics(
2870
+ modelKey,
2871
+ now,
2872
+ );
2873
+ }
2874
+ this.routingDiagnostics = routingDiagnostics;
2875
+
2876
+ const updateInfo = getUpdateInfo();
2877
+
2878
+ // Build circuit breaker summary for the dashboard
2879
+ const modelBreakersSummary: Record<
2880
+ string,
2881
+ { until: number; remainingMs: number }
2882
+ > = {};
2883
+ for (const [key, until] of Object.entries(this.modelBreakers)) {
2884
+ if (until > now) {
2885
+ modelBreakersSummary[key] = { until, remainingMs: until - now };
2886
+ }
2887
+ }
2888
+ const projectBreakersSummary: Record<
2889
+ string,
2890
+ { until: number; remainingMs: number }
2891
+ > = {};
2892
+ for (const [key, until] of Object.entries(this.projectModelBreakers)) {
2893
+ if (until > now) {
2894
+ projectBreakersSummary[key] = { until, remainingMs: until - now };
2895
+ }
2896
+ }
2897
+
2898
+ const adminWarning = getConfiguredAdminToken()
2899
+ ? null
2900
+ : `Admin routes are exposed on ${this.config.bindHost}:${this.config.proxyPort} because TUXEVIL_ROTATOR_ADMIN_TOKEN is not configured.`;
2901
+ const proxyWarning = getProxyExposureWarning(this.config);
2902
+
2903
+ return {
2904
+ version: updateInfo.currentVersion,
2905
+ proxyPort: this.config.proxyPort,
2906
+ requestsPerRotation: this.config.requestsPerRotation,
2907
+ activeAccounts,
2908
+ totalRequestsAllAccounts: this.accounts.reduce(
2909
+ (sum, a) => sum + a.totalRequests,
2910
+ 0,
2911
+ ),
2912
+ uptime: now - this.startTime,
2913
+ protectivePauseUntil: this.protectivePauseUntil,
2914
+ protectivePauseRemaining: Math.max(0, this.protectivePauseUntil - now),
2915
+ protectivePauseReason: this.isProtectivePauseActive(now)
2916
+ ? this.protectivePauseReason
2917
+ : null,
2918
+ operatorControls: {
2919
+ allowFreshWindowStarts: this.allowFreshWindowStarts,
2920
+ autoWarmupEnabled: this.autoWarmupEnabled,
2921
+ },
2922
+ security: {
2923
+ adminTokenConfigured: !!getConfiguredAdminToken(),
2924
+ warning: [adminWarning, proxyWarning].filter(Boolean).join(" ") || null,
2925
+ bindHost: this.config.bindHost || "0.0.0.0",
2926
+ },
2927
+ routingDiagnostics,
2928
+ circuitBreakers: {
2929
+ model: modelBreakersSummary,
2930
+ project: projectBreakersSummary,
2931
+ },
2932
+ routingHealth,
2933
+ accounts,
2934
+ recentEvents: [...this.recentEvents],
2935
+ requestLog: this.requestLog.slice(0, 100),
2936
+ tokenUsage: this.getTokenUsage(),
2937
+ latencyStats: this.getLatencyStats(),
2938
+ updateInfo,
2939
+ notifications: getNotifications(),
2940
+ hostedOAuthConfigured: isHostedOAuthConfigured(),
2941
+ ollamaModels: this.getOllamaModels(),
2942
+ modelTierAccess: this.accounts.some((a) =>
2943
+ hasCredential(a.config, "ollama"),
2944
+ )
2945
+ ? MODEL_TIER_ACCESS
2946
+ : undefined,
2947
+ predictions: this.getPredictionSummary(),
2948
+ };
2949
+ }
2950
+
2951
+ getConfig(): Config {
2952
+ return applyConfigDefaults(structuredClone(this.config));
2953
+ }
2954
+
2955
+ async replaceConfig(nextConfig: Config): Promise<void> {
2956
+ const normalized = applyConfigDefaults(nextConfig);
2957
+ const previous = new Map(
2958
+ this.accounts.map((account) => [account.config.email, account]),
2959
+ );
2960
+ this.config = normalized;
2961
+ this.accounts = normalized.accounts.map((config) => {
2962
+ const existing = previous.get(config.email);
2963
+ if (existing) {
2964
+ return {
2965
+ ...existing,
2966
+ config: { ...existing.config, ...config },
2967
+ };
2968
+ }
2969
+ return {
2970
+ config,
2971
+ accessToken: null,
2972
+ tokenExpires: 0,
2973
+ requestsSinceRotation: 0,
2974
+ totalRequests: 0,
2975
+ cooldownsByModel: {},
2976
+ quotaExhaustedAt: 0,
2977
+ quota: [],
2978
+ lastQuotaPoll: 0,
2979
+ lastUsed: 0,
2980
+ lastError: null,
2981
+ consecutiveErrors: 0,
2982
+ disabled: false,
2983
+ flagged: false,
2984
+ inFlightRequests: 0,
2985
+ inFlightByModel: {},
2986
+ allowFreshWindowStartsOverride: false,
2987
+ dailyRequestCount: 0,
2988
+ dailyRequestDay: currentUtcDay(),
2989
+ healthScore: 1,
2990
+ tokenBucket: {
2991
+ tokens: Math.max(
2992
+ 0,
2993
+ Math.min(
2994
+ this.config.tokenBucketInitialTokens ?? 50,
2995
+ this.config.tokenBucketMaxTokens ?? 50,
2996
+ ),
2997
+ ),
2998
+ lastRefillAt: Date.now(),
2999
+ },
3000
+ };
3001
+ });
3002
+ await saveAccountsConfig(this.config);
3003
+ await this.saveState();
3004
+ this.refreshHealthScores();
3005
+ }
3006
+
3007
+ getAccountCount(): number {
3008
+ return this.accounts.length;
3009
+ }
3010
+
3011
+ /**
3012
+ * Get contextual data for telemetry flag reporting.
3013
+ * Returns anonymous pool state — no emails or PII.
3014
+ */
3015
+ getFlagContext(
3016
+ account: AccountRuntime,
3017
+ modelKey: string,
3018
+ ): {
3019
+ wasProAccount: boolean;
3020
+ accountQuotaPercent: number;
3021
+ timerType: string;
3022
+ poolSize: number;
3023
+ poolHealthyCount: number;
3024
+ protectivePauseTriggered: boolean;
3025
+ accountRequestsLastHour: number;
3026
+ uptimeSeconds: number;
3027
+ } {
3028
+ const now = Date.now();
3029
+ const quota = this.getModelQuota(account, modelKey);
3030
+ const timerType = this.getModelTimerType(account, modelKey);
3031
+ const healthyCount = this.accounts.filter(
3032
+ (a) => !a.disabled && !a.flagged && this.isAvailable(a, now),
3033
+ ).length;
3034
+
3035
+ // Count requests in the last hour from request log
3036
+ const oneHourAgo = now - 3600_000;
3037
+ const label = account.config.label || account.config.email;
3038
+ const requestsLastHour = this.requestLog.filter(
3039
+ (e) => e.timestamp >= oneHourAgo && e.account === label,
3040
+ ).length;
3041
+
3042
+ return {
3043
+ wasProAccount: account.config.type === "pro",
3044
+ accountQuotaPercent: quota,
3045
+ timerType,
3046
+ poolSize: this.accounts.length,
3047
+ poolHealthyCount: healthyCount,
3048
+ protectivePauseTriggered: this.protectivePauseUntil > now,
3049
+ accountRequestsLastHour: requestsLastHour,
3050
+ uptimeSeconds: Math.round((now - this.startTime) / 1000),
3051
+ };
3052
+ }
3053
+
3054
+ async addOrUpdateAccount(accountConfig: AccountConfig): Promise<void> {
3055
+ const existingIndex = this.accounts.findIndex(
3056
+ (account) => account.config.email === accountConfig.email,
3057
+ );
3058
+ if (existingIndex >= 0) {
3059
+ const existing = this.accounts[existingIndex];
3060
+ existing.config = {
3061
+ ...existing.config,
3062
+ ...accountConfig,
3063
+ tier: accountConfig.tier || existing.config.tier || "unknown",
3064
+ };
3065
+ existing.disabled = false;
3066
+ existing.flagged = false;
3067
+ existing.lastError = null;
3068
+ existing.consecutiveErrors = 0;
3069
+ existing.accessToken = null;
3070
+ existing.tokenExpires = 0;
3071
+ this.config.accounts[existingIndex] = existing.config;
3072
+ this.log(`${accountConfig.email}: account updated via hosted login`);
3073
+ } else {
3074
+ const runtime: AccountRuntime = {
3075
+ config: { ...accountConfig, tier: accountConfig.tier || "unknown" },
3076
+ accessToken: null,
3077
+ tokenExpires: 0,
3078
+ requestsSinceRotation: 0,
3079
+ totalRequests: 0,
3080
+ cooldownsByModel: {},
3081
+ quotaExhaustedAt: 0,
3082
+ quota: [],
3083
+ lastQuotaPoll: 0,
3084
+ lastUsed: 0,
3085
+ lastError: null,
3086
+ consecutiveErrors: 0,
3087
+ disabled: false,
3088
+ flagged: false,
3089
+ inFlightRequests: 0,
3090
+ inFlightByModel: {},
3091
+ allowFreshWindowStartsOverride: false,
3092
+ dailyRequestCount: 0,
3093
+ dailyRequestDay: currentUtcDay(),
3094
+ healthScore: 1,
3095
+ tokenBucket: {
3096
+ tokens: Math.max(
3097
+ 0,
3098
+ Math.min(
3099
+ this.config.tokenBucketInitialTokens ?? 50,
3100
+ this.config.tokenBucketMaxTokens ?? 50,
3101
+ ),
3102
+ ),
3103
+ lastRefillAt: Date.now(),
3104
+ },
3105
+ };
3106
+ this.accounts.push(runtime);
3107
+ this.config.accounts.push(runtime.config);
3108
+ this.log(`${accountConfig.email}: account added via hosted login`);
3109
+ }
3110
+
3111
+ await saveAccountsConfig(this.config);
3112
+ await this.saveState();
3113
+ void this.pollAllQuotas();
3114
+ }
3115
+
3116
+ async removeAccount(email: string): Promise<boolean> {
3117
+ const idx = this.accounts.findIndex((a) => a.config.email === email);
3118
+ if (idx < 0) return false;
3119
+ const account = this.accounts[idx];
3120
+ if (account.inFlightRequests > 0) {
3121
+ this.log(
3122
+ `${email}: refusing to remove - ${account.inFlightRequests} in-flight requests`,
3123
+ "warn",
3124
+ );
3125
+ return false;
3126
+ }
3127
+ this.accounts.splice(idx, 1);
3128
+ const configIdx = this.config.accounts.findIndex((a) => a.email === email);
3129
+ if (configIdx >= 0) this.config.accounts.splice(configIdx, 1);
3130
+
3131
+ // Fix up modelState indices that may now be stale after the splice
3132
+ for (const [, mState] of this.modelState.entries()) {
3133
+ if (mState.activeAccountIndex > idx) {
3134
+ mState.activeAccountIndex--;
3135
+ } else if (mState.activeAccountIndex === idx) {
3136
+ mState.activeAccountIndex =
3137
+ this.accounts.length > 0
3138
+ ? Math.min(mState.activeAccountIndex, this.accounts.length - 1)
3139
+ : 0;
3140
+ }
3141
+ }
3142
+ if (this.defaultIndex > idx) {
3143
+ this.defaultIndex--;
3144
+ } else if (
3145
+ this.defaultIndex >= this.accounts.length &&
3146
+ this.accounts.length > 0
3147
+ ) {
3148
+ this.defaultIndex = this.accounts.length - 1;
3149
+ }
3150
+
3151
+ await removeAccountFromConfig(email);
3152
+ await this.saveState();
3153
+ this.log(`${email}: account removed`);
3154
+ return true;
3155
+ }
3156
+
3157
+ async setAccountTier(email: string, tier: string): Promise<boolean> {
3158
+ const validTiers = ["unknown", "free", "plus", "pro", "ultra"];
3159
+ if (!validTiers.includes(tier)) return false;
3160
+ const account = this.accounts.find((a) => a.config.email === email);
3161
+ if (!account) return false;
3162
+ account.config.tier = tier as AccountTier;
3163
+ const configAccount = this.config.accounts.find((a) => a.email === email);
3164
+ if (configAccount) configAccount.tier = tier as AccountTier;
3165
+ await saveAccountsConfig(this.config);
3166
+ await this.saveState();
3167
+ this.log(`${email}: tier changed to ${tier}`);
3168
+ return true;
3169
+ }
3170
+
3171
+ recordProxyEvent(
3172
+ msg: string,
3173
+ level: "info" | "warn" | "error" = "info",
3174
+ ): void {
3175
+ this.pushRecentEvent("proxy", msg, level);
3176
+ }
3177
+
3178
+ private log(msg: string, level: "info" | "warn" | "error" = "info"): void {
3179
+ rotatorLogger.log(level, msg);
3180
+ this.pushRecentEvent("rotator", msg, level);
3181
+ }
3182
+
3183
+ private pushRecentEvent(
3184
+ source: "rotator" | "proxy",
3185
+ message: string,
3186
+ level: "info" | "warn" | "error",
3187
+ ): void {
3188
+ this.recentEvents.unshift({
3189
+ timestamp: Date.now(),
3190
+ source,
3191
+ level,
3192
+ message,
3193
+ });
3194
+ if (this.recentEvents.length > AccountRotator.RECENT_EVENT_LIMIT) {
3195
+ this.recentEvents.length = AccountRotator.RECENT_EVENT_LIMIT;
3196
+ }
3197
+ }
3198
+
3199
+ public getAccountByEmail(email: string): AccountRuntime | undefined {
3200
+ return this.accounts.find((a) => a.config.email === email);
3201
+ }
3202
+
3203
+ public getBenchmarkAccounts(): AccountRuntime[] {
3204
+ return this.accounts.filter((account) => !account.disabled && !account.flagged);
3205
+ }
3206
+
3207
+ private shouldUseRequestCountRotation(
3208
+ account: AccountRuntime,
3209
+ model?: string,
3210
+ ): boolean {
3211
+ if (this.isQuotaAwarePolicy()) return false;
3212
+ if (!this.config.useRequestCountRotationWhenQuotaUnknownOnly) return true;
3213
+ const modelKey = model ? this.resolvePoolKeyForModel(model) : null;
3214
+ if (!modelKey) return true;
3215
+ return this.getModelQuota(account, modelKey) < 0;
3216
+ }
3217
+
3218
+ private shouldTriggerProtectivePause(reason: string): boolean {
3219
+ const lower = reason.toLowerCase();
3220
+ const severePatterns = [
3221
+ "terms of service",
3222
+ "violat",
3223
+ "suspend",
3224
+ "banned",
3225
+ "abus",
3226
+ "infring",
3227
+ ];
3228
+ return severePatterns.some((pattern) => lower.includes(pattern));
3229
+ }
3230
+
3231
+ private isProtectivePauseActive(now: number): boolean {
3232
+ return this.protectivePauseUntil > now;
3233
+ }
3234
+
3235
+ private getRoutingHealth(
3236
+ now: number,
3237
+ accounts: AccountStatus[],
3238
+ ): StatusResponse["routingHealth"] {
3239
+ const activeCount = accounts.filter((a) => a.status === "active").length;
3240
+ const readyCount = accounts.filter((a) => a.status === "ready").length;
3241
+ const exhaustedCount = accounts.filter(
3242
+ (a) => a.status === "exhausted",
3243
+ ).length;
3244
+ const cooldownCount = accounts.filter(
3245
+ (a) => a.status === "cooldown",
3246
+ ).length;
3247
+ const flaggedCount = accounts.filter((a) => a.status === "flagged").length;
3248
+ const disabledCount = accounts.filter(
3249
+ (a) => a.status === "disabled",
3250
+ ).length;
3251
+ const errorCount = accounts.filter((a) => a.status === "error").length;
3252
+ const busyCount = accounts.filter(
3253
+ (a) =>
3254
+ a.status !== "disabled" &&
3255
+ a.status !== "flagged" &&
3256
+ a.inFlightRequests > 0,
3257
+ ).length;
3258
+ const rawAvailableCount = this.accounts.filter(
3259
+ (a) => this.isAvailable(a, now) && !this.isDailySafetyStopped(a, now),
3260
+ ).length;
3261
+ const timedAvailableCount = this.accounts.filter((account) => {
3262
+ if (!this.isAvailable(account, now)) return false;
3263
+ if (this.isDailySafetyStopped(account, now)) return false;
3264
+ const hasTimedQuota = account.quota.some(
3265
+ (q) => q.percentRemaining !== 0 && q.timerType !== "fresh",
3266
+ );
3267
+ return hasTimedQuota || account.allowFreshWindowStartsOverride;
3268
+ }).length;
3269
+ const availableCount = this.allowFreshWindowStarts
3270
+ ? rawAvailableCount
3271
+ : timedAvailableCount;
3272
+ const shortestCooldown = accounts
3273
+ .flatMap((a) =>
3274
+ Object.values(a.cooldownsByModel).map((ts) => Math.max(0, ts - now)),
3275
+ )
3276
+ .filter((rem) => rem > 0)
3277
+ .reduce((best, rem) => (best === 0 || rem < best ? rem : best), 0);
3278
+ const pauseRemaining = Math.max(0, this.protectivePauseUntil - now);
3279
+ const freshOnlyBlocked =
3280
+ !this.allowFreshWindowStarts &&
3281
+ rawAvailableCount > 0 &&
3282
+ timedAvailableCount === 0;
3283
+
3284
+ if (pauseRemaining > 0) {
3285
+ return {
3286
+ state: "paused",
3287
+ reason:
3288
+ this.protectivePauseReason ||
3289
+ "Protective pause active after provider flag",
3290
+ nextRetryIn: pauseRemaining,
3291
+ availableCount,
3292
+ readyCount,
3293
+ activeCount,
3294
+ cooldownCount,
3295
+ busyCount,
3296
+ flaggedCount,
3297
+ disabledCount,
3298
+ errorCount,
3299
+ };
3300
+ }
3301
+
3302
+ if (availableCount > 0) {
3303
+ const freshPolicyNote = !this.allowFreshWindowStarts
3304
+ ? " Fresh window starts are currently disabled by the operator."
3305
+ : "";
3306
+ return {
3307
+ state: "healthy",
3308
+ reason: `Routing can serve requests.${freshPolicyNote}`,
3309
+ nextRetryIn: 0,
3310
+ availableCount,
3311
+ readyCount,
3312
+ activeCount,
3313
+ cooldownCount,
3314
+ busyCount,
3315
+ flaggedCount,
3316
+ disabledCount,
3317
+ errorCount,
3318
+ };
3319
+ }
3320
+
3321
+ if (freshOnlyBlocked) {
3322
+ return {
3323
+ state: "stopped",
3324
+ reason:
3325
+ "Only fresh windows remain, and the operator toggle is preventing the rotator from opening them right now.",
3326
+ nextRetryIn: 0,
3327
+ availableCount,
3328
+ readyCount,
3329
+ activeCount,
3330
+ cooldownCount,
3331
+ busyCount,
3332
+ flaggedCount,
3333
+ disabledCount,
3334
+ errorCount,
3335
+ };
3336
+ }
3337
+
3338
+ if (cooldownCount > 0) {
3339
+ return {
3340
+ state: "cooldown_wait",
3341
+ reason: "All non-quarantined accounts are cooling down",
3342
+ nextRetryIn: shortestCooldown,
3343
+ availableCount,
3344
+ readyCount,
3345
+ activeCount,
3346
+ cooldownCount,
3347
+ busyCount,
3348
+ flaggedCount,
3349
+ disabledCount,
3350
+ errorCount,
3351
+ };
3352
+ }
3353
+
3354
+ if (busyCount > 0) {
3355
+ return {
3356
+ state: "busy",
3357
+ reason:
3358
+ "All available accounts are currently busy with in-flight requests",
3359
+ nextRetryIn: 0,
3360
+ availableCount,
3361
+ readyCount,
3362
+ activeCount,
3363
+ cooldownCount,
3364
+ busyCount,
3365
+ flaggedCount,
3366
+ disabledCount,
3367
+ errorCount,
3368
+ };
3369
+ }
3370
+
3371
+ if (exhaustedCount > 0) {
3372
+ return {
3373
+ state: "stopped",
3374
+ reason:
3375
+ "All otherwise available accounts are stopped by local daily safety budgets until the next UTC day.",
3376
+ nextRetryIn: Math.max(0, nextUtcDayStartMs(now) - now),
3377
+ availableCount,
3378
+ readyCount,
3379
+ activeCount,
3380
+ cooldownCount,
3381
+ busyCount,
3382
+ flaggedCount,
3383
+ disabledCount,
3384
+ errorCount,
3385
+ };
3386
+ }
3387
+
3388
+ return {
3389
+ state: "stopped",
3390
+ reason: !this.allowFreshWindowStarts
3391
+ ? "No timed bucket is currently routable. Fresh window starts are disabled, so the rotator is waiting for an already-running timer, cooldown recovery, or operator action."
3392
+ : "No account is currently routable. All accounts are flagged, disabled, or unavailable.",
3393
+ nextRetryIn: 0,
3394
+ availableCount,
3395
+ readyCount,
3396
+ activeCount,
3397
+ cooldownCount,
3398
+ busyCount,
3399
+ flaggedCount,
3400
+ disabledCount,
3401
+ errorCount,
3402
+ };
3403
+ }
3404
+
3405
+ /**
3406
+ * Send a minimal single-token request to the upstream Antigravity endpoint for a specific
3407
+ * quota pool key on a given account. Uses the cheapest model in that pool to minimise cost.
3408
+ * Applies normal error handling (markExhausted, markFlagged, markError) so the account state
3409
+ * stays consistent with regular traffic.
3410
+ */
3411
+ async kickstartTimerForAccount(
3412
+ email: string,
3413
+ quotaModelKey: string,
3414
+ ): Promise<{ ok: boolean; status: number; upstreamModel: string; error?: string }> {
3415
+ const account = this.accounts.find((a) => a.config.email === email);
3416
+ if (!account) {
3417
+ return { ok: false, status: 404, upstreamModel: "", error: "account not found" };
3418
+ }
3419
+ if (account.disabled || account.flagged) {
3420
+ return {
3421
+ ok: false,
3422
+ status: 409,
3423
+ upstreamModel: "",
3424
+ error: account.disabled ? "account disabled" : "account flagged",
3425
+ };
3426
+ }
3427
+
3428
+ try {
3429
+ await this.ensureValidToken(account);
3430
+ } catch (err) {
3431
+ return {
3432
+ ok: false,
3433
+ status: 401,
3434
+ upstreamModel: "",
3435
+ error: `token refresh failed: ${err instanceof Error ? err.message : String(err)}`,
3436
+ };
3437
+ }
3438
+
3439
+ const kickstartAdapter =
3440
+ quotaModelKey === "session"
3441
+ ? getProviderAdapter("ollama")
3442
+ : getProviderForAccount(account.config);
3443
+ const isOllamaAccount = kickstartAdapter.id === "ollama";
3444
+ if (!account.accessToken && !isOllamaAccount) {
3445
+ return { ok: false, status: 401, upstreamModel: "", error: "no access token" };
3446
+ }
3447
+
3448
+ const upstreamModel =
3449
+ kickstartAdapter.getKickstartModelForPool(quotaModelKey) ??
3450
+ quotaModelKey;
3451
+
3452
+ const controller = new AbortController();
3453
+ const timeout = setTimeout(() => controller.abort(), 15_000);
3454
+
3455
+ let response: Response;
3456
+ if (isOllamaAccount) {
3457
+ const ollamaBody: RequestBody = {
3458
+ project: "",
3459
+ model: upstreamModel,
3460
+ request: {
3461
+ messages: [{ role: "user", content: "." }],
3462
+ options: { num_predict: 1 },
3463
+ stream: false,
3464
+ },
3465
+ };
3466
+ try {
3467
+ const forwarded = await kickstartAdapter.forwardRequest(
3468
+ account,
3469
+ ollamaBody,
3470
+ {},
3471
+ controller.signal,
3472
+ );
3473
+ response = forwarded.response;
3474
+ } catch (err) {
3475
+ clearTimeout(timeout);
3476
+ const msg = `kickstart network error: ${err instanceof Error ? err.message : String(err)}`;
3477
+ this.markError(account, msg);
3478
+ return { ok: false, status: 0, upstreamModel, error: msg };
3479
+ }
3480
+ clearTimeout(timeout);
3481
+ } else {
3482
+ const body = JSON.stringify({
3483
+ project: account.config.projectId,
3484
+ model: upstreamModel,
3485
+ request: {
3486
+ contents: [{ role: "user", parts: [{ text: "." }] }],
3487
+ generationConfig: { maxOutputTokens: 1 },
3488
+ },
3489
+ });
3490
+
3491
+ const endpoint = ANTIGRAVITY_ENDPOINTS[ANTIGRAVITY_ENDPOINTS.length - 1];
3492
+ const url = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;
3493
+
3494
+ try {
3495
+ response = await fetch(url, {
3496
+ method: "POST",
3497
+ headers: {
3498
+ "Content-Type": "application/json",
3499
+ Authorization: `Bearer ${account.accessToken}`,
3500
+ "User-Agent": QUOTA_USER_AGENT,
3501
+ "X-Goog-Api-Client": REQUEST_GOOG_API_CLIENT,
3502
+ "Client-Metadata": REQUEST_CLIENT_METADATA,
3503
+ },
3504
+ body,
3505
+ signal: controller.signal,
3506
+ dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
3507
+ } as RequestInitWithDispatcher);
3508
+ } catch (err) {
3509
+ clearTimeout(timeout);
3510
+ const msg = `kickstart network error: ${err instanceof Error ? err.message : String(err)}`;
3511
+ this.markError(account, msg);
3512
+ return { ok: false, status: 0, upstreamModel, error: msg };
3513
+ }
3514
+ clearTimeout(timeout);
3515
+ }
3516
+
3517
+ // Consume and discard the response body to free the connection
3518
+ try {
3519
+ await response.body?.cancel();
3520
+ } catch {
3521
+ // ignore
3522
+ }
3523
+
3524
+ const label = account.config.label || account.config.email;
3525
+
3526
+ if (response.status === 429) {
3527
+ const cooldownMs = 60_000;
3528
+ this.markExhausted(account, quotaModelKey, cooldownMs, "kickstart 429");
3529
+ this.recordProvider429(account, quotaModelKey, cooldownMs);
3530
+ this.log(
3531
+ `${label} [${quotaModelKey}]: kickstart 429 — cooldown ${cooldownMs / 1000}s`,
3532
+ "warn",
3533
+ );
3534
+ return { ok: false, status: 429, upstreamModel };
3535
+ }
3536
+
3537
+ if (response.status === 401 || response.status === 403) {
3538
+ this.markFlagged(
3539
+ account,
3540
+ `kickstart ${response.status} on ${upstreamModel}`,
3541
+ { triggerProtectivePause: false },
3542
+ );
3543
+ return { ok: false, status: response.status, upstreamModel };
3544
+ }
3545
+
3546
+ if (response.status >= 500) {
3547
+ this.markError(account, `kickstart ${response.status} on ${upstreamModel}`);
3548
+ return { ok: false, status: response.status, upstreamModel };
3549
+ }
3550
+
3551
+ if (response.ok) {
3552
+ this.recordRequest(account, quotaModelKey);
3553
+ this.log(
3554
+ `${label} [${quotaModelKey}]: kickstart sent via ${upstreamModel} — timer should start within the next quota poll`,
3555
+ );
3556
+ }
3557
+
3558
+ return { ok: response.ok, status: response.status, upstreamModel };
3559
+ }
3560
+
3561
+ /**
3562
+ * Kickstart all quota pools that are currently idle (no active timer, or rolling
3563
+ * idle with 100% quota and a fresh resetTime) for a given account. Deduplicates by
3564
+ * upstream model so that pools sharing the same upstream (e.g. gemini-3.5-flash and
3565
+ * gemini-3.1-pro → gemini-3-flash) only receive one request.
3566
+ */
3567
+ async kickstartAllFreshTimers(email: string): Promise<{
3568
+ ok: boolean;
3569
+ error?: string;
3570
+ results: Array<{
3571
+ quotaPools: string[];
3572
+ upstreamModel: string;
3573
+ ok: boolean;
3574
+ status: number;
3575
+ }>;
3576
+ }> {
3577
+ const account = this.accounts.find((a) => a.config.email === email);
3578
+ if (!account) {
3579
+ return { ok: false, error: "account not found", results: [] };
3580
+ }
3581
+
3582
+ const idlePools = account.quota.filter((q) => this.isQuotaIdleForKickstart(q));
3583
+ if (idlePools.length === 0) {
3584
+ return { ok: true, results: [] };
3585
+ }
3586
+
3587
+ // Deduplicate: group quota pool keys by their upstream model
3588
+ const upstreamToQuotaPools = new Map<string, string[]>();
3589
+ for (const q of idlePools) {
3590
+ const upstream = KICKSTART_MODEL_FOR_QUOTA_POOL[q.modelKey] ?? q.modelKey;
3591
+ const list = upstreamToQuotaPools.get(upstream) ?? [];
3592
+ list.push(q.modelKey);
3593
+ upstreamToQuotaPools.set(upstream, list);
3594
+ }
3595
+
3596
+ const results: Array<{
3597
+ quotaPools: string[];
3598
+ upstreamModel: string;
3599
+ ok: boolean;
3600
+ status: number;
3601
+ }> = [];
3602
+
3603
+ for (const [upstreamModel, quotaPools] of upstreamToQuotaPools) {
3604
+ // Use the primary quota pool key for this upstream (for recordRequest/markExhausted)
3605
+ const primaryQuotaKey =
3606
+ QUOTA_POOL_FOR_KICKSTART_MODEL[upstreamModel] ?? quotaPools[0];
3607
+ const result = await this.kickstartTimerForAccount(email, primaryQuotaKey);
3608
+ results.push({ quotaPools, upstreamModel, ok: result.ok, status: result.status });
3609
+ }
3610
+
3611
+ const allOk = results.every((r) => r.ok);
3612
+ return { ok: allOk, results };
3613
+ }
3614
+ }