tuxevil-rotator 4.4.8 → 4.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## [4.4.9] - 2026-11-24
6
+
7
+ ### Fixed
8
+
9
+ - **Paid Claude kickstart fallback**: Select account-aware Claude kickstart models for paid Pro, Ultra, Plus, Max, and Team tiers, preferring advertised Sonnet 5.5 candidates while retaining the historical primary as a compatibility fallback. Retry model-specific 400/404/403 and 5xx failures with per-model backoff without counting them as consecutive account errors; quota-exhaustion 429s do not switch models, and an explicit Free tier takes precedence over legacy Pro metadata. Gemini keeps its existing primary model.
10
+ - **Telemetry receiver account and install aggregation**: Detect paid tiers in `proDetected`/`wasProAccount`, accept larger model catalogs and heartbeat payloads, preserve install state when processing flag events, and aggregate per-model token maxima consistently.
11
+ - **OpenCode discovery recovery**: Keep `ctx.provider.transform` registered and retry automatically (`retryMs`, default 5s) when the rotator is temporarily unreachable at startup; preserve the last known-good model catalog when refreshes return an empty list or transient error.
12
+
5
13
  ## [4.4.8] - 2026-11-23
6
14
 
7
15
  ### Fixed
package/README.md CHANGED
@@ -55,6 +55,7 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
55
55
 
56
56
  ## Current Model Update
57
57
 
58
+ - **v4.4.9: Claude paid-tier kickstart fallback, telemetry accuracy, and OpenCode recovery**: Use account-aware Claude Sonnet 5.5 kickstart candidates for paid tiers with safe model-specific fallbacks and backoff, without changing Gemini's primary or switching models on quota-exhaustion 429s. Correct paid-tier and install telemetry aggregation, and retry OpenCode model discovery after transient startup failures while retaining the last good catalog. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.4.9))
58
59
  - **v4.4.8: Invalid-provider flag loop fix & telemetry receiver overhaul**: Stop quota polling and auto-warmup kickstarts from looping every 5 minutes on already-invalidated or disabled providers (emitting flag telemetry only on transitions and clearing invalidation across all providers on re-auth). Overhaul the standalone telemetry receiver with a cyberpunk/retro-console UX across `/dashboard`, `/notifications`, and `/stats`, fix flag double-counting and request inflation, add 24h sliding-window flag-loop deduplication, and harden security (Stored XSS fix, prototype-safe pricing, constant-time auth + brute-force lockout, trusted-proxy rate limiting, CSP/SRI, scoped CORS, and HTTP timeouts). ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.4.8))
59
60
  - **v4.4.7: Artificial Analysis scores, static specs, and dashboard colors**: Refresh the Artificial Analysis Intelligence Index routing-quality snapshot (`2026-11-23`) with exact per-effort scores for Gemini 4 (`neon`, `hydrogen`, `carbon`, `argon`), Gemini 3.8 Flash, Claude 5.5, and OpenAI `gpt-6.1`/`gpt-6.2`, and add static model specs, context windows, and distinct dashboard chart colors for Gemini 4, Claude 5.5, GPT-6.1/6.2, and newer Ollama Cloud models. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.4.7))
60
61
  - **v4.4.6: Model pricing refresh**: Add official November 2026 pricing and family fallbacks for Gemini 4 (`neon`, `hydrogen`, `carbon`, `argon`), Claude 5.5 (`opus`, `sonnet`), OpenAI `gpt-6.1`/`gpt-6.2`, and newly published Ollama Cloud models in both the rotator and standalone telemetry receiver. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.4.6))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "4.4.8",
3
+ "version": "4.4.9",
4
4
  "description": "Multi-provider, multi-account AI proxy rotator with per-model routing, real-time quota tracking, and infringement detection (Google Antigravity, Ollama Cloud)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -15,6 +15,7 @@
15
15
  * - providerName display name (default "Antigravity (rotator)")
16
16
  * - timeoutMs fetch timeout (default 3500)
17
17
  * - refreshMs background re-discovery interval (default 600000; 0 disables)
18
+ * - retryMs retry interval while initial discovery has not succeeded yet (default 5000)
18
19
  */
19
20
 
20
21
  import { openCodeReasoning, openCodeVariants } from "./capabilities.mjs"
@@ -138,12 +139,19 @@ export function resolvePluginOptions(options = {}, providerEntries = []) {
138
139
  let end = baseURLText.length
139
140
  while (end > 0 && baseURLText.charCodeAt(end - 1) === 47) end--
140
141
 
142
+ const refreshMs = options.refreshMs === 0 ? 0 : Number(options.refreshMs) || 600_000
143
+ const retryMs =
144
+ refreshMs <= 0
145
+ ? 0
146
+ : Math.min(refreshMs, Math.max(1, Number(options.retryMs) || 5_000))
147
+
141
148
  return {
142
149
  baseURL: baseURLText.slice(0, end),
143
150
  providerID: providerID || "antigravity",
144
151
  providerName: providerName || "Antigravity (rotator)",
145
152
  timeoutMs: Number(options.timeoutMs) || 3500,
146
- refreshMs: options.refreshMs === 0 ? 0 : Number(options.refreshMs) || 600_000,
153
+ refreshMs,
154
+ retryMs,
147
155
  }
148
156
  }
149
157
 
@@ -274,20 +282,29 @@ export default {
274
282
  async function load() {
275
283
  try {
276
284
  const models = await fetchRotatorModels(resolved.baseURL, resolved.timeoutMs)
277
- const list = Array.isArray(models) ? models : []
278
- const changed = lastSignature !== null && modelSignature(list) !== lastSignature
285
+ const list = Array.isArray(models) ? models.filter((m) => typeof m?.id === "string" && m.id.length > 0) : []
286
+ if (list.length === 0) {
287
+ // Never wipe the last known good catalog on a transient empty response
288
+ console.warn("[opencode-discovery] model discovery returned an empty catalog; keeping previous inventory")
289
+ return { ok: false, changed: false, invalidUrl: false }
290
+ }
291
+ const sig = modelSignature(list)
292
+ const changed = lastSignature !== sig
279
293
  source.models = list
280
- lastSignature = modelSignature(list)
281
- return { ok: true, changed }
294
+ lastSignature = sig
295
+ return { ok: true, changed, invalidUrl: false }
282
296
  } catch (err) {
297
+ const msg = err?.message ?? String(err)
298
+ const invalidUrl = msg.includes("fetch() URL is invalid") || msg.includes("Unsupported URL protocol")
283
299
  // Safe degrade: never fail OpenCode startup when the rotator is unreachable
284
- console.warn(`[opencode-discovery] model discovery skipped: ${err?.message ?? err}`)
285
- return { ok: false, changed: false }
300
+ console.warn(`[opencode-discovery] model discovery skipped: ${msg}`)
301
+ return { ok: false, changed: false, invalidUrl }
286
302
  }
287
303
  }
288
304
 
289
305
  const first = await load()
290
- if (!first.ok || !source.models?.length) return undefined
306
+ if (first.invalidUrl) return undefined
307
+ if (!first.ok && resolved.refreshMs <= 0) return undefined
291
308
 
292
309
  const toModelInfo = (raw, existingModel) => {
293
310
  const { id, modelDef } = mapModelToOpenCode(raw)
@@ -324,20 +341,32 @@ export default {
324
341
 
325
342
  if (resolved.refreshMs <= 0) return undefined
326
343
 
327
- const timer = setInterval(() => {
328
- void (async () => {
329
- const result = await load()
330
- if (!result.changed) return
331
- try {
332
- await ctx.provider.reload()
333
- } catch {
334
- // Registry reload unavailable; keep the last known inventory
335
- }
336
- })()
337
- }, resolved.refreshMs)
338
- if (typeof timer.unref === "function") timer.unref()
344
+ let stopped = false
345
+ let timer = null
346
+ const scheduleNext = () => {
347
+ if (stopped) return
348
+ const delayMs = source.models?.length ? resolved.refreshMs : resolved.retryMs
349
+ timer = setTimeout(() => {
350
+ void (async () => {
351
+ const result = await load()
352
+ if (!stopped && result.ok && result.changed) {
353
+ try {
354
+ await ctx.provider.reload()
355
+ } catch {
356
+ // Registry reload unavailable; keep the last known inventory
357
+ }
358
+ }
359
+ scheduleNext()
360
+ })()
361
+ }, delayMs)
362
+ if (typeof timer.unref === "function") timer.unref()
363
+ }
364
+ scheduleNext()
339
365
 
340
- return () => clearInterval(timer)
366
+ return () => {
367
+ stopped = true
368
+ if (timer) clearTimeout(timer)
369
+ }
341
370
  },
342
371
  }
343
372
 
@@ -168,6 +168,11 @@ export interface ProviderAdapter {
168
168
  getPoolKey?(model: string): string;
169
169
  /** Cheap upstream model that warms a quota pool during kickstart. */
170
170
  getKickstartModelForPool(quotaModelKey: string): string | undefined;
171
+ /** Ordered kickstart candidate models for a quota pool (primary + fallbacks), optionally tailored to an account. */
172
+ getKickstartModelsForPool?(
173
+ quotaModelKey: string,
174
+ account?: AccountRuntime,
175
+ ): string[];
171
176
  /** Benchmark request used to measure account latency/health. */
172
177
  getBenchmark(account: AccountRuntime): {
173
178
  body: RequestBody;
@@ -34,10 +34,16 @@ import {
34
34
  import {
35
35
  TOKEN_URL,
36
36
  KICKSTART_MODEL_FOR_QUOTA_POOL,
37
+ KICKSTART_FALLBACK_MODELS_FOR_QUOTA_POOL,
38
+ KICKSTART_PRO_MODELS_FOR_QUOTA_POOL,
37
39
  applyModelAlias,
38
40
  resolveQuotaModelKey,
39
41
  } from "../../types.js";
40
42
  import type { AccountRuntime } from "../../types.js";
43
+ import {
44
+ getAccountIdentity,
45
+ getCredentialGeneration,
46
+ } from "../../account-identity.js";
41
47
  import { fetchWithRetry } from "../../fetch-with-retry.js";
42
48
  import { logger } from "../../logger.js";
43
49
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
@@ -175,6 +181,57 @@ export const googleAntigravityAdapter: ProviderAdapter = {
175
181
  );
176
182
  },
177
183
 
184
+ getKickstartModelsForPool(
185
+ quotaModelKey: string,
186
+ account?: AccountRuntime,
187
+ ): string[] {
188
+ const pool = KICKSTART_MODEL_FOR_QUOTA_POOL[quotaModelKey]
189
+ ? quotaModelKey
190
+ : resolveQuotaModelKey(quotaModelKey) ?? "";
191
+ const primary = KICKSTART_MODEL_FOR_QUOTA_POOL[pool];
192
+ if (!pool || !primary) return [];
193
+
194
+ const snapshot = account
195
+ ? dynamicCatalog.getAccountSnapshot(
196
+ getAccountIdentity(account),
197
+ getCredentialGeneration(account.config, "google-antigravity"),
198
+ )
199
+ : undefined;
200
+ const snapshotSet = snapshot
201
+ ? new Set(snapshot.models.map((model) => model.toLowerCase()))
202
+ : null;
203
+
204
+ const tier = account?.config.tier;
205
+ const isExplicitlyFree = tier === "free";
206
+ const isProOrHigher = isExplicitlyFree
207
+ ? false
208
+ : tier === "pro" || tier === "ultra" || tier === "plus" ||
209
+ tier === "max" || tier === "team" || account?.config.type === "pro";
210
+ const snapshotHasSonnet55 = Boolean(
211
+ snapshotSet &&
212
+ (snapshotSet.has("claude-sonnet-5-5-low") ||
213
+ snapshotSet.has("claude-sonnet-5-5-medium")),
214
+ );
215
+ const useProOrder = pool === "claude" && !isExplicitlyFree &&
216
+ (isProOrHigher || snapshotHasSonnet55);
217
+ const preferred =
218
+ (useProOrder
219
+ ? KICKSTART_PRO_MODELS_FOR_QUOTA_POOL[pool]
220
+ : KICKSTART_FALLBACK_MODELS_FOR_QUOTA_POOL[pool]) ?? [primary];
221
+
222
+ if (snapshotSet) {
223
+ const inSnapshot = preferred.filter((model) =>
224
+ snapshotSet.has(model.toLowerCase()),
225
+ );
226
+ if (inSnapshot.length > 0) return inSnapshot;
227
+ return [primary];
228
+ }
229
+
230
+ // Without a per-account catalog, preserve only the existing primary.
231
+ if (pool === "gemini") return [primary];
232
+ return [...preferred];
233
+ },
234
+
178
235
  listModels(): ProviderModel[] {
179
236
  return getEffectiveAntigravityModels().map((model) => ({
180
237
  id: model.id,
package/src/rotator.ts CHANGED
@@ -183,6 +183,21 @@ export function areAccountIdentitiesCompatible(
183
183
  const rotatorLogger = logger.child("rotator");
184
184
  const IN_CONTAINER = isRunningInContainer();
185
185
 
186
+ const PAID_ACCOUNT_TIERS: ReadonlySet<AccountTier> = new Set([
187
+ "ultra",
188
+ "pro",
189
+ "plus",
190
+ "max",
191
+ "team",
192
+ ]);
193
+
194
+ function isPaidAccountConfig(config: AccountConfig): boolean {
195
+ if (config.tier && config.tier !== "unknown") {
196
+ return PAID_ACCOUNT_TIERS.has(config.tier);
197
+ }
198
+ return config.type === "pro";
199
+ }
200
+
186
201
  function currentUtcDay(now = Date.now()): string {
187
202
  return new Date(now).toISOString().slice(0, 10);
188
203
  }
@@ -221,6 +236,9 @@ interface AccountRequestWaiter {
221
236
  // Reverse map: upstream model → the quota pool key it primarily represents (for deduplication).
222
237
  const QUOTA_POOL_FOR_KICKSTART_MODEL: Record<string, string> = {
223
238
  "gpt-oss-120b-medium": "claude",
239
+ "claude-sonnet-5-5-low": "claude",
240
+ "claude-sonnet-5-5-medium": "claude",
241
+ "claude-sonnet-4-6": "claude",
224
242
  "gemini-3-flash": "gemini",
225
243
  "gpt-5.6-luna": CODEX_QUOTA_MODEL_KEY,
226
244
  // Legacy manual kickstart compatibility. New Ollama quota polling/routes
@@ -521,7 +539,10 @@ export class AccountRotator {
521
539
  private routingWarningLastLoggedAt = new Map<string, number>();
522
540
  private static readonly ROUTING_WARNING_DEDUP_MS = 60_000;
523
541
  private autoWarmupEnabled = false;
524
- private readonly kickstartDeniedUntil = new Map<string, number>();
542
+ private readonly kickstartDeniedUntil = new Map<
543
+ string,
544
+ { until: number; status: number; reason: string }
545
+ >();
525
546
  // Debounced state writer: batches multiple saveState() calls within a 1s window
526
547
  // to a single disk write. Hot paths (markError, recordRequest, etc.) call
527
548
  // scheduleStateSave() instead of saveState() to avoid blocking the event loop.
@@ -1336,6 +1357,7 @@ export class AccountRotator {
1336
1357
  providerId: string;
1337
1358
  adapter: ReturnType<typeof getProviderAdapter>;
1338
1359
  upstreamModel: string;
1360
+ upstreamModels: string[];
1339
1361
  } | null {
1340
1362
  const poolKey = this.resolveAccountPoolKey(account, quotaModelKey);
1341
1363
  const quota = account.quota.find((candidate) => candidate.modelKey === poolKey);
@@ -1345,9 +1367,20 @@ export class AccountRotator {
1345
1367
  if (!hasCredential(account.config, providerId)) return null;
1346
1368
 
1347
1369
  const adapter = getProviderAdapter(providerId);
1348
- const upstreamModel = adapter.getKickstartModelForPool(poolKey);
1349
- if (!upstreamModel) return null;
1350
- return { poolKey, providerId, adapter, upstreamModel };
1370
+ const candidates = adapter.getKickstartModelsForPool
1371
+ ? adapter.getKickstartModelsForPool(poolKey, account)
1372
+ : (() => {
1373
+ const single = adapter.getKickstartModelForPool(poolKey);
1374
+ return single ? [single] : [];
1375
+ })();
1376
+ if (candidates.length === 0) return null;
1377
+ return {
1378
+ poolKey,
1379
+ providerId,
1380
+ adapter,
1381
+ upstreamModel: candidates[0],
1382
+ upstreamModels: candidates,
1383
+ };
1351
1384
  }
1352
1385
 
1353
1386
  // Timer priority for a specific model:
@@ -4419,7 +4452,7 @@ export class AccountRotator {
4419
4452
  quota: a.quota,
4420
4453
  inFlightRequests: a.inFlightRequests,
4421
4454
  inFlightByModel: a.inFlightByModel,
4422
- proDetected: a.config.type === "pro",
4455
+ proDetected: isPaidAccountConfig(a.config),
4423
4456
  tier: a.config.tier || "unknown",
4424
4457
  healthScore: a.healthScore,
4425
4458
  tokenBucket,
@@ -4675,7 +4708,7 @@ export class AccountRotator {
4675
4708
  ).length;
4676
4709
 
4677
4710
  return {
4678
- wasProAccount: account.config.type === "pro",
4711
+ wasProAccount: isPaidAccountConfig(account.config),
4679
4712
  accountQuotaPercent: quota,
4680
4713
  timerType,
4681
4714
  poolSize: this.accounts.length,
@@ -5113,7 +5146,10 @@ export class AccountRotator {
5113
5146
  error: `${target.providerId} credential requires re-authentication`,
5114
5147
  };
5115
5148
  }
5116
- if (isProviderModelOff(this, target.providerId, target.upstreamModel)) {
5149
+ const enabledCandidates = target.upstreamModels.filter(
5150
+ (model) => !isProviderModelOff(this, target.providerId, model),
5151
+ );
5152
+ if (enabledCandidates.length === 0) {
5117
5153
  return {
5118
5154
  ok: false,
5119
5155
  status: 409,
@@ -5122,13 +5158,23 @@ export class AccountRotator {
5122
5158
  };
5123
5159
  }
5124
5160
 
5125
- const denialKey = `${email}\0${target.upstreamModel}`;
5126
- if ((this.kickstartDeniedUntil.get(denialKey) ?? 0) > Date.now()) {
5161
+ const now = Date.now();
5162
+ const runnableCandidates: string[] = [];
5163
+ let activeDenial: { until: number; status: number; reason: string } | undefined;
5164
+ for (const model of enabledCandidates) {
5165
+ const denial = this.kickstartDeniedUntil.get(`${email}\0${model}`);
5166
+ if (!denial || denial.until <= now) {
5167
+ runnableCandidates.push(model);
5168
+ } else {
5169
+ activeDenial ??= denial;
5170
+ }
5171
+ }
5172
+ if (runnableCandidates.length === 0) {
5127
5173
  return {
5128
5174
  ok: false,
5129
- status: 403,
5130
- upstreamModel: target.upstreamModel,
5131
- error: "kickstart temporarily skipped after model-specific 403",
5175
+ status: activeDenial?.status ?? 403,
5176
+ upstreamModel: enabledCandidates[0],
5177
+ error: activeDenial?.reason ?? "kickstart temporarily skipped after model-specific failure",
5132
5178
  };
5133
5179
  }
5134
5180
 
@@ -5150,7 +5196,6 @@ export class AccountRotator {
5150
5196
  return { ok: false, status: 401, upstreamModel: "", error: "no access token" };
5151
5197
  }
5152
5198
 
5153
- const upstreamModel = target.upstreamModel;
5154
5199
  const poolKey = target.poolKey;
5155
5200
 
5156
5201
  const activeCooldown = Math.max(
@@ -5161,180 +5206,217 @@ export class AccountRotator {
5161
5206
  return {
5162
5207
  ok: false,
5163
5208
  status: 429,
5164
- upstreamModel,
5209
+ upstreamModel: runnableCandidates[0],
5165
5210
  error: `quota cooldown active for ${Math.ceil((activeCooldown - Date.now()) / 1000)}s`,
5166
5211
  };
5167
5212
  }
5168
5213
 
5169
- const controller = new AbortController();
5170
- const timeout = setTimeout(() => controller.abort(), 15_000);
5171
-
5172
- let response: Response;
5173
- if (kickstartAdapter.forwardKickstartRequest) {
5174
- try {
5175
- const forwarded = await kickstartAdapter.forwardKickstartRequest(
5176
- account,
5177
- upstreamModel,
5178
- controller.signal,
5179
- );
5180
- response = forwarded.response;
5181
- } catch (err) {
5214
+ const label = account.config.label || account.config.email;
5215
+ let failedFrom: string | null = null;
5216
+ for (let index = 0; index < runnableCandidates.length; index++) {
5217
+ const upstreamModel = runnableCandidates[index];
5218
+ const denialKey = `${email}\0${upstreamModel}`;
5219
+ const nextCandidate = runnableCandidates[index + 1];
5220
+ const controller = new AbortController();
5221
+ const timeout = setTimeout(() => controller.abort(), 15_000);
5222
+
5223
+ let response: Response;
5224
+ if (kickstartAdapter.forwardKickstartRequest) {
5225
+ try {
5226
+ const forwarded = await kickstartAdapter.forwardKickstartRequest(
5227
+ account,
5228
+ upstreamModel,
5229
+ controller.signal,
5230
+ );
5231
+ response = forwarded.response;
5232
+ } catch (err) {
5233
+ clearTimeout(timeout);
5234
+ const msg = `kickstart network error: ${err instanceof Error ? err.message : String(err)}`;
5235
+ this.markError(account, msg);
5236
+ return { ok: false, status: 0, upstreamModel, error: msg };
5237
+ }
5182
5238
  clearTimeout(timeout);
5183
- const msg = `kickstart network error: ${err instanceof Error ? err.message : String(err)}`;
5184
- this.markError(account, msg);
5185
- return { ok: false, status: 0, upstreamModel, error: msg };
5186
- }
5187
- clearTimeout(timeout);
5188
- } else if (isOllamaAccount) {
5189
- const ollamaBody: RequestBody = {
5190
- project: "",
5191
- model: upstreamModel,
5192
- request: {
5193
- messages: [{ role: "user", content: "." }],
5194
- options: { num_predict: 1 },
5195
- stream: false,
5196
- },
5197
- };
5198
- try {
5199
- const forwarded = await kickstartAdapter.forwardRequest(
5200
- account,
5201
- ollamaBody,
5202
- {},
5203
- controller.signal,
5204
- );
5205
- response = forwarded.response;
5206
- } catch (err) {
5239
+ } else if (isOllamaAccount) {
5240
+ const ollamaBody: RequestBody = {
5241
+ project: "",
5242
+ model: upstreamModel,
5243
+ request: {
5244
+ messages: [{ role: "user", content: "." }],
5245
+ options: { num_predict: 1 },
5246
+ stream: false,
5247
+ },
5248
+ };
5249
+ try {
5250
+ const forwarded = await kickstartAdapter.forwardRequest(
5251
+ account,
5252
+ ollamaBody,
5253
+ {},
5254
+ controller.signal,
5255
+ );
5256
+ response = forwarded.response;
5257
+ } catch (err) {
5258
+ clearTimeout(timeout);
5259
+ const msg = `kickstart network error: ${err instanceof Error ? err.message : String(err)}`;
5260
+ this.markError(account, msg);
5261
+ return { ok: false, status: 0, upstreamModel, error: msg };
5262
+ }
5207
5263
  clearTimeout(timeout);
5208
- const msg = `kickstart network error: ${err instanceof Error ? err.message : String(err)}`;
5209
- this.markError(account, msg);
5210
- return { ok: false, status: 0, upstreamModel, error: msg };
5211
- }
5212
- clearTimeout(timeout);
5213
- } else {
5214
- const body = JSON.stringify({
5215
- project: this.getProjectIdForModel(account, poolKey),
5216
- model: upstreamModel,
5217
- request: {
5218
- contents: [{ role: "user", parts: [{ text: "." }] }],
5219
- generationConfig: { maxOutputTokens: 1 },
5220
- },
5221
- });
5222
-
5223
- const endpoint = ANTIGRAVITY_ENDPOINTS[ANTIGRAVITY_ENDPOINTS.length - 1];
5224
- const url = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;
5225
-
5226
- try {
5227
- response = await fetch(url, {
5228
- method: "POST",
5229
- headers: {
5230
- "Content-Type": "application/json",
5231
- Authorization: `Bearer ${account.accessToken}`,
5232
- "User-Agent": QUOTA_USER_AGENT,
5233
- "X-Goog-Api-Client": REQUEST_GOOG_API_CLIENT,
5234
- "Client-Metadata": REQUEST_CLIENT_METADATA,
5264
+ } else {
5265
+ const body = JSON.stringify({
5266
+ project: this.getProjectIdForModel(account, poolKey),
5267
+ model: upstreamModel,
5268
+ request: {
5269
+ contents: [{ role: "user", parts: [{ text: "." }] }],
5270
+ generationConfig: { maxOutputTokens: 1 },
5235
5271
  },
5236
- body,
5237
- signal: controller.signal,
5238
- dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
5239
- } as RequestInitWithDispatcher);
5240
- } catch (err) {
5272
+ });
5273
+
5274
+ const endpoint = ANTIGRAVITY_ENDPOINTS[ANTIGRAVITY_ENDPOINTS.length - 1];
5275
+ const url = `${endpoint}/v1internal:streamGenerateContent?alt=sse`;
5276
+ try {
5277
+ response = await fetch(url, {
5278
+ method: "POST",
5279
+ headers: {
5280
+ "Content-Type": "application/json",
5281
+ Authorization: `Bearer ${account.accessToken}`,
5282
+ "User-Agent": QUOTA_USER_AGENT,
5283
+ "X-Goog-Api-Client": REQUEST_GOOG_API_CLIENT,
5284
+ "Client-Metadata": REQUEST_CLIENT_METADATA,
5285
+ },
5286
+ body,
5287
+ signal: controller.signal,
5288
+ dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
5289
+ } as RequestInitWithDispatcher);
5290
+ } catch (err) {
5291
+ clearTimeout(timeout);
5292
+ const msg = `kickstart network error: ${err instanceof Error ? err.message : String(err)}`;
5293
+ this.markError(account, msg);
5294
+ return { ok: false, status: 0, upstreamModel, error: msg };
5295
+ }
5241
5296
  clearTimeout(timeout);
5242
- const msg = `kickstart network error: ${err instanceof Error ? err.message : String(err)}`;
5243
- this.markError(account, msg);
5244
- return { ok: false, status: 0, upstreamModel, error: msg };
5245
5297
  }
5246
- clearTimeout(timeout);
5247
- }
5248
5298
 
5249
- let errorText = "";
5250
- if (response.status === 429 || response.status === 401 || response.status === 403) {
5251
- errorText = await response.text().catch(() => "");
5252
- } else {
5253
- // Consume and discard the response body to free the connection.
5254
- try {
5255
- await response.body?.cancel();
5256
- } catch {
5257
- // ignore
5299
+ let errorText = "";
5300
+ if (response.status === 429 || response.status === 401 || response.status === 403) {
5301
+ errorText = await response.text().catch(() => "");
5302
+ } else {
5303
+ try {
5304
+ await response.body?.cancel();
5305
+ } catch {
5306
+ // ignore
5307
+ }
5258
5308
  }
5259
- }
5260
5309
 
5261
- const label = account.config.label || account.config.email;
5262
-
5263
- if (response.status === 429) {
5264
- const providerResourceExhausted =
5265
- classifyRateLimitReason(errorText, response.status) === "quota-exhausted";
5266
- const cooldownMs = providerResourceExhausted
5267
- ? target.providerId === DEFAULT_PROVIDER || target.providerId === "openai-codex"
5268
- ? parseRetryAfterMs(
5269
- errorText,
5270
- response.headers,
5310
+ if (response.status === 429) {
5311
+ this.kickstartDeniedUntil.delete(denialKey);
5312
+ const providerResourceExhausted =
5313
+ classifyRateLimitReason(errorText, response.status) === "quota-exhausted";
5314
+ const cooldownMs = providerResourceExhausted
5315
+ ? target.providerId === DEFAULT_PROVIDER || target.providerId === "openai-codex"
5316
+ ? parseRetryAfterMs(
5317
+ errorText,
5318
+ response.headers,
5319
+ RESOURCE_EXHAUSTED_FALLBACK_MS,
5320
+ )
5321
+ : RESOURCE_EXHAUSTED_FALLBACK_MS
5322
+ : Math.min(
5323
+ parseRetryAfterMs(errorText, response.headers),
5271
5324
  RESOURCE_EXHAUSTED_FALLBACK_MS,
5272
- )
5273
- : RESOURCE_EXHAUSTED_FALLBACK_MS
5274
- : Math.min(
5275
- parseRetryAfterMs(errorText, response.headers),
5276
- RESOURCE_EXHAUSTED_FALLBACK_MS,
5325
+ );
5326
+ this.markExhausted(account, poolKey, cooldownMs, errorText || "kickstart 429");
5327
+ this.recordProvider429(account, poolKey, cooldownMs, providerResourceExhausted);
5328
+ this.log(
5329
+ `${label} [${poolKey}]: kickstart 429 — cooldown ${cooldownMs / 1000}s`,
5330
+ "warn",
5331
+ );
5332
+ return { ok: false, status: 429, upstreamModel };
5333
+ }
5334
+
5335
+ if (response.status === 401 || response.status === 403) {
5336
+ const failure = describeKickstartAuthFailure(response.status, upstreamModel, errorText);
5337
+ if (target.providerId === "openai-codex") {
5338
+ this.markProviderInvalid(account, target.providerId, failure.description);
5339
+ return { ok: false, status: response.status, upstreamModel, error: failure.description };
5340
+ }
5341
+ if (failure.accountEnforcement) {
5342
+ this.kickstartDeniedUntil.delete(denialKey);
5343
+ // Enforcement errors invalidate the provider credential, not sibling providers.
5344
+ this.reportQuotaPollFlag(account, response.status, errorText, upstreamModel, target.providerId);
5345
+ this.markProviderInvalid(account, target.providerId, failure.description);
5346
+ return { ok: false, status: response.status, upstreamModel, error: failure.description };
5347
+ }
5348
+ const reason = `kickstart temporarily skipped after model-specific ${response.status}`;
5349
+ this.kickstartDeniedUntil.set(denialKey, {
5350
+ until: Date.now() + 30 * 60 * 1000,
5351
+ status: response.status,
5352
+ reason,
5353
+ });
5354
+ if (nextCandidate) {
5355
+ failedFrom ??= `${response.status} on ${upstreamModel}`;
5356
+ this.log(
5357
+ `${label} [${poolKey}]: ${failure.description}; trying fallback ${nextCandidate}`,
5358
+ "warn",
5277
5359
  );
5278
- this.markExhausted(
5279
- account,
5280
- poolKey,
5281
- cooldownMs,
5282
- errorText || "kickstart 429",
5283
- );
5284
- this.recordProvider429(
5285
- account,
5286
- poolKey,
5287
- cooldownMs,
5288
- providerResourceExhausted,
5289
- );
5290
- this.log(
5291
- `${label} [${poolKey}]: kickstart 429 — cooldown ${cooldownMs / 1000}s`,
5292
- "warn",
5293
- );
5294
- return { ok: false, status: 429, upstreamModel };
5295
- }
5296
-
5297
- if (response.status === 401 || response.status === 403) {
5298
- const failure = describeKickstartAuthFailure(response.status, upstreamModel, errorText);
5299
- if (target.providerId === "openai-codex") {
5300
- this.markProviderInvalid(account, target.providerId, failure.description);
5301
- } else if (failure.accountEnforcement) {
5302
- // Provider-scoped invalidation: even with account-enforcement language
5303
- // in the response, only the specific provider credential is invalidated.
5304
- // Sibling providers on the same account remain routable.
5305
- this.reportQuotaPollFlag(account, response.status, errorText, upstreamModel, target.providerId);
5306
- this.markProviderInvalid(account, target.providerId, failure.description);
5307
- } else {
5360
+ continue;
5361
+ }
5308
5362
  account.lastError = failure.description;
5309
- this.kickstartDeniedUntil.set(denialKey, Date.now() + 30 * 60 * 1000);
5363
+ this.scheduleStateSave();
5310
5364
  this.log(`${label}: ${failure.description}; retrying kickstart after 30 minutes`, "warn");
5365
+ return { ok: false, status: response.status, upstreamModel, error: failure.description };
5311
5366
  }
5312
- return { ok: false, status: response.status, upstreamModel, error: failure.description };
5313
- }
5314
5367
 
5315
- if (response.status >= 500) {
5316
- this.markError(account, `kickstart ${response.status} on ${upstreamModel}`);
5317
- return { ok: false, status: response.status, upstreamModel };
5318
- }
5368
+ this.kickstartDeniedUntil.delete(denialKey);
5369
+
5370
+ if (response.status === 400 || response.status === 404 || response.status >= 500) {
5371
+ const backoffMs = response.status >= 500 ? 15 * 60 * 1000 : 30 * 60 * 1000;
5372
+ const message = `kickstart ${response.status} on ${upstreamModel}`;
5373
+ this.kickstartDeniedUntil.set(denialKey, {
5374
+ until: Date.now() + backoffMs,
5375
+ status: response.status,
5376
+ reason: `kickstart temporarily skipped after ${response.status} on ${upstreamModel}`,
5377
+ });
5378
+ if (nextCandidate) {
5379
+ failedFrom ??= `${response.status} on ${upstreamModel}`;
5380
+ this.log(
5381
+ `${label} [${poolKey}]: ${message}; trying fallback ${nextCandidate}`,
5382
+ "warn",
5383
+ );
5384
+ continue;
5385
+ }
5386
+ // Model-specific upstream failures must not count toward disabling a healthy account.
5387
+ account.lastError = message;
5388
+ this.scheduleStateSave();
5389
+ this.log(
5390
+ `${label} [${poolKey}]: ${message}; retrying kickstart after ${backoffMs / 60_000} minutes`,
5391
+ "warn",
5392
+ );
5393
+ return { ok: false, status: response.status, upstreamModel, error: message };
5394
+ }
5319
5395
 
5320
- if (response.ok) {
5321
- this.recordRequest(account, poolKey);
5322
- target.adapter.clearQuotaCache?.(account);
5323
- this.log(
5324
- `${label} [${poolKey}]: kickstart sent via ${upstreamModel} — ${refreshQuota ? "refreshing quota" : "bulk quota refresh pending"}`,
5325
- );
5326
- // Immediately re-poll the account quota so newly started resetTime and timerType
5327
- // are captured and exposed without waiting for the background polling cycle.
5328
- if (refreshQuota) {
5329
- try {
5330
- await this.pollAccountQuota(account);
5331
- } catch {
5332
- // non-fatal
5396
+ if (response.ok) {
5397
+ this.recordRequest(account, poolKey);
5398
+ target.adapter.clearQuotaCache?.(account);
5399
+ const fallbackNote = failedFrom ? ` (fallback after ${failedFrom})` : "";
5400
+ this.log(
5401
+ `${label} [${poolKey}]: kickstart sent via ${upstreamModel}${fallbackNote} — ${refreshQuota ? "refreshing quota" : "bulk quota refresh pending"}`,
5402
+ );
5403
+ if (refreshQuota) {
5404
+ try {
5405
+ await this.pollAccountQuota(account);
5406
+ } catch {
5407
+ // non-fatal
5408
+ }
5333
5409
  }
5334
5410
  }
5411
+ return { ok: response.ok, status: response.status, upstreamModel };
5335
5412
  }
5336
5413
 
5337
- return { ok: response.ok, status: response.status, upstreamModel };
5414
+ return {
5415
+ ok: false,
5416
+ status: 503,
5417
+ upstreamModel: target.upstreamModel,
5418
+ error: `kickstart failed on all candidates for ${poolKey}`,
5419
+ };
5338
5420
  }
5339
5421
 
5340
5422
  /**
@@ -5396,7 +5478,12 @@ export class AccountRotator {
5396
5478
  primaryQuotaKey,
5397
5479
  false,
5398
5480
  );
5399
- results.push({ quotaPools, upstreamModel, ok: result.ok, status: result.status });
5481
+ results.push({
5482
+ quotaPools,
5483
+ upstreamModel: result.upstreamModel || upstreamModel,
5484
+ ok: result.ok,
5485
+ status: result.status,
5486
+ });
5400
5487
  }
5401
5488
 
5402
5489
  if (results.some((result) => result.ok)) {
package/src/types.ts CHANGED
@@ -1306,6 +1306,22 @@ export const KICKSTART_MODEL_FOR_QUOTA_POOL: Record<string, string> = {
1306
1306
  "gemini": "gemini-3-flash",
1307
1307
  };
1308
1308
 
1309
+ // Ordered fallback candidates per Antigravity quota pool (cheapest first; never Opus).
1310
+ export const KICKSTART_FALLBACK_MODELS_FOR_QUOTA_POOL: Record<string, readonly string[]> = {
1311
+ claude: ["gpt-oss-120b-medium", "claude-sonnet-4-6"],
1312
+ };
1313
+
1314
+ // Paid (Pro/Ultra) Antigravity accounts advertise Claude 5.5 models and can hit
1315
+ // 503 on gpt-oss-120b-medium; prefer the cheapest low-effort Sonnet 5.5 model first.
1316
+ export const KICKSTART_PRO_MODELS_FOR_QUOTA_POOL: Record<string, readonly string[]> = {
1317
+ claude: [
1318
+ "claude-sonnet-5-5-low",
1319
+ "claude-sonnet-5-5-medium",
1320
+ "claude-sonnet-4-6",
1321
+ "gpt-oss-120b-medium",
1322
+ ],
1323
+ };
1324
+
1309
1325
  export const QUOTA_API_URL =
1310
1326
  "https://daily-cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels";
1311
1327
 
@@ -299,9 +299,9 @@ function getActiveNotifications(clientVersion) {
299
299
  const ALLOWED_EVENTS = new Set(["boot", "heartbeat", "shutdown", "flag"]);
300
300
  const ALLOWED_FEATURE_KEYS = new Set(["dashboard", "proAdvisor", "freshWindowToggle", "hostedLogin"]);
301
301
  const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
302
- const MAX_BODY_BYTES = 4096;
302
+ const MAX_BODY_BYTES = 32_768;
303
303
  const MAX_ADMIN_BODY_BYTES = 16_384;
304
- const MAX_MODELS = 20;
304
+ const MAX_MODELS = 200;
305
305
  const MAX_STRING_LEN = 128;
306
306
  const MAX_REQUESTS_CAP = 1_000_000_000;
307
307
  const MAX_TOKENS_CAP = 10_000_000_000_000;
@@ -320,9 +320,14 @@ function safeNonNegInt(val, max) {
320
320
  return Math.floor(val);
321
321
  }
322
322
 
323
+ const INSTALL_ID_RE = /^[a-zA-Z0-9._-]{4,64}$/;
324
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
325
+ const REQUIRE_UUID_INSTALL_ID = process.env.REQUIRE_UUID_INSTALL_ID === "1";
326
+
323
327
  function isCorePayload(data) {
324
328
  if (typeof data !== "object" || data === null) return false;
325
- if (typeof data.installId !== "string" || data.installId.length === 0 || data.installId.length > 64) return false;
329
+ if (typeof data.installId !== "string" || !INSTALL_ID_RE.test(data.installId)) return false;
330
+ if (REQUIRE_UUID_INSTALL_ID && !UUID_RE.test(data.installId)) return false;
326
331
  if (typeof data.version !== "string" || data.version.length > MAX_STRING_LEN) return false;
327
332
  if (typeof data.ts !== "string" || data.ts.length > 30) return false;
328
333
 
@@ -336,7 +341,7 @@ function isHeartbeatPayload(data) {
336
341
  if (typeof data.arch !== "string" || data.arch.length > MAX_STRING_LEN) return false;
337
342
  if (!isFiniteInRange(data.accountCount, 0, 1000)) return false;
338
343
  if (!Array.isArray(data.modelsUsed) || data.modelsUsed.length > MAX_MODELS) return false;
339
- if (!data.modelsUsed.every((m) => typeof m === "string" && m.length > 0 && m.length <= 64)) return false;
344
+ if (!data.modelsUsed.every((m) => typeof m === "string" && m.length > 0 && m.length <= MAX_STRING_LEN)) return false;
340
345
  if (!isFiniteInRange(data.totalRequests, 0, MAX_REQUESTS_CAP)) return false;
341
346
  if (!isFiniteInRange(data.uptimeSeconds, 0, MAX_UPTIME_CAP)) return false;
342
347
  if (typeof data.routingHealthState !== "string" || data.routingHealthState.length > 30) return false;
@@ -438,7 +443,7 @@ function storeEvent(payload) {
438
443
  receivedAt: new Date().toISOString(),
439
444
  accountCount: safeNonNegInt(payload.accountCount, 1000),
440
445
  modelsUsed: Array.isArray(payload.modelsUsed)
441
- ? payload.modelsUsed.filter((m) => typeof m === "string" && m.length > 0 && m.length <= 64).slice(0, MAX_MODELS)
446
+ ? payload.modelsUsed.filter((m) => typeof m === "string" && m.length > 0 && m.length <= MAX_STRING_LEN).slice(0, MAX_MODELS)
442
447
  : [],
443
448
  totalRequests: safeNonNegInt(payload.totalRequests, MAX_REQUESTS_CAP),
444
449
  uptimeSeconds: safeNonNegInt(payload.uptimeSeconds, MAX_UPTIME_CAP),
@@ -503,7 +508,7 @@ function sanitizeTokensByModel(raw) {
503
508
  let count = 0;
504
509
  for (const [model, data] of Object.entries(raw)) {
505
510
  if (count >= MAX_MODELS) break;
506
- if (typeof model !== "string" || model.length === 0 || model.length > 64 || FORBIDDEN_KEYS.has(model)) continue;
511
+ if (typeof model !== "string" || model.length === 0 || model.length > MAX_STRING_LEN || FORBIDDEN_KEYS.has(model)) continue;
507
512
  if (typeof data !== "object" || data === null) continue;
508
513
  clean[model] = {
509
514
  input: safeNonNegInt(data.input, MAX_TOKENS_CAP),
@@ -750,9 +755,28 @@ function buildFilterOptions(events, flagEvents) {
750
755
  }
751
756
 
752
757
 
758
+ // Merge cumulative tokensByModel snapshots per install using per-model maxima so
759
+ // cloned .telemetry-id machines, restarts, or empty/flag events never drop historical usage.
760
+ function mergeMaxTokens(target, tokensByModel) {
761
+ if (!tokensByModel || typeof tokensByModel !== "object" || Array.isArray(tokensByModel)) return;
762
+ for (const [model, data] of Object.entries(tokensByModel)) {
763
+ if (!model || FORBIDDEN_KEYS.has(model) || !data || typeof data !== "object") continue;
764
+ const inp = safeNonNegInt(data.input, MAX_TOKENS_CAP);
765
+ const out = safeNonNegInt(data.output, MAX_TOKENS_CAP);
766
+ const req = safeNonNegInt(data.requests, MAX_REQUESTS_CAP);
767
+ if (!target[model]) {
768
+ target[model] = { input: inp, output: out, requests: req };
769
+ } else {
770
+ if (inp > target[model].input) target[model].input = inp;
771
+ if (out > target[model].output) target[model].output = out;
772
+ if (req > target[model].requests) target[model].requests = req;
773
+ }
774
+ }
775
+ }
776
+
753
777
  // ── Per-install list ─────────────────────────────────────────────────
754
778
  // Returns one summary row per unique installId based on their latest
755
- // heartbeat/boot event + flag count over the same filtered window.
779
+ // non-flag heartbeat/boot/shutdown event + flag count over the same filtered window.
756
780
  function computeInstallList(filters = {}) {
757
781
  const { events: allEvents, flagEvents: allFlagEvents } = loadAllEvents();
758
782
 
@@ -776,18 +800,32 @@ function computeInstallList(filters = {}) {
776
800
  return true;
777
801
  });
778
802
 
779
- // Latest heartbeat snapshot per install
780
- const latest = Object.create(null); // installId -> ev
781
- for (const { ev } of events) {
782
- const prev = latest[ev.installId];
783
- if (!prev || ev.ts >= prev.ts) latest[ev.installId] = ev;
784
- }
785
-
786
- // First seen per install
803
+ // Latest non-flag state snapshot + latest overall timestamp per install.
804
+ // Excluding flag events from state prevents a recent flag (which lacks accountCount,
805
+ // OS, health, and tokensByModel) from overwriting the install's real profile with zeros.
806
+ const latestState = Object.create(null); // installId -> latest non-flag ev
807
+ const latestAny = Object.create(null); // installId -> latest ev (for lastSeen & fallback)
787
808
  const firstSeen = Object.create(null);
809
+ const maxRequests = Object.create(null);
810
+ const maxTokensByInstall = Object.create(null); // installId -> { [model]: { input, output, requests } }
811
+
788
812
  for (const { ev } of events) {
789
- if (!firstSeen[ev.installId] || ev.ts < firstSeen[ev.installId])
790
- firstSeen[ev.installId] = ev.ts;
813
+ const id = ev.installId;
814
+ if (!id) continue;
815
+ const prevAny = latestAny[id];
816
+ if (!prevAny || (ev.ts || '') >= (prevAny.ts || '')) latestAny[id] = ev;
817
+ if (!firstSeen[id] || (ev.ts || '') < firstSeen[id]) firstSeen[id] = ev.ts;
818
+
819
+ if (ev.event !== 'flag') {
820
+ const prevState = latestState[id];
821
+ if (!prevState || (ev.ts || '') >= (prevState.ts || '')) latestState[id] = ev;
822
+ const reqVal = safeNonNegInt(ev.totalRequests, MAX_REQUESTS_CAP);
823
+ if (reqVal > (maxRequests[id] || 0)) maxRequests[id] = reqVal;
824
+ if (ev.tokensByModel && typeof ev.tokensByModel === 'object') {
825
+ if (!maxTokensByInstall[id]) maxTokensByInstall[id] = Object.create(null);
826
+ mergeMaxTokens(maxTokensByInstall[id], ev.tokensByModel);
827
+ }
828
+ }
791
829
  }
792
830
 
793
831
  // Flag counts per install
@@ -796,24 +834,18 @@ function computeInstallList(filters = {}) {
796
834
  flagsByInstall[fl.installId] = (flagsByInstall[fl.installId] || 0) + 1;
797
835
  }
798
836
 
799
- // Total requests per install (max across all events — it's cumulative)
800
- const maxRequests = Object.create(null);
801
- for (const { ev } of events) {
802
- const cur = maxRequests[ev.installId] || 0;
803
- if ((ev.totalRequests || 0) > cur) maxRequests[ev.installId] = ev.totalRequests || 0;
804
- }
805
-
806
- const list = Object.values(latest).map((ev) => {
807
- const tokens = ev.tokensByModel && typeof ev.tokensByModel === 'object'
808
- ? ev.tokensByModel : {};
837
+ const list = Object.keys(latestAny).map((id) => {
838
+ const ev = latestState[id] || latestAny[id];
839
+ const anyEv = latestAny[id];
840
+ const tokens = maxTokensByInstall[id] || {};
809
841
  const savings = calculateSavings(tokens);
810
842
  return {
811
- installId: ev.installId,
812
- version: ev.version || '?',
843
+ installId: id,
844
+ version: ev.version || anyEv.version || '?',
813
845
  os: ev.os || '?',
814
846
  arch: ev.arch || '?',
815
847
  accountCount: safeNonNegInt(ev.accountCount, 1000),
816
- totalRequests: maxRequests[ev.installId] || 0,
848
+ totalRequests: maxRequests[id] || 0,
817
849
  routingHealthState: ev.routingHealthState || 'unknown',
818
850
  flaggedCount: safeNonNegInt(ev.flaggedCount, 1000),
819
851
  disabledCount: safeNonNegInt(ev.disabledCount, 1000),
@@ -821,9 +853,9 @@ function computeInstallList(filters = {}) {
821
853
  freeCount: safeNonNegInt(ev.freeCount, 1000),
822
854
  tokensByModel: tokens,
823
855
  savingsUsd: savings.totalUsd,
824
- flagEvents: flagsByInstall[ev.installId] || 0,
825
- lastSeen: ev.ts,
826
- firstSeen: firstSeen[ev.installId] || ev.ts,
856
+ flagEvents: flagsByInstall[id] || 0,
857
+ lastSeen: anyEv.ts || ev.ts,
858
+ firstSeen: firstSeen[id] || ev.ts,
827
859
  featuresUsed: ev.featuresUsed || {},
828
860
  };
829
861
  });
@@ -860,6 +892,7 @@ function computeStats(filters = {}) {
860
892
 
861
893
  const uniqueInstalls = new Set();
862
894
  let totalEvents = 0;
895
+ let nonFlagEvents = 0;
863
896
  let totalBoots = 0;
864
897
  let totalFlags = 0;
865
898
  const versionCounts = Object.create(null);
@@ -871,10 +904,11 @@ function computeStats(filters = {}) {
871
904
  const maxRequestsByInstall = Object.create(null); // installId -> max cumulative totalRequests
872
905
  let featuresCount = { dashboard: 0, proAdvisor: 0, freshWindowToggle: 0, hostedLogin: 0 };
873
906
 
874
- // tokensByModel is CUMULATIVE per install (each heartbeat sends total-since-boot).
875
- // To avoid multi-counting, track the LATEST snapshot per installId and sum those.
876
- const latestTokenSnapshotByInstall = Object.create(null); // installId → { ts, tokensByModel }
877
- const latestEventByInstall = Object.create(null); // installId → ev
907
+ // tokensByModel is CUMULATIVE per install; track per-model max per installId so cloned
908
+ // .telemetry-id machines, restarts, or flag events never erase prior usage.
909
+ const maxTokensByInstall = Object.create(null); // installId → { [model]: { input, output, requests } }
910
+ const latestStateByInstall = Object.create(null); // installId → latest non-flag ev
911
+ const latestSeenByInstall = Object.create(null); // installId → latest ev (any type, for activity)
878
912
  const dailyMap = Object.create(null); // YYYY-MM-DD → { date, events, installs: Set, boots, mainFlags, detailFlags }
879
913
 
880
914
  function ensureDay(date) {
@@ -889,15 +923,7 @@ function computeStats(filters = {}) {
889
923
  uniqueInstalls.add(ev.installId);
890
924
  if (ev.event === "boot") totalBoots++;
891
925
  if (ev.event === "flag") totalFlags++;
892
- versionCounts[ev.version] = (versionCounts[ev.version] || 0) + 1;
893
- osCounts[ev.os] = (osCounts[ev.os] || 0) + 1;
894
- archCounts[ev.arch] = (archCounts[ev.arch] || 0) + 1;
895
- healthCounts[ev.routingHealthState] = (healthCounts[ev.routingHealthState] || 0) + 1;
896
- totalAccounts += safeNonNegInt(ev.accountCount, 1000);
897
- const reqVal = safeNonNegInt(ev.totalRequests, MAX_REQUESTS_CAP);
898
- if (ev.installId && reqVal > (maxRequestsByInstall[ev.installId] || 0)) {
899
- maxRequestsByInstall[ev.installId] = reqVal;
900
- }
926
+ if (ev.version) versionCounts[ev.version] = (versionCounts[ev.version] || 0) + 1;
901
927
 
902
928
  const day = ensureDay(file.replace(".jsonl", ""));
903
929
  day.events++;
@@ -905,33 +931,49 @@ function computeStats(filters = {}) {
905
931
  if (ev.event === "boot") day.boots++;
906
932
  if (ev.event === "flag") day.mainFlags++;
907
933
 
908
- const prevEv = latestEventByInstall[ev.installId];
909
- if (!prevEv || (ev.ts || "") >= (prevEv.ts || "")) {
910
- latestEventByInstall[ev.installId] = ev;
934
+ const prevSeen = latestSeenByInstall[ev.installId];
935
+ if (!prevSeen || (ev.ts || "") >= (prevSeen.ts || "")) {
936
+ latestSeenByInstall[ev.installId] = ev;
911
937
  }
912
938
 
913
- // Keep only the most recent token snapshot per install
914
- if (ev.tokensByModel && typeof ev.tokensByModel === "object") {
915
- const prev = latestTokenSnapshotByInstall[ev.installId];
916
- if (!prev || ev.ts >= prev.ts) {
917
- latestTokenSnapshotByInstall[ev.installId] = { ts: ev.ts, tokensByModel: ev.tokensByModel };
939
+ if (ev.event !== "flag") {
940
+ nonFlagEvents++;
941
+ if (ev.os) osCounts[ev.os] = (osCounts[ev.os] || 0) + 1;
942
+ if (ev.arch) archCounts[ev.arch] = (archCounts[ev.arch] || 0) + 1;
943
+ if (ev.routingHealthState) healthCounts[ev.routingHealthState] = (healthCounts[ev.routingHealthState] || 0) + 1;
944
+ totalAccounts += safeNonNegInt(ev.accountCount, 1000);
945
+ const reqVal = safeNonNegInt(ev.totalRequests, MAX_REQUESTS_CAP);
946
+ if (ev.installId && reqVal > (maxRequestsByInstall[ev.installId] || 0)) {
947
+ maxRequestsByInstall[ev.installId] = reqVal;
918
948
  }
919
- }
920
- for (const m of ev.modelsUsed || []) modelCounts[m] = (modelCounts[m] || 0) + 1;
921
- if (ev.featuresUsed && typeof ev.featuresUsed === "object") {
922
- for (const [k, v] of Object.entries(ev.featuresUsed)) {
923
- if (v === true && Object.hasOwn(featuresCount, k)) featuresCount[k]++;
949
+
950
+ const prevState = latestStateByInstall[ev.installId];
951
+ if (!prevState || (ev.ts || "") >= (prevState.ts || "")) {
952
+ latestStateByInstall[ev.installId] = ev;
953
+ }
954
+
955
+ if (ev.installId && ev.tokensByModel && typeof ev.tokensByModel === "object") {
956
+ if (!maxTokensByInstall[ev.installId]) maxTokensByInstall[ev.installId] = Object.create(null);
957
+ mergeMaxTokens(maxTokensByInstall[ev.installId], ev.tokensByModel);
958
+ }
959
+ for (const m of ev.modelsUsed || []) modelCounts[m] = (modelCounts[m] || 0) + 1;
960
+ if (ev.featuresUsed && typeof ev.featuresUsed === "object") {
961
+ for (const [k, v] of Object.entries(ev.featuresUsed)) {
962
+ if (v === true && Object.hasOwn(featuresCount, k)) featuresCount[k]++;
963
+ }
924
964
  }
925
965
  }
926
966
  }
927
967
 
928
- // Fleet summary from latest snapshot per unique install
968
+ // Fleet summary from latest non-flag state snapshot per unique install
929
969
  const nowMs = Date.now();
930
970
  const DAY_MS = 24 * 60 * 60 * 1000;
931
971
  const fleet = {
932
972
  active24h: 0,
933
973
  active7d: 0,
934
974
  totalAccounts: 0,
975
+ avgAccounts: 0,
976
+ medianAccounts: 0,
935
977
  proAccounts: 0,
936
978
  freeAccounts: 0,
937
979
  flaggedAccounts: 0,
@@ -940,13 +982,18 @@ function computeStats(filters = {}) {
940
982
  osByInstall: Object.create(null),
941
983
  versionByInstall: Object.create(null),
942
984
  };
943
- for (const ev of Object.values(latestEventByInstall)) {
944
- const tsMs = Date.parse(ev.ts || ev.receivedAt || "");
985
+ const accountCountsPerInstall = [];
986
+ for (const id of Object.keys(latestSeenByInstall)) {
987
+ const seenEv = latestSeenByInstall[id];
988
+ const ev = latestStateByInstall[id] || seenEv;
989
+ const tsMs = Date.parse(seenEv.ts || seenEv.receivedAt || "");
945
990
  if (Number.isFinite(tsMs)) {
946
991
  if (nowMs - tsMs <= DAY_MS) fleet.active24h++;
947
992
  if (nowMs - tsMs <= 7 * DAY_MS) fleet.active7d++;
948
993
  }
949
- fleet.totalAccounts += safeNonNegInt(ev.accountCount, 1000);
994
+ const accCount = safeNonNegInt(ev.accountCount, 1000);
995
+ accountCountsPerInstall.push(accCount);
996
+ fleet.totalAccounts += accCount;
950
997
  fleet.proAccounts += safeNonNegInt(ev.proCount, 1000);
951
998
  fleet.freeAccounts += safeNonNegInt(ev.freeCount, 1000);
952
999
  fleet.flaggedAccounts += safeNonNegInt(ev.flaggedCount, 1000);
@@ -955,16 +1002,24 @@ function computeStats(filters = {}) {
955
1002
  fleet.healthByInstall[health] = (fleet.healthByInstall[health] || 0) + 1;
956
1003
  const osKey = ev.os || "unknown";
957
1004
  fleet.osByInstall[osKey] = (fleet.osByInstall[osKey] || 0) + 1;
958
- const verKey = ev.version || "unknown";
1005
+ const verKey = ev.version || seenEv.version || "unknown";
959
1006
  fleet.versionByInstall[verKey] = (fleet.versionByInstall[verKey] || 0) + 1;
960
1007
  }
1008
+ if (accountCountsPerInstall.length > 0) {
1009
+ accountCountsPerInstall.sort((a, b) => a - b);
1010
+ const mid = Math.floor(accountCountsPerInstall.length / 2);
1011
+ fleet.medianAccounts = accountCountsPerInstall.length % 2 === 1
1012
+ ? accountCountsPerInstall[mid]
1013
+ : Math.round(((accountCountsPerInstall[mid - 1] + accountCountsPerInstall[mid]) / 2) * 10) / 10;
1014
+ fleet.avgAccounts = Math.round((fleet.totalAccounts / accountCountsPerInstall.length) * 10) / 10;
1015
+ }
961
1016
 
962
- // Aggregate latest token snapshot per install into global totals
1017
+ // Aggregate per-model max tokens per install into global totals
963
1018
  const globalTokensByModel = Object.create(null);
964
1019
  let totalInputTokens = 0;
965
1020
  let totalOutputTokens = 0;
966
1021
  let totalTokenRequests = 0;
967
- for (const { tokensByModel } of Object.values(latestTokenSnapshotByInstall)) {
1022
+ for (const tokensByModel of Object.values(maxTokensByInstall)) {
968
1023
  for (const [model, data] of Object.entries(tokensByModel)) {
969
1024
  if (!globalTokensByModel[model]) globalTokensByModel[model] = { input: 0, output: 0, requests: 0 };
970
1025
  globalTokensByModel[model].input += data.input || 0;
@@ -1077,7 +1132,8 @@ function computeStats(filters = {}) {
1077
1132
  uniqueInstalls: uniqueInstalls.size,
1078
1133
  totalEvents,
1079
1134
  totalBoots,
1080
- avgAccountsPerEvent: totalEvents > 0 ? Math.round(totalAccounts / totalEvents * 10) / 10 : 0,
1135
+ avgAccountsPerEvent: nonFlagEvents > 0 ? Math.round(totalAccounts / nonFlagEvents * 10) / 10 : 0,
1136
+ avgAccountsPerInstall: fleet.avgAccounts,
1081
1137
  totalRequestsAcrossAll,
1082
1138
  fleet,
1083
1139
  daily,
@@ -2757,7 +2813,7 @@ function render(d){
2757
2813
  {l:'Requests Routed',v:fmtCompact(d.totalRequestsAcrossAll),sub:fmt(d.totalRequestsAcrossAll)+' total | '+fmt(d.totalEvents)+' ev',c:'c-amber'},
2758
2814
  {l:'Estimated Savings',v:usd(sv.totalUsd),sub:Object.keys(sv.byModel||{}).length+' priced models',c:'c-green'},
2759
2815
  {l:'Token Volume',v:fmtCompact((tok.totalInput||0)+(tok.totalOutput||0)),sub:'IN '+fmtCompact(tok.totalInput)+' / OUT '+fmtCompact(tok.totalOutput),c:'c-violet'},
2760
- {l:'Fleet Accounts',v:fmt(fleet.totalAccounts||0),sub:'P:'+fmt(fleet.proAccounts||0)+' F:'+fmt(fleet.freeAccounts||0)+(fleet.flaggedAccounts?' | FLG:'+fleet.flaggedAccounts:''),c:fleet.flaggedAccounts?'c-amber':'c-cyan'},
2816
+ {l:'Fleet Accounts',v:fmt(fleet.totalAccounts||0),sub:'P:'+fmt(fleet.proAccounts||0)+' F:'+fmt(fleet.freeAccounts||0)+(fleet.flaggedAccounts?' | FLG:'+fleet.flaggedAccounts:'')+' | med '+fmt(fleet.medianAccounts||0),c:fleet.flaggedAccounts?'c-amber':'c-cyan'},
2761
2817
  {l:'Flag Signals',v:fmt(totalFlags),sub:fmt(fl.uniqueIncidents||0)+' unique | avg '+fmt(fl.avgRequestsBeforeFlag||0)+' req',c:totalFlags>0?'c-red':'c-green'}
2762
2818
  ].map(function(k){
2763
2819
  return '<article class="kpi '+k.c+'"><div class="kpi-label">'+esc(k.l)+'</div><div class="kpi-value">'+esc(k.v)+'</div><div class="kpi-sub">'+esc(k.sub)+'</div></article>';