tuxevil-rotator 3.5.0 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,14 @@
1
1
  // Dynamic Google Antigravity model availability discovered during quota polling.
2
2
 
3
- import type { ModelSpec } from "../../compat/model-specs.js";
4
- import type { GoogleQuotaResponse } from "../../types.js";
3
+ import {
4
+ getStaticModelSpec,
5
+ type ModelSpec,
6
+ } from "../../compat/model-specs.js";
7
+ import {
8
+ QUOTA_MODEL_KEYS,
9
+ type GoogleQuotaResponse,
10
+ type PersistedDynamicModelOwnership,
11
+ } from "../../types.js";
5
12
 
6
13
  export interface DynamicModelEntry {
7
14
  id: string;
@@ -12,12 +19,146 @@ export interface DynamicModelEntry {
12
19
  tools: boolean;
13
20
  maxOutputTokens: number;
14
21
  thinkingBudget: number;
22
+ minThinkingBudget?: number;
15
23
  isThinking: boolean;
16
24
  isTiered: boolean;
17
25
  displayName?: string;
18
26
  }
19
27
 
20
28
  const DEFAULT_ACCOUNT_KEY = "__default__";
29
+ const RESERVED_QUOTA_MODEL_IDS = new Set(
30
+ Object.values(QUOTA_MODEL_KEYS).map(({ key }) => key.toLowerCase()),
31
+ );
32
+
33
+ type GoogleModelInfo = GoogleQuotaResponse["models"][string];
34
+ type ActiveAccount = string | { id: string; generation: string };
35
+ type PersistedOwnershipAccount = {
36
+ id: string;
37
+ credentialGenerationFingerprint: string;
38
+ };
39
+ interface ActiveAccountGeneration {
40
+ credentialGeneration: string | null;
41
+ epoch: number;
42
+ }
43
+
44
+ function isRecord(value: unknown): value is Record<string, unknown> {
45
+ return typeof value === "object" && value !== null && !Array.isArray(value);
46
+ }
47
+
48
+ function isSafeModelId(value: string): boolean {
49
+ const lower = value.toLowerCase();
50
+ return value.length <= 256 &&
51
+ /^[a-z0-9][a-z0-9._:/-]*$/i.test(value) &&
52
+ lower !== "__proto__" &&
53
+ lower !== "prototype" &&
54
+ lower !== "constructor";
55
+ }
56
+
57
+ function isDiscoverableModelId(value: string): boolean {
58
+ const id = value.trim();
59
+ const lower = id.toLowerCase();
60
+ return isSafeModelId(id) &&
61
+ !RESERVED_QUOTA_MODEL_IDS.has(lower) &&
62
+ !lower.startsWith("chat_") &&
63
+ !lower.startsWith("tab_") &&
64
+ !lower.startsWith("gemini-3.5-");
65
+ }
66
+
67
+ /** Validate and sanitize the untrusted runtime catalog response. */
68
+ export function parseGoogleQuotaResponse(
69
+ value: unknown,
70
+ ): GoogleQuotaResponse | null {
71
+ if (!isRecord(value) || !isRecord(value.models)) return null;
72
+
73
+ const models = Object.create(null) as GoogleQuotaResponse["models"];
74
+ let rawEntryCount = 0;
75
+ let validEntryCount = 0;
76
+ for (const [rawId, rawInfo] of Object.entries(value.models)) {
77
+ rawEntryCount++;
78
+ const id = rawId.trim();
79
+ if (!isSafeModelId(id) || !isRecord(rawInfo)) continue;
80
+ validEntryCount++;
81
+
82
+ const info: GoogleModelInfo = {};
83
+ if (typeof rawInfo.displayName === "string" && rawInfo.displayName.trim()) {
84
+ info.displayName = rawInfo.displayName.trim();
85
+ }
86
+ for (const field of ["maxTokens", "maxOutputTokens"] as const) {
87
+ const candidate = rawInfo[field];
88
+ if (typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0) {
89
+ info[field] = candidate;
90
+ }
91
+ }
92
+ if (
93
+ typeof rawInfo.thinkingBudget === "number" &&
94
+ Number.isFinite(rawInfo.thinkingBudget) &&
95
+ (rawInfo.thinkingBudget === -1 || rawInfo.thinkingBudget >= 0)
96
+ ) {
97
+ info.thinkingBudget = rawInfo.thinkingBudget;
98
+ }
99
+ if (
100
+ typeof rawInfo.minThinkingBudget === "number" &&
101
+ Number.isFinite(rawInfo.minThinkingBudget) &&
102
+ rawInfo.minThinkingBudget >= 0
103
+ ) {
104
+ info.minThinkingBudget = rawInfo.minThinkingBudget;
105
+ }
106
+ for (
107
+ const field of [
108
+ "supportsThinking",
109
+ "supportsImages",
110
+ "supportsVideo",
111
+ ] as const
112
+ ) {
113
+ if (typeof rawInfo[field] === "boolean") info[field] = rawInfo[field];
114
+ }
115
+ if (isRecord(rawInfo.quotaInfo)) {
116
+ const quotaInfo: NonNullable<GoogleModelInfo["quotaInfo"]> = {};
117
+ const remaining = rawInfo.quotaInfo.remainingFraction;
118
+ if (
119
+ typeof remaining === "number" &&
120
+ Number.isFinite(remaining) &&
121
+ remaining >= 0 &&
122
+ remaining <= 1
123
+ ) {
124
+ quotaInfo.remainingFraction = remaining;
125
+ }
126
+ const resetTime = rawInfo.quotaInfo.resetTime;
127
+ if (typeof resetTime === "string" && resetTime.trim()) {
128
+ quotaInfo.resetTime = resetTime;
129
+ }
130
+ if (Object.keys(quotaInfo).length > 0) info.quotaInfo = quotaInfo;
131
+ }
132
+ models[id] = info;
133
+ }
134
+
135
+ // An explicitly empty catalog is a valid snapshot. A non-empty catalog
136
+ // containing no usable entries is ambiguous, so retain the last good one.
137
+ if (rawEntryCount > 0 && validEntryCount === 0) return null;
138
+
139
+ const parsed: GoogleQuotaResponse = { models };
140
+ if (
141
+ typeof value.defaultAgentModelId === "string" &&
142
+ isSafeModelId(value.defaultAgentModelId.trim())
143
+ ) {
144
+ parsed.defaultAgentModelId = value.defaultAgentModelId.trim();
145
+ }
146
+ if (isRecord(value.tieredModelIds)) {
147
+ const tieredModelIds = Object.create(null) as Record<string, string[]>;
148
+ for (const [tier, rawIds] of Object.entries(value.tieredModelIds)) {
149
+ if (!Array.isArray(rawIds)) continue;
150
+ const ids = rawIds
151
+ .filter((id): id is string => typeof id === "string")
152
+ .map((id) => id.trim())
153
+ .filter(isSafeModelId);
154
+ if (ids.length > 0) tieredModelIds[tier] = ids;
155
+ }
156
+ if (Object.keys(tieredModelIds).length > 0) {
157
+ parsed.tieredModelIds = tieredModelIds;
158
+ }
159
+ }
160
+ return parsed;
161
+ }
21
162
 
22
163
  function accountKey(value: string): string {
23
164
  return value.trim();
@@ -73,7 +214,17 @@ export class DynamicModelRegistry {
73
214
  private static instance: DynamicModelRegistry | null = null;
74
215
  private accountModels = new Map<string, Map<string, DynamicModelEntry>>();
75
216
  private defaultAgentModelIds = new Map<string, string>();
76
- private discoveredModelIds = new Set<string>();
217
+ private discoveredModels = new Map<
218
+ string,
219
+ Pick<DynamicModelEntry, "id" | "quotaPool">
220
+ >();
221
+ private accountModelOwnership = new Map<string, Set<string>>();
222
+ private ownershipScopedModels = new Set<string>();
223
+ private activeAccountGenerations: Map<
224
+ string,
225
+ ActiveAccountGeneration
226
+ > | null = null;
227
+ private nextAccountEpoch = 0;
77
228
 
78
229
  static getInstance(): DynamicModelRegistry {
79
230
  DynamicModelRegistry.instance ??= new DynamicModelRegistry();
@@ -84,7 +235,11 @@ export class DynamicModelRegistry {
84
235
  reset(): void {
85
236
  this.accountModels.clear();
86
237
  this.defaultAgentModelIds.clear();
87
- this.discoveredModelIds.clear();
238
+ this.discoveredModels.clear();
239
+ this.accountModelOwnership.clear();
240
+ this.ownershipScopedModels.clear();
241
+ this.activeAccountGenerations = null;
242
+ this.nextAccountEpoch = 0;
88
243
  }
89
244
 
90
245
  /** Derive the model family and quota pool from a model ID string. */
@@ -106,12 +261,22 @@ export class DynamicModelRegistry {
106
261
 
107
262
  /** Replace one account's advertised models with its latest successful response. */
108
263
  updateFromEndpointResponse(
109
- data: GoogleQuotaResponse,
264
+ value: unknown,
110
265
  accountId = DEFAULT_ACCOUNT_KEY,
266
+ credentialGeneration?: string,
267
+ accountEpoch?: number,
111
268
  ): number {
112
- if (!data || typeof data !== "object" || !data.models) return 0;
269
+ const data = parseGoogleQuotaResponse(value);
270
+ if (!data) return 0;
113
271
 
114
272
  const key = accountKey(accountId);
273
+ if (
274
+ !this.isAccountGenerationActive(
275
+ key,
276
+ credentialGeneration,
277
+ accountEpoch,
278
+ )
279
+ ) return 0;
115
280
  const previous = this.accountModels.get(key);
116
281
  const knownBefore = new Set(this.getAllModels().map((model) => model.id.toLowerCase()));
117
282
  const next = new Map<string, DynamicModelEntry>();
@@ -130,16 +295,23 @@ export class DynamicModelRegistry {
130
295
  for (const [rawId, info] of Object.entries(data.models)) {
131
296
  const normalizedId = rawId.trim();
132
297
  const lowerId = normalizedId.toLowerCase();
133
- if (
134
- !lowerId ||
135
- lowerId.startsWith("chat_") ||
136
- lowerId.startsWith("tab_") ||
137
- lowerId.startsWith("gemini-3.5-")
138
- ) continue;
298
+ if (!isDiscoverableModelId(normalizedId)) continue;
139
299
 
140
- this.discoveredModelIds.add(lowerId);
141
300
  const { family, quotaPool } = DynamicModelRegistry.inferFamilyAndPool(normalizedId);
142
- const defaults = previous?.get(lowerId) ?? familyDefaults(family);
301
+ const familySpec = familyDefaults(family);
302
+ const staticSpec = getStaticModelSpec(normalizedId);
303
+ const defaults = previous?.get(lowerId) ?? {
304
+ ...familySpec,
305
+ ...(staticSpec
306
+ ? {
307
+ ctx: staticSpec.contextWindow ?? familySpec.ctx,
308
+ maxOutputTokens: staticSpec.maxOutputTokens,
309
+ thinkingBudget: staticSpec.thinkingBudget,
310
+ minThinkingBudget: staticSpec.minThinkingBudget,
311
+ isThinking: staticSpec.isThinking,
312
+ }
313
+ : {}),
314
+ };
143
315
  const isTiered = lowerId.includes("-tiered") || tieredIds.has(lowerId);
144
316
  const hasThinkingBudget = typeof info.thinkingBudget === "number";
145
317
  const thinkingBudget = hasThinkingBudget
@@ -171,26 +343,96 @@ export class DynamicModelRegistry {
171
343
  ? info.maxOutputTokens
172
344
  : defaults.maxOutputTokens,
173
345
  thinkingBudget,
346
+ minThinkingBudget:
347
+ typeof info.minThinkingBudget === "number"
348
+ ? info.minThinkingBudget
349
+ : defaults.minThinkingBudget,
174
350
  isThinking,
175
351
  isTiered,
176
352
  displayName: info.displayName ?? previous?.get(lowerId)?.displayName ?? normalizedId,
177
353
  });
354
+ this.discoveredModels.set(lowerId, { id: normalizedId, quotaPool });
355
+ this.ownershipScopedModels.add(lowerId);
178
356
  if (!knownBefore.has(lowerId)) newModelsCount++;
179
357
  }
180
358
 
181
359
  this.accountModels.set(key, next);
360
+ this.accountModelOwnership.set(key, new Set(next.keys()));
182
361
  return newModelsCount;
183
362
  }
184
363
 
185
364
  /** Expire catalogs belonging to accounts that are no longer active. */
186
- retainAccounts(accountIds: Iterable<string>): void {
187
- const active = new Set(Array.from(accountIds, accountKey));
365
+ retainAccounts(accounts: Iterable<ActiveAccount>): void {
366
+ const previous = this.activeAccountGenerations;
367
+ const active = new Map<string, ActiveAccountGeneration>();
368
+ for (const account of accounts) {
369
+ const key = accountKey(typeof account === "string" ? account : account.id);
370
+ const credentialGeneration = typeof account === "string"
371
+ ? null
372
+ : account.generation;
373
+ const prior = previous?.get(key);
374
+ active.set(
375
+ key,
376
+ prior?.credentialGeneration === credentialGeneration
377
+ ? prior
378
+ : { credentialGeneration, epoch: ++this.nextAccountEpoch },
379
+ );
380
+ }
188
381
  for (const key of this.accountModels.keys()) {
189
- if (!active.has(key)) this.accountModels.delete(key);
382
+ const nextGeneration = active.get(key)?.credentialGeneration;
383
+ const previousGeneration = previous?.get(key)?.credentialGeneration;
384
+ if (
385
+ !active.has(key) ||
386
+ (previousGeneration !== undefined && previousGeneration !== nextGeneration)
387
+ ) {
388
+ this.accountModels.delete(key);
389
+ }
390
+ }
391
+ for (const key of this.accountModelOwnership.keys()) {
392
+ const nextGeneration = active.get(key)?.credentialGeneration;
393
+ const previousGeneration = previous?.get(key)?.credentialGeneration;
394
+ if (
395
+ !active.has(key) ||
396
+ (previousGeneration !== undefined && previousGeneration !== nextGeneration)
397
+ ) {
398
+ this.accountModelOwnership.delete(key);
399
+ }
190
400
  }
191
401
  for (const key of this.defaultAgentModelIds.keys()) {
192
- if (!active.has(key)) this.defaultAgentModelIds.delete(key);
402
+ if (!this.accountModels.has(key)) this.defaultAgentModelIds.delete(key);
403
+ }
404
+ this.activeAccountGenerations = active;
405
+ }
406
+
407
+ captureAccountEpoch(
408
+ accountId: string,
409
+ credentialGeneration: string,
410
+ ): number | null | undefined {
411
+ if (!this.activeAccountGenerations) return undefined;
412
+ const active = this.activeAccountGenerations.get(accountKey(accountId));
413
+ if (
414
+ !active ||
415
+ (active.credentialGeneration !== null &&
416
+ active.credentialGeneration !== credentialGeneration)
417
+ ) {
418
+ return null;
193
419
  }
420
+ return active.epoch;
421
+ }
422
+
423
+ isAccountGenerationActive(
424
+ accountId: string,
425
+ credentialGeneration?: string,
426
+ accountEpoch?: number,
427
+ ): boolean {
428
+ if (!this.activeAccountGenerations) return true;
429
+ const key = accountKey(accountId);
430
+ const active = this.activeAccountGenerations.get(key);
431
+ if (!active) return false;
432
+ if (accountEpoch !== undefined && active.epoch !== accountEpoch) return false;
433
+ return credentialGeneration === undefined ||
434
+ active.credentialGeneration === null ||
435
+ active.credentialGeneration === credentialGeneration;
194
436
  }
195
437
 
196
438
  getAllModels(): DynamicModelEntry[] {
@@ -211,13 +453,116 @@ export class DynamicModelRegistry {
211
453
  }
212
454
 
213
455
  hasModelForAccount(accountId: string, id: string): boolean {
214
- return this.accountModels
456
+ return this.accountModelOwnership
215
457
  .get(accountKey(accountId))
216
458
  ?.has(id.trim().toLowerCase()) ?? false;
217
459
  }
218
460
 
461
+ hasOwnershipForModel(id: string): boolean {
462
+ return this.ownershipScopedModels.has(id.trim().toLowerCase());
463
+ }
464
+
219
465
  wasDiscovered(id: string): boolean {
220
- return this.discoveredModelIds.has(id.trim().toLowerCase());
466
+ return this.discoveredModels.has(id.trim().toLowerCase());
467
+ }
468
+
469
+ getObservedModelId(id: string): string | undefined {
470
+ return this.getModel(id)?.id ??
471
+ this.discoveredModels.get(id.trim().toLowerCase())?.id;
472
+ }
473
+
474
+ getDiscoveredQuotaPools(): Record<string, string> {
475
+ const pools = Object.create(null) as Record<string, string>;
476
+ for (const { id, quotaPool } of this.discoveredModels.values()) {
477
+ pools[id] = quotaPool;
478
+ }
479
+ return pools;
480
+ }
481
+
482
+ getPersistedModelOwnership(
483
+ accounts: Iterable<PersistedOwnershipAccount>,
484
+ ): PersistedDynamicModelOwnership {
485
+ const persistedAccounts = Object.create(null) as PersistedDynamicModelOwnership["accounts"];
486
+ for (const account of accounts) {
487
+ const id = accountKey(account.id);
488
+ const models = this.accountModelOwnership.get(id);
489
+ if (!models) continue;
490
+ persistedAccounts[id] = {
491
+ credentialGenerationFingerprint:
492
+ account.credentialGenerationFingerprint,
493
+ models: Array.from(models).sort(),
494
+ };
495
+ }
496
+ return {
497
+ scopedModels: Array.from(this.ownershipScopedModels).sort(),
498
+ accounts: persistedAccounts,
499
+ };
500
+ }
501
+
502
+ restorePersistedModelOwnership(
503
+ value: unknown,
504
+ accounts: Iterable<PersistedOwnershipAccount>,
505
+ ): void {
506
+ if (
507
+ !isRecord(value) ||
508
+ !Array.isArray(value.scopedModels) ||
509
+ !isRecord(value.accounts)
510
+ ) return;
511
+
512
+ const expectedGenerations = new Map(
513
+ Array.from(accounts, (account) => [
514
+ accountKey(account.id),
515
+ account.credentialGenerationFingerprint,
516
+ ]),
517
+ );
518
+ const scopedModels = new Set<string>();
519
+ for (const rawModel of value.scopedModels) {
520
+ if (typeof rawModel !== "string") continue;
521
+ const model = rawModel.trim().toLowerCase();
522
+ if (
523
+ isDiscoverableModelId(model) &&
524
+ this.discoveredModels.has(model)
525
+ ) scopedModels.add(model);
526
+ }
527
+
528
+ const restoredAccounts = new Map<string, Set<string>>();
529
+ for (const [rawAccountId, rawSnapshot] of Object.entries(value.accounts)) {
530
+ const accountId = accountKey(rawAccountId);
531
+ const expectedGeneration = expectedGenerations.get(accountId);
532
+ if (
533
+ !expectedGeneration ||
534
+ !isRecord(rawSnapshot) ||
535
+ rawSnapshot.credentialGenerationFingerprint !== expectedGeneration ||
536
+ !Array.isArray(rawSnapshot.models)
537
+ ) continue;
538
+ const models = new Set<string>();
539
+ for (const rawModel of rawSnapshot.models) {
540
+ if (typeof rawModel !== "string") continue;
541
+ const model = rawModel.trim().toLowerCase();
542
+ if (scopedModels.has(model)) models.add(model);
543
+ }
544
+ restoredAccounts.set(accountId, models);
545
+ }
546
+
547
+ for (const model of scopedModels) this.ownershipScopedModels.add(model);
548
+ for (const [accountId, models] of restoredAccounts) {
549
+ this.accountModelOwnership.set(accountId, models);
550
+ }
551
+ }
552
+
553
+ restoreDiscoveredQuotaPools(value: unknown): void {
554
+ if (!isRecord(value)) return;
555
+ for (const [rawId, rawPool] of Object.entries(value)) {
556
+ const id = rawId.trim();
557
+ const quotaPool = typeof rawPool === "string"
558
+ ? rawPool.trim().toLowerCase()
559
+ : "";
560
+ if (
561
+ !isDiscoverableModelId(id) ||
562
+ (quotaPool !== "gemini" && quotaPool !== "claude")
563
+ ) continue;
564
+ this.discoveredModels.set(id.toLowerCase(), { id, quotaPool });
565
+ }
221
566
  }
222
567
 
223
568
  getModelSpec(id: string): ModelSpec | undefined {
@@ -226,6 +571,9 @@ export class DynamicModelRegistry {
226
571
  return {
227
572
  maxOutputTokens: entry.maxOutputTokens,
228
573
  thinkingBudget: entry.thinkingBudget,
574
+ ...(entry.minThinkingBudget !== undefined
575
+ ? { minThinkingBudget: entry.minThinkingBudget }
576
+ : {}),
229
577
  isThinking: entry.isThinking,
230
578
  contextWindow: entry.ctx,
231
579
  };
@@ -241,7 +589,9 @@ export class DynamicModelRegistry {
241
589
  }
242
590
 
243
591
  resolveQuotaPool(id: string): string | undefined {
244
- return this.getModel(id)?.quotaPool;
592
+ const lowerId = id.trim().toLowerCase();
593
+ return this.getModel(lowerId)?.quotaPool ??
594
+ this.discoveredModels.get(lowerId)?.quotaPool;
245
595
  }
246
596
 
247
597
  getDefaultAgentModelId(): string | null {
@@ -12,13 +12,38 @@ import {
12
12
  QUOTA_MODEL_KEYS,
13
13
  } from "../../types.js";
14
14
  import { fetchWithRetry } from "../../fetch-with-retry.js";
15
- import { getAccountIdentity } from "../../account-identity.js";
15
+ import {
16
+ getAccountIdentity,
17
+ getCredentialGeneration,
18
+ } from "../../account-identity.js";
16
19
  import type { QuotaFetchContext } from "../adapter.js";
17
20
  import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
18
21
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
19
22
  import { sortQuotaPools } from "../registry.js";
20
23
 
21
- import { dynamicCatalog, DynamicModelRegistry } from "./dynamic-catalog.js";
24
+ import {
25
+ dynamicCatalog,
26
+ DynamicModelRegistry,
27
+ parseGoogleQuotaResponse,
28
+ } from "./dynamic-catalog.js";
29
+
30
+ type GoogleModelInfo = GoogleQuotaResponse["models"][string];
31
+ type GoogleModelInfoWithQuota = GoogleModelInfo & {
32
+ quotaInfo: NonNullable<GoogleModelInfo["quotaInfo"]> & {
33
+ remainingFraction: number;
34
+ };
35
+ };
36
+
37
+ function hasUsableQuotaInfo(
38
+ info: GoogleModelInfo | undefined,
39
+ ): info is GoogleModelInfoWithQuota {
40
+ if (!info?.quotaInfo) return false;
41
+ const remaining = info.quotaInfo.remainingFraction;
42
+ return typeof remaining === "number" &&
43
+ Number.isFinite(remaining) &&
44
+ remaining >= 0 &&
45
+ remaining <= 1;
46
+ }
22
47
 
23
48
  /**
24
49
  * Extract per-model quotas from a Google quota response, preserving the
@@ -32,18 +57,21 @@ export function extractQuotas(
32
57
  const now = Date.now();
33
58
 
34
59
  for (const [, config] of Object.entries(QUOTA_MODEL_KEYS)) {
35
- let modelInfo = data.models[config.key];
36
-
37
- if (!modelInfo) {
38
- for (const altKey of config.altKeys) {
39
- modelInfo = data.models[altKey];
40
- if (modelInfo) break;
60
+ let modelInfo: GoogleModelInfoWithQuota | undefined;
61
+ for (const candidate of [config.key, ...config.altKeys]) {
62
+ const info = data.models[candidate];
63
+ if (hasUsableQuotaInfo(info)) {
64
+ modelInfo = info;
65
+ break;
41
66
  }
42
67
  }
43
68
 
44
69
  if (!modelInfo) {
45
70
  for (const [modelKey, info] of Object.entries(data.models)) {
46
- if (DynamicModelRegistry.inferFamilyAndPool(modelKey).quotaPool === config.key) {
71
+ if (
72
+ DynamicModelRegistry.inferFamilyAndPool(modelKey).quotaPool === config.key &&
73
+ hasUsableQuotaInfo(info)
74
+ ) {
47
75
  modelInfo = info;
48
76
  break;
49
77
  }
@@ -51,7 +79,7 @@ export function extractQuotas(
51
79
  }
52
80
 
53
81
  if (modelInfo?.quotaInfo) {
54
- const remainingFraction = modelInfo.quotaInfo.remainingFraction ?? 0;
82
+ const remainingFraction = modelInfo.quotaInfo.remainingFraction;
55
83
  // Google can publish a nominal reset for an untouched pool; no usage means
56
84
  // there is no active quota window yet.
57
85
  const resetTime =
@@ -98,6 +126,24 @@ export async function fetchProviderQuota(
98
126
  ctx: QuotaFetchContext,
99
127
  ): Promise<void> {
100
128
  if (!account.accessToken) return;
129
+ const accountId = getAccountIdentity(account);
130
+ const credentialGeneration = getCredentialGeneration(
131
+ account,
132
+ DEFAULT_PROVIDER,
133
+ );
134
+ const accountEpoch = dynamicCatalog.captureAccountEpoch(
135
+ accountId,
136
+ credentialGeneration,
137
+ );
138
+ if (accountEpoch === null) return;
139
+ const isCurrentGeneration = (): boolean =>
140
+ accountId === getAccountIdentity(account) &&
141
+ credentialGeneration === getCredentialGeneration(account, DEFAULT_PROVIDER) &&
142
+ dynamicCatalog.isAccountGenerationActive(
143
+ accountId,
144
+ credentialGeneration,
145
+ accountEpoch,
146
+ );
101
147
 
102
148
  try {
103
149
  const response = await fetchWithRetry(QUOTA_API_URL, {
@@ -113,10 +159,12 @@ export async function fetchProviderQuota(
113
159
  timeoutMs: 8000,
114
160
  dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
115
161
  });
162
+ if (!isCurrentGeneration()) return;
116
163
 
117
164
  if (!response.ok) {
118
165
  if (response.status === 401 || response.status === 403) {
119
166
  const errorText = await response.text();
167
+ if (!isCurrentGeneration()) return;
120
168
  ctx.log(
121
169
  `${account.config.email}: quota API returned ${response.status}, flagging account`,
122
170
  );
@@ -130,18 +178,24 @@ export async function fetchProviderQuota(
130
178
  return;
131
179
  }
132
180
 
133
- const data = (await response.json()) as GoogleQuotaResponse;
181
+ const rawData = await response.json();
182
+ if (!isCurrentGeneration()) return;
183
+ const data = parseGoogleQuotaResponse(rawData);
184
+ if (!data) return;
185
+ const oldQuota = account.quota || [];
186
+ const fresh = extractQuotas(data, oldQuota);
187
+ if (fresh.length === 0) return;
134
188
  const newModels = dynamicCatalog.updateFromEndpointResponse(
135
189
  data,
136
- getAccountIdentity(account),
190
+ accountId,
191
+ credentialGeneration,
192
+ accountEpoch,
137
193
  );
138
194
  if (newModels > 0) {
139
195
  ctx.log(
140
196
  `${account.config.email}: discovered ${newModels} Antigravity model(s) from quota response`,
141
197
  );
142
198
  }
143
- const oldQuota = account.quota || [];
144
- const fresh = extractQuotas(data, oldQuota);
145
199
  // Drop the previous Antigravity entries so the new ones fully replace
146
200
  // them; keep entries from OTHER providers (Ollama) so multi-provider
147
201
  // accounts accumulate quotas across credentials without overwriting