tuxevil-rotator 4.4.8 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/README.md +3 -1
- package/package.json +1 -1
- package/plugins/opencode-discovery/index.mjs +50 -21
- package/src/access-probe.ts +1 -1
- package/src/account-store.ts +14 -2
- package/src/audio-transcription.ts +1 -0
- package/src/auto-model-access.ts +22 -0
- package/src/compat/model-specs.ts +7 -0
- package/src/compat/schema-sanitizer.ts +420 -287
- package/src/compat.ts +110 -66
- package/src/config-defaults.ts +7 -0
- package/src/fetch-with-retry.ts +294 -16
- package/src/idempotency.ts +3 -1
- package/src/model-access-api.ts +9 -1
- package/src/model-access.ts +2 -2
- package/src/notification-poller.ts +9 -1
- package/src/provider-catalog-evidence.ts +18 -1
- package/src/providers/adapter.ts +10 -0
- package/src/providers/credential-helpers.ts +34 -0
- package/src/providers/google-antigravity/aicode-eligibility.ts +256 -0
- package/src/providers/google-antigravity/aicode-forward.ts +381 -0
- package/src/providers/google-antigravity/aicode.ts +478 -0
- package/src/providers/google-antigravity/catalog.ts +6 -0
- package/src/providers/google-antigravity/code-assist.ts +53 -41
- package/src/providers/google-antigravity/dynamic-catalog.ts +72 -7
- package/src/providers/google-antigravity/forward.ts +309 -86
- package/src/providers/google-antigravity/index.ts +122 -4
- package/src/providers/google-antigravity/oauth.ts +22 -12
- package/src/providers/google-antigravity/quota.ts +781 -34
- package/src/providers/google-antigravity/translators.ts +55 -46
- package/src/providers/google-antigravity/twin-payload.ts +231 -0
- package/src/providers/ollama/quota.ts +6 -4
- package/src/providers/openai-codex/compat.ts +11 -2
- package/src/providers/openai-codex/quota.ts +2 -1
- package/src/providers/opencode-zen/catalog.ts +159 -13
- package/src/providers/opencode-zen/discovery.ts +50 -0
- package/src/providers/opencode-zen/index.ts +7 -2
- package/src/providers/opencode-zen/quota.ts +14 -1
- package/src/proxy.ts +570 -87
- package/src/quota-pools.ts +76 -1
- package/src/rate-limit-parser.ts +239 -19
- package/src/rotator.ts +848 -297
- package/src/stream-guards.ts +87 -1
- package/src/telemetry.ts +17 -3
- package/src/types.ts +184 -9
- package/src/validators.ts +3 -0
- package/src/web/lib/accounts.ts +2 -0
- package/src/web/lib/attention.ts +19 -0
- package/src/web/lib/models.ts +6 -1
- package/src/web/lib/status.ts +22 -4
- package/src/web/pages/AccountDetail.tsx +49 -2
- package/src/web/pages/Accounts.tsx +38 -3
- package/src/web/pages/ModelAccess.tsx +4 -0
- package/src/web/pages/Models.tsx +2 -1
- package/src/web/pages/Overview.tsx +15 -1
- package/src/web/styles/app.css +73 -3
- package/tools/telemetry-receiver/receiver.js +523 -266
|
@@ -1,18 +1,22 @@
|
|
|
1
1
|
import { observeQuota } from "../../quota-observation.js";
|
|
2
|
-
// Google Antigravity quota polling: fetch per-model quota from
|
|
3
|
-
// fetchAvailableModels
|
|
2
|
+
// Google Antigravity quota polling: fetch per-model quota from
|
|
3
|
+
// fetchAvailableModels and dynamic groups/windows from retrieveUserQuotaSummary.
|
|
4
4
|
|
|
5
5
|
import type {
|
|
6
6
|
AccountRuntime,
|
|
7
7
|
GoogleQuotaResponse,
|
|
8
|
+
GoogleQuotaSummaryBucket,
|
|
9
|
+
GoogleQuotaSummaryGroup,
|
|
10
|
+
GoogleQuotaSummaryResponse,
|
|
8
11
|
ModelQuota,
|
|
12
|
+
QuotaWindow,
|
|
9
13
|
} from "../../types.js";
|
|
10
14
|
import {
|
|
11
15
|
QUOTA_API_URL,
|
|
16
|
+
QUOTA_SUMMARY_API_URL,
|
|
12
17
|
QUOTA_USER_AGENT,
|
|
13
18
|
QUOTA_MODEL_KEYS,
|
|
14
|
-
|
|
15
|
-
REQUEST_GOOG_API_CLIENT,
|
|
19
|
+
resolveQuotaModelKey,
|
|
16
20
|
} from "../../types.js";
|
|
17
21
|
import { fetchWithRetry } from "../../fetch-with-retry.js";
|
|
18
22
|
import {
|
|
@@ -20,7 +24,13 @@ import {
|
|
|
20
24
|
getCredentialGeneration,
|
|
21
25
|
} from "../../account-identity.js";
|
|
22
26
|
import type { QuotaFetchContext } from "../adapter.js";
|
|
23
|
-
import {
|
|
27
|
+
import {
|
|
28
|
+
DEFAULT_PROVIDER,
|
|
29
|
+
formatQuotaResetRemaining,
|
|
30
|
+
getProviderProjectId,
|
|
31
|
+
isOllamaQuotaPoolKey,
|
|
32
|
+
isSafePoolKey,
|
|
33
|
+
} from "../credential-helpers.js";
|
|
24
34
|
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
25
35
|
import { sortQuotaPools } from "../registry.js";
|
|
26
36
|
|
|
@@ -29,12 +39,374 @@ import {
|
|
|
29
39
|
DynamicModelRegistry,
|
|
30
40
|
parseGoogleQuotaResponse,
|
|
31
41
|
} from "./dynamic-catalog.js";
|
|
42
|
+
import { refreshAicodeEligibilityIfNeeded } from "./aicode-eligibility.js";
|
|
43
|
+
import { fetchAicodeQuotaStatus } from "./aicode.js";
|
|
44
|
+
import { shouldShadowAicodeQuotaStatus } from "./aicode-forward.js";
|
|
45
|
+
|
|
46
|
+
const SIX_HOURS_MS = 6 * 60 * 60 * 1000;
|
|
47
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
48
|
+
const RESERVED_POOL_KEYS = new Set(["openai-codex", "opencode-zen", "__default__"]);
|
|
32
49
|
|
|
33
50
|
type GoogleModelInfo = GoogleQuotaResponse["models"][string];
|
|
34
51
|
type GoogleModelInfoWithQuota = GoogleModelInfo & {
|
|
35
52
|
quotaInfo: NonNullable<GoogleModelInfo["quotaInfo"]>;
|
|
36
53
|
};
|
|
37
54
|
|
|
55
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
56
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sanitizeSummaryBucket(raw: unknown): GoogleQuotaSummaryBucket | null {
|
|
60
|
+
if (!isRecord(raw)) return null;
|
|
61
|
+
const fraction = raw.remainingFraction;
|
|
62
|
+
if (
|
|
63
|
+
fraction !== undefined &&
|
|
64
|
+
(typeof fraction !== "number" || !Number.isFinite(fraction) || fraction < 0 || fraction > 1)
|
|
65
|
+
) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const bucket: GoogleQuotaSummaryBucket = {};
|
|
69
|
+
if (typeof raw.bucketId === "string" && raw.bucketId.trim()) bucket.bucketId = raw.bucketId.trim();
|
|
70
|
+
if (typeof raw.displayName === "string" && raw.displayName.trim()) bucket.displayName = raw.displayName.trim();
|
|
71
|
+
if (typeof raw.description === "string" && raw.description.trim()) bucket.description = raw.description.trim();
|
|
72
|
+
const rawWindow =
|
|
73
|
+
typeof raw.window === "string" && raw.window.trim()
|
|
74
|
+
? raw.window.trim()
|
|
75
|
+
: typeof raw.refreshWindowLabel === "string" && raw.refreshWindowLabel.trim()
|
|
76
|
+
? raw.refreshWindowLabel.trim()
|
|
77
|
+
: undefined;
|
|
78
|
+
if (rawWindow) bucket.window = rawWindow;
|
|
79
|
+
if (fraction !== undefined) bucket.remainingFraction = fraction;
|
|
80
|
+
if (typeof raw.remainingAmount === "string" || typeof raw.remainingAmount === "number") {
|
|
81
|
+
bucket.remainingAmount = raw.remainingAmount;
|
|
82
|
+
}
|
|
83
|
+
if (typeof raw.disabled === "boolean") bucket.disabled = raw.disabled;
|
|
84
|
+
if (typeof raw.resetTime === "string" && raw.resetTime.trim()) bucket.resetTime = raw.resetTime.trim();
|
|
85
|
+
if (!bucket.bucketId && !bucket.window && !bucket.displayName && fraction === undefined && !bucket.resetTime) {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
return bucket;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function parseGoogleQuotaSummaryResponse(value: unknown): GoogleQuotaSummaryResponse | null {
|
|
92
|
+
if (!isRecord(value)) return null;
|
|
93
|
+
const parsed: GoogleQuotaSummaryResponse = {};
|
|
94
|
+
if (typeof value.description === "string" && value.description.trim()) {
|
|
95
|
+
parsed.description = value.description.trim();
|
|
96
|
+
}
|
|
97
|
+
if (Array.isArray(value.groups)) {
|
|
98
|
+
const groups: GoogleQuotaSummaryGroup[] = [];
|
|
99
|
+
for (const rawGroup of value.groups) {
|
|
100
|
+
if (!isRecord(rawGroup) || !Array.isArray(rawGroup.buckets)) continue;
|
|
101
|
+
const buckets = rawGroup.buckets
|
|
102
|
+
.map(sanitizeSummaryBucket)
|
|
103
|
+
.filter((bucket): bucket is GoogleQuotaSummaryBucket => bucket !== null);
|
|
104
|
+
if (buckets.length === 0) continue;
|
|
105
|
+
const group: GoogleQuotaSummaryGroup = { buckets };
|
|
106
|
+
if (typeof rawGroup.displayName === "string" && rawGroup.displayName.trim()) {
|
|
107
|
+
group.displayName = rawGroup.displayName.trim();
|
|
108
|
+
}
|
|
109
|
+
if (typeof rawGroup.description === "string" && rawGroup.description.trim()) {
|
|
110
|
+
group.description = rawGroup.description.trim();
|
|
111
|
+
}
|
|
112
|
+
groups.push(group);
|
|
113
|
+
}
|
|
114
|
+
if (groups.length > 0) parsed.groups = groups;
|
|
115
|
+
}
|
|
116
|
+
if (Array.isArray(value.buckets)) {
|
|
117
|
+
const buckets = value.buckets
|
|
118
|
+
.map(sanitizeSummaryBucket)
|
|
119
|
+
.filter((bucket): bucket is GoogleQuotaSummaryBucket => bucket !== null);
|
|
120
|
+
if (buckets.length > 0) parsed.buckets = buckets;
|
|
121
|
+
}
|
|
122
|
+
if (!parsed.groups?.length && !parsed.buckets?.length) return null;
|
|
123
|
+
return parsed;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function slugifyPoolKey(raw: string): string {
|
|
127
|
+
return raw
|
|
128
|
+
.toLowerCase()
|
|
129
|
+
.replace(/[^a-z0-9._:-]+/g, "-")
|
|
130
|
+
.replace(/^-+|-+$/g, "")
|
|
131
|
+
.slice(0, 64);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function stripWindowSuffix(bucketId: string): string {
|
|
135
|
+
return bucketId
|
|
136
|
+
.toLowerCase()
|
|
137
|
+
.replace(/-(?:wtu-)?(?:weekly|daily|monthly|hourly|\d+[smhdw])$/i, "");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function resolveSummaryGroupIdentity(group: GoogleQuotaSummaryGroup): {
|
|
141
|
+
key: string;
|
|
142
|
+
displayName: string;
|
|
143
|
+
} {
|
|
144
|
+
const displayLower = (group.displayName ?? "").trim().toLowerCase();
|
|
145
|
+
const bucketIds = (group.buckets ?? []).map((b) => (b.bucketId ?? "").toLowerCase()).filter(Boolean);
|
|
146
|
+
const isCoreGeminiBucket =
|
|
147
|
+
bucketIds.length > 0 &&
|
|
148
|
+
bucketIds.every((id) => /^gemini-(?:weekly|daily|monthly|\d+[smhdw])$/.test(id));
|
|
149
|
+
const isCoreClaudeBucket =
|
|
150
|
+
bucketIds.length > 0 &&
|
|
151
|
+
bucketIds.every((id) => /^(?:3p|claude)-(?:wtu-)?(?:weekly|daily|monthly|\d+[smhdw])$/.test(id));
|
|
152
|
+
|
|
153
|
+
if (isCoreGeminiBucket || displayLower === "gemini models" || displayLower === "gemini") {
|
|
154
|
+
return { key: "gemini", displayName: group.displayName?.trim() || "Gemini" };
|
|
155
|
+
}
|
|
156
|
+
if (
|
|
157
|
+
isCoreClaudeBucket ||
|
|
158
|
+
displayLower === "claude and gpt models" ||
|
|
159
|
+
displayLower === "claude" ||
|
|
160
|
+
(displayLower.includes("claude") && !/\d/.test(displayLower))
|
|
161
|
+
) {
|
|
162
|
+
return { key: "claude", displayName: group.displayName?.trim() || "Claude" };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
let slug = group.displayName ? slugifyPoolKey(group.displayName) : "";
|
|
166
|
+
if (!slug && bucketIds[0]) {
|
|
167
|
+
slug = slugifyPoolKey(stripWindowSuffix(bucketIds[0]));
|
|
168
|
+
}
|
|
169
|
+
if (!slug) slug = "google-pool";
|
|
170
|
+
if (isOllamaQuotaPoolKey(slug) || RESERVED_POOL_KEYS.has(slug) || slug === "gemini" || slug === "claude") {
|
|
171
|
+
slug = slugifyPoolKey(`google-${slug}`);
|
|
172
|
+
}
|
|
173
|
+
if (!isSafePoolKey(slug)) slug = "google-pool";
|
|
174
|
+
return {
|
|
175
|
+
key: slug,
|
|
176
|
+
displayName: group.displayName?.trim() || group.buckets?.[0]?.displayName?.trim() || slug,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function inferGroupsFromTopLevelBuckets(buckets: GoogleQuotaSummaryBucket[]): GoogleQuotaSummaryGroup[] {
|
|
181
|
+
const byPrefix = new Map<string, GoogleQuotaSummaryBucket[]>();
|
|
182
|
+
for (const bucket of buckets) {
|
|
183
|
+
const prefix = bucket.bucketId ? stripWindowSuffix(bucket.bucketId) : "google";
|
|
184
|
+
const list = byPrefix.get(prefix) ?? [];
|
|
185
|
+
list.push(bucket);
|
|
186
|
+
byPrefix.set(prefix, list);
|
|
187
|
+
}
|
|
188
|
+
return Array.from(byPrefix.entries()).map(([prefix, groupBuckets]) => ({
|
|
189
|
+
displayName:
|
|
190
|
+
prefix === "gemini"
|
|
191
|
+
? "Gemini Models"
|
|
192
|
+
: prefix === "3p" || prefix === "claude"
|
|
193
|
+
? "Claude and GPT models"
|
|
194
|
+
: groupBuckets[0]?.displayName || prefix,
|
|
195
|
+
buckets: groupBuckets,
|
|
196
|
+
}));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function parseWindowDurationMs(
|
|
200
|
+
windowKey: string,
|
|
201
|
+
resetTime: string | null,
|
|
202
|
+
now: number,
|
|
203
|
+
): number | undefined {
|
|
204
|
+
const lower = windowKey.trim().toLowerCase();
|
|
205
|
+
if (lower === "5h") return 5 * 3600_000;
|
|
206
|
+
if (lower === "daily" || lower === "1d") return DAY_MS;
|
|
207
|
+
if (lower === "weekly" || lower === "7d") return 7 * DAY_MS;
|
|
208
|
+
if (lower === "monthly" || lower === "30d") return 30 * DAY_MS;
|
|
209
|
+
const match = lower.match(/^(\d+)\s*([smhdw])$/);
|
|
210
|
+
if (match) {
|
|
211
|
+
const value = Number(match[1]);
|
|
212
|
+
const unitMs: Record<string, number> = {
|
|
213
|
+
s: 1000,
|
|
214
|
+
m: 60_000,
|
|
215
|
+
h: 3600_000,
|
|
216
|
+
d: DAY_MS,
|
|
217
|
+
w: 7 * DAY_MS,
|
|
218
|
+
};
|
|
219
|
+
return value * (unitMs[match[2]] ?? 0);
|
|
220
|
+
}
|
|
221
|
+
if (resetTime) {
|
|
222
|
+
const resetMs = Date.parse(resetTime);
|
|
223
|
+
if (Number.isFinite(resetMs) && resetMs > now) return resetMs - now;
|
|
224
|
+
}
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function resolveBucketWindowKey(bucket: GoogleQuotaSummaryBucket, now: number): string {
|
|
229
|
+
const explicit = bucket.window?.trim().toLowerCase();
|
|
230
|
+
if (explicit) return explicit;
|
|
231
|
+
const fromId = bucket.bucketId?.trim().toLowerCase().match(/(?:^|-)(weekly|daily|monthly|\d+[smhdw])$/)?.[1];
|
|
232
|
+
if (fromId) return fromId;
|
|
233
|
+
if (bucket.resetTime) {
|
|
234
|
+
const resetMs = Date.parse(bucket.resetTime);
|
|
235
|
+
if (Number.isFinite(resetMs) && resetMs > now) {
|
|
236
|
+
return resetMs - now < SIX_HOURS_MS ? "5h" : "weekly";
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return "weekly";
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function formatWindowLabel(windowKey: string, bucketDisplayName?: string): string {
|
|
243
|
+
const lower = windowKey.trim().toLowerCase();
|
|
244
|
+
if (lower === "daily") return "Daily limit";
|
|
245
|
+
if (lower === "weekly" || lower === "7d") return "Weekly limit";
|
|
246
|
+
if (lower === "monthly") return "Monthly limit";
|
|
247
|
+
if (/^\d+[smhdw]$/.test(lower)) return `${lower} limit`;
|
|
248
|
+
return bucketDisplayName?.trim() || windowKey;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function classifyWindowTimerType(
|
|
252
|
+
windowKey: string,
|
|
253
|
+
durationMs: number | undefined,
|
|
254
|
+
active: boolean,
|
|
255
|
+
): ModelQuota["timerType"] {
|
|
256
|
+
if (!active) return "fresh";
|
|
257
|
+
const lower = windowKey.trim().toLowerCase();
|
|
258
|
+
if (lower === "5h") return "5h";
|
|
259
|
+
if (lower === "weekly" || lower === "7d") return "7d";
|
|
260
|
+
if (lower === "monthly") return "monthly";
|
|
261
|
+
if (lower === "daily" || /^\d+[smhdw]$/.test(lower)) {
|
|
262
|
+
if (durationMs !== undefined && durationMs <= SIX_HOURS_MS && lower === "5h") return "5h";
|
|
263
|
+
return lower;
|
|
264
|
+
}
|
|
265
|
+
if (durationMs !== undefined) {
|
|
266
|
+
return durationMs < SIX_HOURS_MS ? "5h" : "7d";
|
|
267
|
+
}
|
|
268
|
+
return "7d";
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function normalizeModelMatchText(text: string): string {
|
|
272
|
+
return text
|
|
273
|
+
.toLowerCase()
|
|
274
|
+
.replace(/\([^)]*\)/g, " ")
|
|
275
|
+
.replace(/(\d)\.(\d)/g, "$1-$2")
|
|
276
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
277
|
+
.replace(/^-+|-+$/g, "");
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function extractGroupModelPhrases(group: GoogleQuotaSummaryGroup, poolKey: string): string[] {
|
|
281
|
+
const phrases: string[] = [];
|
|
282
|
+
if (group.description) {
|
|
283
|
+
const descMatch = group.description.match(/models\s+within\s+this\s+group\s*:\s*([^\n]+)/i);
|
|
284
|
+
if (descMatch) {
|
|
285
|
+
const listPart = descMatch[1].replace(/\.$/, "");
|
|
286
|
+
for (const item of listPart.split(",")) {
|
|
287
|
+
const norm = normalizeModelMatchText(item);
|
|
288
|
+
if (norm) phrases.push(norm);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (group.displayName && poolKey !== "gemini" && poolKey !== "claude") {
|
|
293
|
+
const normDisplay = normalizeModelMatchText(group.displayName);
|
|
294
|
+
if (normDisplay) phrases.push(normDisplay);
|
|
295
|
+
}
|
|
296
|
+
if (poolKey !== "gemini" && poolKey !== "claude") {
|
|
297
|
+
const normKey = normalizeModelMatchText(poolKey);
|
|
298
|
+
if (normKey) phrases.push(normKey);
|
|
299
|
+
}
|
|
300
|
+
return Array.from(new Set(phrases));
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function modelMatchesPhrase(modelId: string, modelDisplayName: string | undefined, phrase: string): boolean {
|
|
304
|
+
const normId = normalizeModelMatchText(modelId);
|
|
305
|
+
if (normId === phrase || normId.startsWith(`${phrase}-`) || normId.includes(phrase)) {
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
if (modelDisplayName) {
|
|
309
|
+
const normDisp = normalizeModelMatchText(modelDisplayName);
|
|
310
|
+
if (normDisp === phrase || normDisp.startsWith(`${phrase}-`) || normDisp.includes(phrase)) {
|
|
311
|
+
return true;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return false;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function buildSummaryModelPoolMap(
|
|
318
|
+
data: GoogleQuotaResponse,
|
|
319
|
+
summary: GoogleQuotaSummaryResponse | null | undefined,
|
|
320
|
+
): Map<string, string> {
|
|
321
|
+
const result = new Map<string, string>();
|
|
322
|
+
if (!summary) return result;
|
|
323
|
+
const groups = summary.groups?.length
|
|
324
|
+
? summary.groups
|
|
325
|
+
: summary.buckets?.length
|
|
326
|
+
? inferGroupsFromTopLevelBuckets(summary.buckets)
|
|
327
|
+
: [];
|
|
328
|
+
if (groups.length === 0) return result;
|
|
329
|
+
|
|
330
|
+
const resolvedGroups = groups.map((group) => {
|
|
331
|
+
const identity = resolveSummaryGroupIdentity(group);
|
|
332
|
+
return {
|
|
333
|
+
group,
|
|
334
|
+
key: identity.key,
|
|
335
|
+
phrases: extractGroupModelPhrases(group, identity.key),
|
|
336
|
+
};
|
|
337
|
+
});
|
|
338
|
+
const groupKeys = new Set(resolvedGroups.map((entry) => entry.key));
|
|
339
|
+
|
|
340
|
+
// Rank phrase matchers longest-first so specific pools (e.g. "gemini-4-argon") win
|
|
341
|
+
// over generic family substrings.
|
|
342
|
+
const phraseMatchers = resolvedGroups
|
|
343
|
+
.flatMap((entry) => entry.phrases.map((phrase) => ({ phrase, key: entry.key })))
|
|
344
|
+
.sort((a, b) => b.phrase.length - a.phrase.length);
|
|
345
|
+
|
|
346
|
+
const now = Date.now();
|
|
347
|
+
for (const [rawId, info] of Object.entries(data.models)) {
|
|
348
|
+
const lowerId = rawId.trim().toLowerCase();
|
|
349
|
+
if (!lowerId) continue;
|
|
350
|
+
|
|
351
|
+
let matchedKey: string | undefined;
|
|
352
|
+
for (const matcher of phraseMatchers) {
|
|
353
|
+
if (modelMatchesPhrase(lowerId, info.displayName, matcher.phrase)) {
|
|
354
|
+
matchedKey = matcher.key;
|
|
355
|
+
break;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// Fallback: correlate active/exhausted model quota signature against summary buckets.
|
|
360
|
+
if (!matchedKey && info.quotaInfo) {
|
|
361
|
+
const mFrac = info.quotaInfo.remainingFraction;
|
|
362
|
+
const mResetMs = info.quotaInfo.resetTime ? Date.parse(info.quotaInfo.resetTime) : NaN;
|
|
363
|
+
const candidateKeys = new Set<string>();
|
|
364
|
+
for (const entry of resolvedGroups) {
|
|
365
|
+
for (const bucket of entry.group.buckets ?? []) {
|
|
366
|
+
const bResetMs = bucket.resetTime ? Date.parse(bucket.resetTime) : NaN;
|
|
367
|
+
const resetMatch =
|
|
368
|
+
Number.isFinite(mResetMs) &&
|
|
369
|
+
Number.isFinite(bResetMs) &&
|
|
370
|
+
Math.abs(mResetMs - bResetMs) <= 120_000;
|
|
371
|
+
const fracMatch =
|
|
372
|
+
typeof mFrac === "number" &&
|
|
373
|
+
typeof bucket.remainingFraction === "number" &&
|
|
374
|
+
(mFrac < 1 || bucket.remainingFraction < 1) &&
|
|
375
|
+
Math.abs(mFrac - bucket.remainingFraction) <= 0.02;
|
|
376
|
+
if (resetMatch && (typeof mFrac !== "number" || typeof bucket.remainingFraction !== "number" || Math.abs(mFrac - bucket.remainingFraction) <= 0.05)) {
|
|
377
|
+
candidateKeys.add(entry.key);
|
|
378
|
+
} else if (fracMatch && !Number.isFinite(bResetMs)) {
|
|
379
|
+
candidateKeys.add(entry.key);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (candidateKeys.size === 1) {
|
|
384
|
+
matchedKey = Array.from(candidateKeys)[0];
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (!matchedKey) {
|
|
389
|
+
const inferred = DynamicModelRegistry.inferFamilyAndPool(lowerId).quotaPool;
|
|
390
|
+
if (groupKeys.has(inferred)) {
|
|
391
|
+
matchedKey = inferred;
|
|
392
|
+
} else {
|
|
393
|
+
// Match custom group pool slug prefix directly against model ID when possible.
|
|
394
|
+
const customMatch = resolvedGroups
|
|
395
|
+
.filter((entry) => entry.key !== "gemini" && entry.key !== "claude")
|
|
396
|
+
.sort((a, b) => b.key.length - a.key.length)
|
|
397
|
+
.find((entry) => lowerId.startsWith(entry.key) && now >= 0);
|
|
398
|
+
if (customMatch) matchedKey = customMatch.key;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (matchedKey) {
|
|
403
|
+
result.set(lowerId, matchedKey);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
return result;
|
|
408
|
+
}
|
|
409
|
+
|
|
38
410
|
function hasUsableQuotaInfo(
|
|
39
411
|
info: GoogleModelInfo | undefined,
|
|
40
412
|
): info is GoogleModelInfoWithQuota {
|
|
@@ -69,13 +441,30 @@ function applyActiveCooldown(
|
|
|
69
441
|
const advertisedReset = quota.resetTime
|
|
70
442
|
? new Date(quota.resetTime).getTime()
|
|
71
443
|
: 0;
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
444
|
+
// Only adopt the upstream reset time if the upstream already reported 0%
|
|
445
|
+
// quota; a local 429 cooldown on an otherwise healthy pool expires at
|
|
446
|
+
// cooldownUntil, not at the pool's 5h/weekly refresh boundary.
|
|
447
|
+
const resetAt =
|
|
448
|
+
quota.percentRemaining === 0 && Number.isFinite(advertisedReset) && advertisedReset > now
|
|
449
|
+
? Math.max(cooldownUntil, advertisedReset)
|
|
450
|
+
: cooldownUntil;
|
|
451
|
+
const resetIso = new Date(resetAt).toISOString();
|
|
76
452
|
quota.percentRemaining = 0;
|
|
77
|
-
quota.resetTime =
|
|
78
|
-
quota.timerType = resetAt - now <
|
|
453
|
+
quota.resetTime = resetIso;
|
|
454
|
+
quota.timerType = resetAt - now < SIX_HOURS_MS ? "5h" : "7d";
|
|
455
|
+
if (quota.windows?.length) {
|
|
456
|
+
// Keep windows consistent when local 429 cooldown marks the pool empty.
|
|
457
|
+
const matching = quota.windows.find(
|
|
458
|
+
(w) =>
|
|
459
|
+
(quota.timerType === "5h" && w.window === "5h") ||
|
|
460
|
+
(quota.timerType === "7d" && (w.window === "weekly" || w.window === "7d")),
|
|
461
|
+
) ?? quota.windows[0];
|
|
462
|
+
if (matching) {
|
|
463
|
+
matching.percentRemaining = 0;
|
|
464
|
+
matching.resetTime = resetIso;
|
|
465
|
+
matching.active = true;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
79
468
|
}
|
|
80
469
|
|
|
81
470
|
function getActiveCooldownForPool(
|
|
@@ -83,10 +472,11 @@ function getActiveCooldownForPool(
|
|
|
83
472
|
poolKey: string,
|
|
84
473
|
): number | undefined {
|
|
85
474
|
let cooldownUntil = account.cooldownsByModel[poolKey] ?? 0;
|
|
475
|
+
const accountId = getAccountIdentity(account);
|
|
86
476
|
for (const [modelKey, deadline] of Object.entries(account.cooldownsByModel)) {
|
|
87
477
|
if (
|
|
88
478
|
modelKey !== poolKey &&
|
|
89
|
-
dynamicCatalog.
|
|
479
|
+
dynamicCatalog.resolveQuotaPoolForAccount(accountId, modelKey) === poolKey
|
|
90
480
|
) {
|
|
91
481
|
cooldownUntil = Math.max(cooldownUntil, deadline);
|
|
92
482
|
}
|
|
@@ -94,18 +484,244 @@ function getActiveCooldownForPool(
|
|
|
94
484
|
return cooldownUntil || undefined;
|
|
95
485
|
}
|
|
96
486
|
|
|
487
|
+
function buildWindowsFromSummaryGroup(
|
|
488
|
+
group: GoogleQuotaSummaryGroup,
|
|
489
|
+
matchedModels: GoogleModelInfoWithQuota[],
|
|
490
|
+
now: number,
|
|
491
|
+
): {
|
|
492
|
+
windows: QuotaWindow[];
|
|
493
|
+
percentageSource: "derived" | "unknown";
|
|
494
|
+
resetSource: "reported" | "unknown";
|
|
495
|
+
} {
|
|
496
|
+
let hasUnknownFraction = false;
|
|
497
|
+
let hasReportedReset = false;
|
|
498
|
+
|
|
499
|
+
const rawWindows = (group.buckets ?? []).map((bucket) => {
|
|
500
|
+
const windowKey = resolveBucketWindowKey(bucket, now);
|
|
501
|
+
const hasFraction = typeof bucket.remainingFraction === "number";
|
|
502
|
+
const fraction = hasFraction ? bucket.remainingFraction! : bucket.resetTime ? 0 : 1;
|
|
503
|
+
const resetTime: string | null = fraction >= 1 ? null : (bucket.resetTime ?? null);
|
|
504
|
+
if (!hasFraction && bucket.resetTime) hasUnknownFraction = true;
|
|
505
|
+
if (resetTime) hasReportedReset = true;
|
|
506
|
+
const durationMs = parseWindowDurationMs(windowKey, bucket.resetTime ?? null, now);
|
|
507
|
+
return {
|
|
508
|
+
id: bucket.bucketId || windowKey,
|
|
509
|
+
window: windowKey,
|
|
510
|
+
label: formatWindowLabel(windowKey, bucket.displayName),
|
|
511
|
+
hasFraction,
|
|
512
|
+
fraction,
|
|
513
|
+
resetTime,
|
|
514
|
+
durationMs,
|
|
515
|
+
description: bucket.description,
|
|
516
|
+
disabled: bucket.disabled,
|
|
517
|
+
};
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
// Only fill summary buckets that omitted remainingFraction using
|
|
521
|
+
// fetchAvailableModels. When retrieveUserQuotaSummary explicitly reports
|
|
522
|
+
// remainingFraction (e.g. 1.0 after a weekly reset), treat the summary as
|
|
523
|
+
// authoritative instead of letting stale legacy quotaInfo override it.
|
|
524
|
+
if (matchedModels.length > 0 && rawWindows.some((w) => !w.hasFraction)) {
|
|
525
|
+
const modelMin = [...matchedModels].sort(
|
|
526
|
+
(a, b) =>
|
|
527
|
+
getRemainingFraction(a) - getRemainingFraction(b) ||
|
|
528
|
+
Number(Boolean(b.quotaInfo.resetTime)) - Number(Boolean(a.quotaInfo.resetTime)),
|
|
529
|
+
)[0];
|
|
530
|
+
if (modelMin) {
|
|
531
|
+
const mFraction = getRemainingFraction(modelMin);
|
|
532
|
+
const mResetTime = mFraction >= 1 ? null : (modelMin.quotaInfo.resetTime ?? null);
|
|
533
|
+
const mResetMs = mResetTime ? Date.parse(mResetTime) : NaN;
|
|
534
|
+
const mClass = Number.isFinite(mResetMs) && mResetMs > now
|
|
535
|
+
? (mResetMs - now < SIX_HOURS_MS ? "5h" : "weekly")
|
|
536
|
+
: undefined;
|
|
537
|
+
|
|
538
|
+
const missingWindows = rawWindows.filter((w) => !w.hasFraction);
|
|
539
|
+
const targetWin =
|
|
540
|
+
(mResetTime
|
|
541
|
+
? missingWindows.find(
|
|
542
|
+
(w) =>
|
|
543
|
+
w.resetTime &&
|
|
544
|
+
Math.abs(Date.parse(w.resetTime) - mResetMs) <= 120_000,
|
|
545
|
+
)
|
|
546
|
+
: undefined) ??
|
|
547
|
+
(mClass
|
|
548
|
+
? missingWindows.find(
|
|
549
|
+
(w) =>
|
|
550
|
+
w.window === mClass ||
|
|
551
|
+
(mClass === "weekly" && (w.window === "weekly" || w.window === "7d")),
|
|
552
|
+
)
|
|
553
|
+
: undefined) ??
|
|
554
|
+
missingWindows[missingWindows.length - 1];
|
|
555
|
+
|
|
556
|
+
if (targetWin && typeof modelMin.quotaInfo.remainingFraction === "number") {
|
|
557
|
+
targetWin.fraction = mFraction;
|
|
558
|
+
targetWin.hasFraction = true;
|
|
559
|
+
if (!targetWin.resetTime && mResetTime) {
|
|
560
|
+
targetWin.resetTime = mResetTime;
|
|
561
|
+
hasReportedReset = true;
|
|
562
|
+
}
|
|
563
|
+
hasUnknownFraction = rawWindows.some((w) => !w.hasFraction && Boolean(w.resetTime));
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
const windows: QuotaWindow[] = rawWindows
|
|
569
|
+
.sort((a, b) => (a.durationMs ?? Infinity) - (b.durationMs ?? Infinity))
|
|
570
|
+
.map((entry) => {
|
|
571
|
+
const percentRemaining = Math.round(entry.fraction * 100);
|
|
572
|
+
const active = (percentRemaining < 100 || entry.fraction < 1) && Boolean(entry.resetTime);
|
|
573
|
+
return {
|
|
574
|
+
id: entry.id,
|
|
575
|
+
window: entry.window,
|
|
576
|
+
label: entry.label,
|
|
577
|
+
percentRemaining,
|
|
578
|
+
resetTime: active || percentRemaining === 0 ? entry.resetTime : null,
|
|
579
|
+
...(entry.durationMs !== undefined ? { durationMs: entry.durationMs } : {}),
|
|
580
|
+
active: Boolean(active || (percentRemaining === 0 && entry.resetTime)),
|
|
581
|
+
...(entry.description ? { description: entry.description } : {}),
|
|
582
|
+
...(entry.disabled !== undefined ? { disabled: entry.disabled } : {}),
|
|
583
|
+
};
|
|
584
|
+
});
|
|
585
|
+
|
|
586
|
+
return {
|
|
587
|
+
windows,
|
|
588
|
+
percentageSource: hasUnknownFraction ? "unknown" : "derived",
|
|
589
|
+
resetSource: hasReportedReset ? "reported" : "unknown",
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function summarizeGroupQuota(
|
|
594
|
+
poolKey: string,
|
|
595
|
+
displayName: string,
|
|
596
|
+
description: string | undefined,
|
|
597
|
+
windows: QuotaWindow[],
|
|
598
|
+
percentageSource: "derived" | "unknown",
|
|
599
|
+
resetSource: "reported" | "unknown",
|
|
600
|
+
now: number,
|
|
601
|
+
oldQ?: ModelQuota,
|
|
602
|
+
): ModelQuota {
|
|
603
|
+
const usable = windows.filter((w) => !w.disabled);
|
|
604
|
+
const poolWindows = usable.length > 0 ? usable : windows;
|
|
605
|
+
const percentRemaining = Math.min(...poolWindows.map((w) => w.percentRemaining));
|
|
606
|
+
|
|
607
|
+
const exhaustedWithReset = poolWindows
|
|
608
|
+
.filter((w) => w.percentRemaining === 0 && w.resetTime)
|
|
609
|
+
.sort((a, b) => Date.parse(b.resetTime!) - Date.parse(a.resetTime!));
|
|
610
|
+
const activeWithReset = poolWindows
|
|
611
|
+
.filter((w) => w.active && w.resetTime)
|
|
612
|
+
.sort((a, b) => (a.durationMs ?? Infinity) - (b.durationMs ?? Infinity));
|
|
613
|
+
|
|
614
|
+
const primary = exhaustedWithReset[0] ?? activeWithReset[0];
|
|
615
|
+
let timerType: ModelQuota["timerType"] = "fresh";
|
|
616
|
+
const resetTime = primary?.resetTime ?? null;
|
|
617
|
+
if (primary && resetTime) {
|
|
618
|
+
if (
|
|
619
|
+
!primary.window &&
|
|
620
|
+
oldQ &&
|
|
621
|
+
oldQ.resetTime === resetTime &&
|
|
622
|
+
oldQ.timerType !== "fresh"
|
|
623
|
+
) {
|
|
624
|
+
timerType = oldQ.timerType;
|
|
625
|
+
} else {
|
|
626
|
+
timerType = classifyWindowTimerType(primary.window, primary.durationMs, true);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
return {
|
|
631
|
+
modelKey: poolKey,
|
|
632
|
+
displayName,
|
|
633
|
+
...(description ? { groupDescription: description } : {}),
|
|
634
|
+
windows,
|
|
635
|
+
observation: observeQuota(
|
|
636
|
+
{ percentRemaining, resetTime },
|
|
637
|
+
now,
|
|
638
|
+
percentageSource,
|
|
639
|
+
resetTime ? resetSource : "unknown",
|
|
640
|
+
),
|
|
641
|
+
percentRemaining,
|
|
642
|
+
resetTime,
|
|
643
|
+
timerType,
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
|
|
97
647
|
/**
|
|
98
|
-
* Extract per-
|
|
99
|
-
*
|
|
648
|
+
* Extract per-pool quotas from Google quota responses.
|
|
649
|
+
* When `summary` (from `retrieveUserQuotaSummary`) is present, its dynamic groups
|
|
650
|
+
* and time windows are authoritative (reconciled against `fetchAvailableModels`).
|
|
651
|
+
* Without `summary`, falls back to model-level `fetchAvailableModels` extraction.
|
|
100
652
|
*/
|
|
101
653
|
export function extractQuotas(
|
|
102
654
|
data: GoogleQuotaResponse,
|
|
103
655
|
oldQuota: ModelQuota[],
|
|
656
|
+
summary?: GoogleQuotaSummaryResponse | null,
|
|
657
|
+
now: number = Date.now(),
|
|
104
658
|
): ModelQuota[] {
|
|
659
|
+
const summaryGroups = summary?.groups?.length
|
|
660
|
+
? summary.groups
|
|
661
|
+
: summary?.buckets?.length
|
|
662
|
+
? inferGroupsFromTopLevelBuckets(summary.buckets)
|
|
663
|
+
: null;
|
|
664
|
+
|
|
665
|
+
if (summaryGroups && summaryGroups.length > 0) {
|
|
666
|
+
const modelPoolMap = buildSummaryModelPoolMap(data, { groups: summaryGroups });
|
|
667
|
+
const modelsByPool = new Map<string, GoogleModelInfoWithQuota[]>();
|
|
668
|
+
for (const [modelId, info] of Object.entries(data.models)) {
|
|
669
|
+
if (!hasUsableQuotaInfo(info)) continue;
|
|
670
|
+
const poolKey =
|
|
671
|
+
modelPoolMap.get(modelId.trim().toLowerCase()) ??
|
|
672
|
+
DynamicModelRegistry.inferFamilyAndPool(modelId).quotaPool;
|
|
673
|
+
const list = modelsByPool.get(poolKey) ?? [];
|
|
674
|
+
list.push(info);
|
|
675
|
+
modelsByPool.set(poolKey, list);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const quotas: ModelQuota[] = [];
|
|
679
|
+
const seenKeys = new Set<string>();
|
|
680
|
+
for (const group of summaryGroups) {
|
|
681
|
+
const identity = resolveSummaryGroupIdentity(group);
|
|
682
|
+
if (seenKeys.has(identity.key)) continue;
|
|
683
|
+
seenKeys.add(identity.key);
|
|
684
|
+
const matched = modelsByPool.get(identity.key) ?? [];
|
|
685
|
+
const built = buildWindowsFromSummaryGroup(group, matched, now);
|
|
686
|
+
if (built.windows.length === 0) continue;
|
|
687
|
+
const oldQ = oldQuota.find((q) => q.modelKey === identity.key);
|
|
688
|
+
quotas.push(
|
|
689
|
+
summarizeGroupQuota(
|
|
690
|
+
identity.key,
|
|
691
|
+
identity.displayName,
|
|
692
|
+
group.description,
|
|
693
|
+
built.windows,
|
|
694
|
+
built.percentageSource,
|
|
695
|
+
built.resetSource,
|
|
696
|
+
now,
|
|
697
|
+
oldQ,
|
|
698
|
+
),
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
return quotas;
|
|
702
|
+
}
|
|
703
|
+
|
|
105
704
|
const quotas: ModelQuota[] = [];
|
|
106
|
-
const
|
|
705
|
+
const resolveFallbackPoolKey = (modelKey: string): string =>
|
|
706
|
+
dynamicCatalog.resolveQuotaPool(modelKey) ??
|
|
707
|
+
DynamicModelRegistry.inferFamilyAndPool(modelKey).quotaPool;
|
|
107
708
|
|
|
709
|
+
const fallbackPoolMeta = new Map<string, { key: string; display: string }>();
|
|
108
710
|
for (const [, config] of Object.entries(QUOTA_MODEL_KEYS)) {
|
|
711
|
+
fallbackPoolMeta.set(config.key, config);
|
|
712
|
+
}
|
|
713
|
+
for (const modelKey of Object.keys(data.models)) {
|
|
714
|
+
const resolvedKey = resolveFallbackPoolKey(modelKey);
|
|
715
|
+
if (!fallbackPoolMeta.has(resolvedKey) && hasUsableQuotaInfo(data.models[modelKey])) {
|
|
716
|
+
const oldDisplay = oldQuota.find((q) => q.modelKey === resolvedKey)?.displayName;
|
|
717
|
+
fallbackPoolMeta.set(resolvedKey, {
|
|
718
|
+
key: resolvedKey,
|
|
719
|
+
display: oldDisplay ?? resolvedKey,
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
for (const [, config] of fallbackPoolMeta) {
|
|
109
725
|
const candidates: GoogleModelInfoWithQuota[] = [];
|
|
110
726
|
const sharedPoolInfo = data.models[config.key];
|
|
111
727
|
if (hasUsableQuotaInfo(sharedPoolInfo)) {
|
|
@@ -115,7 +731,7 @@ export function extractQuotas(
|
|
|
115
731
|
for (const [modelKey, info] of Object.entries(data.models)) {
|
|
116
732
|
if (
|
|
117
733
|
modelKey !== config.key &&
|
|
118
|
-
|
|
734
|
+
resolveFallbackPoolKey(modelKey) === config.key &&
|
|
119
735
|
hasUsableQuotaInfo(info)
|
|
120
736
|
) {
|
|
121
737
|
candidates.push(info);
|
|
@@ -150,7 +766,7 @@ export function extractQuotas(
|
|
|
150
766
|
const resetMs = new Date(resetTime).getTime();
|
|
151
767
|
if (resetMs > now) {
|
|
152
768
|
const durationMs = resetMs - now;
|
|
153
|
-
timerType = durationMs <
|
|
769
|
+
timerType = durationMs < SIX_HOURS_MS ? "5h" : "7d";
|
|
154
770
|
}
|
|
155
771
|
}
|
|
156
772
|
}
|
|
@@ -197,21 +813,25 @@ export async function fetchProviderQuota(
|
|
|
197
813
|
credentialGeneration,
|
|
198
814
|
accountEpoch,
|
|
199
815
|
);
|
|
816
|
+
const cooldownSnapshotAtStart: Record<string, number> = {
|
|
817
|
+
...account.cooldownsByModel,
|
|
818
|
+
};
|
|
200
819
|
|
|
820
|
+
const projectId = getProviderProjectId(account.config, DEFAULT_PROVIDER);
|
|
821
|
+
const quotaHeaders: Record<string, string> = {
|
|
822
|
+
"Content-Type": "application/json",
|
|
823
|
+
Authorization: `Bearer ${account.accessToken}`,
|
|
824
|
+
"User-Agent": QUOTA_USER_AGENT,
|
|
825
|
+
};
|
|
201
826
|
try {
|
|
202
827
|
const response = await fetchWithRetry(QUOTA_API_URL, {
|
|
203
828
|
method: "POST",
|
|
204
|
-
headers:
|
|
205
|
-
"Content-Type": "application/json",
|
|
206
|
-
Authorization: `Bearer ${account.accessToken}`,
|
|
207
|
-
"User-Agent": QUOTA_USER_AGENT,
|
|
208
|
-
"X-Goog-Api-Client": REQUEST_GOOG_API_CLIENT,
|
|
209
|
-
"Client-Metadata": REQUEST_CLIENT_METADATA,
|
|
210
|
-
},
|
|
829
|
+
headers: quotaHeaders,
|
|
211
830
|
body: JSON.stringify({
|
|
212
|
-
project:
|
|
831
|
+
project: projectId,
|
|
213
832
|
}),
|
|
214
833
|
timeoutMs: 8000,
|
|
834
|
+
retryPolicy: "antigravity",
|
|
215
835
|
dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
|
|
216
836
|
});
|
|
217
837
|
if (!isCurrentGeneration()) return;
|
|
@@ -239,13 +859,51 @@ export async function fetchProviderQuota(
|
|
|
239
859
|
if (!isCurrentGeneration()) return;
|
|
240
860
|
const data = parseGoogleQuotaResponse(rawData);
|
|
241
861
|
if (!data) return;
|
|
862
|
+
|
|
863
|
+
await refreshAicodeEligibilityIfNeeded(
|
|
864
|
+
account,
|
|
865
|
+
quotaHeaders,
|
|
866
|
+
isCurrentGeneration,
|
|
867
|
+
);
|
|
868
|
+
if (!isCurrentGeneration()) return;
|
|
869
|
+
|
|
870
|
+
const hasModels = Object.keys(data.models).length > 0;
|
|
871
|
+
let summary: GoogleQuotaSummaryResponse | null = null;
|
|
872
|
+
if (shouldShadowAicodeQuotaStatus(account)) {
|
|
873
|
+
// Shadow-only, like Antigravity.app: the result never replaces CCPA quota.
|
|
874
|
+
await fetchAicodeQuotaStatus(account, quotaHeaders).catch(() => null);
|
|
875
|
+
if (!isCurrentGeneration()) return;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
if (hasModels) {
|
|
879
|
+
try {
|
|
880
|
+
const summaryResponse = await fetchWithRetry(QUOTA_SUMMARY_API_URL, {
|
|
881
|
+
method: "POST",
|
|
882
|
+
headers: quotaHeaders,
|
|
883
|
+
body: JSON.stringify({ project: projectId }),
|
|
884
|
+
timeoutMs: 8000,
|
|
885
|
+
retries: 0,
|
|
886
|
+
dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
|
|
887
|
+
});
|
|
888
|
+
if (!isCurrentGeneration()) return;
|
|
889
|
+
if (summaryResponse.ok) {
|
|
890
|
+
summary = parseGoogleQuotaSummaryResponse(await summaryResponse.json());
|
|
891
|
+
}
|
|
892
|
+
} catch {
|
|
893
|
+
// Quota summary is additive; fall back to fetchAvailableModels when unavailable.
|
|
894
|
+
}
|
|
895
|
+
if (!isCurrentGeneration()) return;
|
|
896
|
+
}
|
|
897
|
+
|
|
242
898
|
const oldQuota = account.quota || [];
|
|
243
|
-
const
|
|
899
|
+
const poolOverrides = buildSummaryModelPoolMap(data, summary);
|
|
900
|
+
const fresh = extractQuotas(data, oldQuota, summary);
|
|
244
901
|
const newModels = dynamicCatalog.updateFromEndpointResponse(
|
|
245
902
|
data,
|
|
246
903
|
accountId,
|
|
247
904
|
credentialGeneration,
|
|
248
905
|
accountEpoch,
|
|
906
|
+
poolOverrides.size > 0 ? poolOverrides : undefined,
|
|
249
907
|
);
|
|
250
908
|
if (newModels > 0) {
|
|
251
909
|
ctx.log(
|
|
@@ -265,10 +923,91 @@ export async function fetchProviderQuota(
|
|
|
265
923
|
(q) => ((q as { providerId?: string }).providerId = "google-antigravity"),
|
|
266
924
|
);
|
|
267
925
|
const freshKeys = new Set(fresh.map((quota) => quota.modelKey));
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
926
|
+
const hasAuthoritativeSummary = Boolean(summary?.groups?.length || summary?.buckets?.length);
|
|
927
|
+
// When retrieveUserQuotaSummary returned authoritative groups, drop pools
|
|
928
|
+
// Google removed instead of retaining stale pools across polls. Only retain
|
|
929
|
+
// missing pools during partial fetchAvailableModels-only responses.
|
|
930
|
+
const previousGooglePools = hasAuthoritativeSummary
|
|
931
|
+
? []
|
|
932
|
+
: oldQuota.filter(
|
|
933
|
+
(q) => (q as { providerId?: string }).providerId === DEFAULT_PROVIDER &&
|
|
934
|
+
!freshKeys.has(q.modelKey),
|
|
935
|
+
);
|
|
936
|
+
const now = Date.now();
|
|
937
|
+
if (hasAuthoritativeSummary) {
|
|
938
|
+
// 1) Self-heal legacy/collapsed cooldowns: before dynamic pool separation,
|
|
939
|
+
// an exhausted custom group (e.g. "gemini-4-argon") could store its reset
|
|
940
|
+
// deadline under its parent family pool ("gemini"). When Google's summary
|
|
941
|
+
// separates that exhausted group while reporting the parent pool healthy,
|
|
942
|
+
// migrate that matching deadline off the parent pool so healthy sibling
|
|
943
|
+
// models (e.g. Hydrogen/Neon) are not locked out.
|
|
944
|
+
for (const customQuota of fresh) {
|
|
945
|
+
if (customQuota.percentRemaining !== 0 || !customQuota.resetTime) continue;
|
|
946
|
+
const parentPool = resolveQuotaModelKey(customQuota.modelKey);
|
|
947
|
+
if (!parentPool || parentPool === customQuota.modelKey) continue;
|
|
948
|
+
const customResetAt = Date.parse(customQuota.resetTime);
|
|
949
|
+
if (!Number.isFinite(customResetAt) || customResetAt <= now) continue;
|
|
950
|
+
const parentQuota = fresh.find((q) => q.modelKey === parentPool);
|
|
951
|
+
if (!parentQuota || parentQuota.percentRemaining <= 0) continue;
|
|
952
|
+
const parentCooldown = account.cooldownsByModel[parentPool];
|
|
953
|
+
if (
|
|
954
|
+
typeof parentCooldown === "number" &&
|
|
955
|
+
parentCooldown === cooldownSnapshotAtStart[parentPool] &&
|
|
956
|
+
Math.abs(parentCooldown - customResetAt) <= 1000
|
|
957
|
+
) {
|
|
958
|
+
delete account.cooldownsByModel[parentPool];
|
|
959
|
+
account.cooldownsByModel[customQuota.modelKey] = Math.max(
|
|
960
|
+
account.cooldownsByModel[customQuota.modelKey] ?? 0,
|
|
961
|
+
customResetAt,
|
|
962
|
+
);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// 2) Clear superseded multi-day (>= 6h) cooldowns when Google's
|
|
967
|
+
// authoritative summary reports the pool healthy (> 0%) with an active
|
|
968
|
+
// long window (e.g. weekly) whose reset time no longer matches the stored
|
|
969
|
+
// cooldown (e.g. quota rolled over to a new weekly cycle or was reset early).
|
|
970
|
+
for (const quota of fresh) {
|
|
971
|
+
if (quota.percentRemaining <= 0) continue;
|
|
972
|
+
const cooldownUntil = account.cooldownsByModel[quota.modelKey];
|
|
973
|
+
if (
|
|
974
|
+
typeof cooldownUntil !== "number" ||
|
|
975
|
+
!Number.isFinite(cooldownUntil) ||
|
|
976
|
+
cooldownUntil - now < SIX_HOURS_MS ||
|
|
977
|
+
cooldownUntil !== cooldownSnapshotAtStart[quota.modelKey]
|
|
978
|
+
) {
|
|
979
|
+
continue;
|
|
980
|
+
}
|
|
981
|
+
const longWindow = quota.windows?.find(
|
|
982
|
+
(w) =>
|
|
983
|
+
!w.disabled &&
|
|
984
|
+
(w.window === "weekly" ||
|
|
985
|
+
w.window === "7d" ||
|
|
986
|
+
(w.durationMs !== undefined && w.durationMs >= SIX_HOURS_MS)),
|
|
987
|
+
);
|
|
988
|
+
if (!longWindow || longWindow.percentRemaining <= 0) {
|
|
989
|
+
continue;
|
|
990
|
+
}
|
|
991
|
+
const isResetToFull = longWindow.percentRemaining === 100 && !longWindow.resetTime;
|
|
992
|
+
const longResetAt = longWindow.resetTime ? Date.parse(longWindow.resetTime) : NaN;
|
|
993
|
+
const resetMoved =
|
|
994
|
+
Number.isFinite(longResetAt) &&
|
|
995
|
+
longResetAt > now &&
|
|
996
|
+
Math.abs(longResetAt - cooldownUntil) > 5 * 60_000;
|
|
997
|
+
if (isResetToFull || resetMoved) {
|
|
998
|
+
delete account.cooldownsByModel[quota.modelKey];
|
|
999
|
+
for (const [modelKey, deadline] of Object.entries(account.cooldownsByModel)) {
|
|
1000
|
+
if (
|
|
1001
|
+
deadline === cooldownSnapshotAtStart[modelKey] &&
|
|
1002
|
+
Math.abs(deadline - cooldownUntil) <= 1000 &&
|
|
1003
|
+
dynamicCatalog.resolveQuotaPoolForAccount(accountId, modelKey) === quota.modelKey
|
|
1004
|
+
) {
|
|
1005
|
+
delete account.cooldownsByModel[modelKey];
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
272
1011
|
for (const quota of [...previousGooglePools, ...fresh]) {
|
|
273
1012
|
if (
|
|
274
1013
|
freshKeys.has(quota.modelKey) &&
|
|
@@ -282,7 +1021,7 @@ export async function fetchProviderQuota(
|
|
|
282
1021
|
applyActiveCooldown(
|
|
283
1022
|
quota,
|
|
284
1023
|
getActiveCooldownForPool(account, quota.modelKey),
|
|
285
|
-
|
|
1024
|
+
now,
|
|
286
1025
|
);
|
|
287
1026
|
}
|
|
288
1027
|
account.quota = sortQuotaPools([
|
|
@@ -301,10 +1040,18 @@ export async function fetchProviderQuota(
|
|
|
301
1040
|
(q as { providerId?: string }).providerId === "google-antigravity",
|
|
302
1041
|
)
|
|
303
1042
|
.map((q) => {
|
|
1043
|
+
const logNow = Date.now();
|
|
1044
|
+
if (q.windows?.length) {
|
|
1045
|
+
const parts = q.windows.map((w) => {
|
|
1046
|
+
const rem = w.resetTime
|
|
1047
|
+
? formatQuotaResetRemaining(w.resetTime, logNow)
|
|
1048
|
+
: "fresh";
|
|
1049
|
+
return `${w.window}:${w.percentRemaining}%/${rem}`;
|
|
1050
|
+
});
|
|
1051
|
+
return `[${q.modelKey}: ${parts.join(", ")}]`;
|
|
1052
|
+
}
|
|
304
1053
|
const remain = q.resetTime
|
|
305
|
-
?
|
|
306
|
-
(new Date(q.resetTime).getTime() - Date.now()) / 60000,
|
|
307
|
-
) + "m"
|
|
1054
|
+
? formatQuotaResetRemaining(q.resetTime, logNow)
|
|
308
1055
|
: "no_reset";
|
|
309
1056
|
return `[${q.modelKey}: ${q.timerType} ${q.percentRemaining}% in ${remain}]`;
|
|
310
1057
|
})
|