omp-multi-auth 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +109 -0
- package/extensions/lib/commands-preset.ts +286 -0
- package/extensions/lib/commands-subs.ts +551 -0
- package/extensions/lib/config.ts +316 -0
- package/extensions/lib/core.ts +96 -0
- package/extensions/lib/providers.ts +356 -0
- package/extensions/lib/quota.ts +1048 -0
- package/extensions/lib/ui.ts +101 -0
- package/extensions/multi-auth.ts +189 -0
- package/package.json +37 -0
|
@@ -0,0 +1,1048 @@
|
|
|
1
|
+
// ========================================================================
|
|
2
|
+
// Built-in quota checking
|
|
3
|
+
// ========================================================================
|
|
4
|
+
import type { ExtensionCommandContext, ExtensionContext, AuthStorage } from "@oh-my-pi/pi-coding-agent";
|
|
5
|
+
import { BorderedLoader } from "@oh-my-pi/pi-coding-agent";
|
|
6
|
+
import type { Api, Model } from "@oh-my-pi/pi-ai";
|
|
7
|
+
import { getBaseProvider, subDisplayName, PROVIDER_TEMPLATES } from "./providers.ts";
|
|
8
|
+
import { getAuthStorage, subProviderName, type AuthStorageEntry, type MultiAuthConfig, type QuotaAccount, type QuotaCheckResult, type QuotaStatusKind, type ProviderQuotaChecker } from "./core.ts";
|
|
9
|
+
import { loadGlobalConfig, loadProjectConfig, parseEnvConfig, mergeConfigs, normalizeEntries } from "./config.ts";
|
|
10
|
+
import { getWrappedSelectIndex, showWrappedSelect } from "./ui.ts";
|
|
11
|
+
import type { SelectItem } from "@oh-my-pi/pi-tui";
|
|
12
|
+
|
|
13
|
+
export const DEFAULT_CODEX_USAGE_BASE_URL = "https://chatgpt.com/backend-api";
|
|
14
|
+
export const GOOGLE_GEMINI_QUOTA_ENDPOINT = "https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota";
|
|
15
|
+
export const GOOGLE_ANTIGRAVITY_QUOTA_ENDPOINTS = [
|
|
16
|
+
"https://daily-cloudcode-pa.sandbox.googleapis.com/v1internal:fetchAvailableModels",
|
|
17
|
+
"https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels",
|
|
18
|
+
] as const;
|
|
19
|
+
export const GOOGLE_GEMINI_HEADERS = {
|
|
20
|
+
"User-Agent": "google-api-nodejs-client/9.15.1",
|
|
21
|
+
"X-Goog-Api-Client": "gl-node/22.17.0",
|
|
22
|
+
};
|
|
23
|
+
export const GOOGLE_ANTIGRAVITY_HEADERS = {
|
|
24
|
+
"User-Agent": "antigravity/1.11.9 windows/amd64",
|
|
25
|
+
"X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1",
|
|
26
|
+
"Client-Metadata": JSON.stringify({
|
|
27
|
+
ideType: "IDE_UNSPECIFIED",
|
|
28
|
+
platform: "PLATFORM_UNSPECIFIED",
|
|
29
|
+
pluginType: "GEMINI",
|
|
30
|
+
}),
|
|
31
|
+
};
|
|
32
|
+
export const GOOGLE_ANTIGRAVITY_HIDDEN_MODELS = new Set(["tab_flash_lite_preview"]);
|
|
33
|
+
export const OPENAI_AUTH_CLAIM = "https://api.openai.com/auth";
|
|
34
|
+
export const OPENAI_PROFILE_CLAIM = "https://api.openai.com/profile";
|
|
35
|
+
|
|
36
|
+
export interface CodexUsageWindow {
|
|
37
|
+
usedPercent: number;
|
|
38
|
+
windowSeconds: number;
|
|
39
|
+
resetAt?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface CodexUsageSnapshot {
|
|
43
|
+
planType: string;
|
|
44
|
+
email: string;
|
|
45
|
+
fiveHour?: CodexUsageWindow;
|
|
46
|
+
weekly?: CodexUsageWindow;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface GoogleGeminiQuotaResponse {
|
|
50
|
+
buckets?: Array<{
|
|
51
|
+
modelId?: string;
|
|
52
|
+
remainingFraction?: number;
|
|
53
|
+
resetTime?: string;
|
|
54
|
+
}>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface GoogleAntigravityQuotaResponse {
|
|
58
|
+
models?: Record<
|
|
59
|
+
string,
|
|
60
|
+
{
|
|
61
|
+
displayName?: string;
|
|
62
|
+
model?: string;
|
|
63
|
+
isInternal?: boolean;
|
|
64
|
+
quotaInfo?: {
|
|
65
|
+
remainingFraction?: number;
|
|
66
|
+
resetTime?: string;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface GoogleQuotaModelSnapshot {
|
|
73
|
+
model: string;
|
|
74
|
+
remainingPercent?: number;
|
|
75
|
+
resetAt?: number;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface GoogleQuotaAccountSnapshot {
|
|
79
|
+
endpoint: string;
|
|
80
|
+
projectId?: string;
|
|
81
|
+
models: GoogleQuotaModelSnapshot[];
|
|
82
|
+
worstRemainingPercent?: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function decodeJwtPayload(token: string): Record<string, unknown> {
|
|
86
|
+
const parts = token.split(".");
|
|
87
|
+
if (parts.length < 2) return {};
|
|
88
|
+
try {
|
|
89
|
+
return JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) as Record<string, unknown>;
|
|
90
|
+
} catch {
|
|
91
|
+
return {};
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function getRecord(value: unknown): Record<string, unknown> | undefined {
|
|
96
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
97
|
+
return value as Record<string, unknown>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function getCodexTokenMetadata(accessToken: string): {
|
|
101
|
+
accountId?: string;
|
|
102
|
+
planType?: string;
|
|
103
|
+
email?: string;
|
|
104
|
+
} {
|
|
105
|
+
const payload = decodeJwtPayload(accessToken);
|
|
106
|
+
const auth = getRecord(payload[OPENAI_AUTH_CLAIM]);
|
|
107
|
+
const profile = getRecord(payload[OPENAI_PROFILE_CLAIM]);
|
|
108
|
+
const accountId = typeof auth?.chatgpt_account_id === "string" ? auth.chatgpt_account_id : undefined;
|
|
109
|
+
const planType = typeof auth?.chatgpt_plan_type === "string" ? auth.chatgpt_plan_type : undefined;
|
|
110
|
+
const email = typeof profile?.email === "string" ? profile.email : undefined;
|
|
111
|
+
return { accountId, planType, email };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function normalizeCodexUsageWindow(window: unknown): CodexUsageWindow | undefined {
|
|
115
|
+
const raw = getRecord(window);
|
|
116
|
+
if (!raw) return undefined;
|
|
117
|
+
const usedPercent = typeof raw.used_percent === "number" ? raw.used_percent : 0;
|
|
118
|
+
const windowSeconds = typeof raw.limit_window_seconds === "number" ? raw.limit_window_seconds : 0;
|
|
119
|
+
const resetAt = typeof raw.reset_at === "number" ? raw.reset_at : undefined;
|
|
120
|
+
return {
|
|
121
|
+
usedPercent,
|
|
122
|
+
windowSeconds,
|
|
123
|
+
resetAt,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function matchesUsageWindow(window: CodexUsageWindow | undefined, expectedSeconds: number): boolean {
|
|
128
|
+
if (!window) return false;
|
|
129
|
+
return Math.abs(window.windowSeconds - expectedSeconds) <= 120;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function parseCodexUsageSnapshot(data: unknown): CodexUsageSnapshot {
|
|
133
|
+
const raw = getRecord(data);
|
|
134
|
+
const rateLimit = getRecord(raw?.rate_limit);
|
|
135
|
+
const windows = [
|
|
136
|
+
normalizeCodexUsageWindow(rateLimit?.primary_window),
|
|
137
|
+
normalizeCodexUsageWindow(rateLimit?.secondary_window),
|
|
138
|
+
].filter((window): window is CodexUsageWindow => Boolean(window));
|
|
139
|
+
const fiveHour = windows.find((window) => matchesUsageWindow(window, 5 * 60 * 60));
|
|
140
|
+
const weekly = windows.find((window) => matchesUsageWindow(window, 7 * 24 * 60 * 60));
|
|
141
|
+
return {
|
|
142
|
+
planType: typeof raw?.plan_type === "string" ? raw.plan_type : "unknown",
|
|
143
|
+
email: typeof raw?.email === "string" ? raw.email : "",
|
|
144
|
+
fiveHour,
|
|
145
|
+
weekly,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function getCodexWindowRemaining(window: CodexUsageWindow | undefined): number | undefined {
|
|
150
|
+
if (!window) return undefined;
|
|
151
|
+
return Math.max(0, Math.min(100, 100 - window.usedPercent));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function formatResetShort(resetAt?: number): string {
|
|
155
|
+
if (!resetAt) return "--";
|
|
156
|
+
const diffMs = resetAt * 1000 - Date.now();
|
|
157
|
+
if (diffMs <= 0) return "now";
|
|
158
|
+
const totalMinutes = Math.round(diffMs / 60000);
|
|
159
|
+
const days = Math.floor(totalMinutes / (60 * 24));
|
|
160
|
+
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
|
|
161
|
+
const minutes = totalMinutes % 60;
|
|
162
|
+
if (days > 0) return `~${days}d`;
|
|
163
|
+
if (hours > 0) return `~${hours}h`;
|
|
164
|
+
return `~${minutes}m`;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function formatResetLong(resetAt?: number): string {
|
|
168
|
+
if (!resetAt) return "unknown";
|
|
169
|
+
const diffMs = resetAt * 1000 - Date.now();
|
|
170
|
+
if (diffMs <= 0) return "now";
|
|
171
|
+
const totalMinutes = Math.round(diffMs / 60000);
|
|
172
|
+
const days = Math.floor(totalMinutes / (60 * 24));
|
|
173
|
+
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
|
|
174
|
+
const minutes = totalMinutes % 60;
|
|
175
|
+
if (days > 0) return `in ${days}d ${hours}h`;
|
|
176
|
+
if (hours > 0) return `in ${hours}h ${minutes}m`;
|
|
177
|
+
return `in ${minutes}m`;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function formatRemainingPercent(value: number | undefined): string {
|
|
181
|
+
if (value === undefined) return "--";
|
|
182
|
+
return `${Math.round(value)}%`;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function isAbortError(error: unknown): boolean {
|
|
186
|
+
return error instanceof Error && error.name === "AbortError";
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function parseIsoTimestampSeconds(value: string | undefined): number | undefined {
|
|
190
|
+
if (!value) return undefined;
|
|
191
|
+
const parsed = Date.parse(value);
|
|
192
|
+
if (!Number.isFinite(parsed)) return undefined;
|
|
193
|
+
return Math.floor(parsed / 1000);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export async function readResponseError(response: Response): Promise<string> {
|
|
197
|
+
const raw = await response.text();
|
|
198
|
+
if (response.status === 401) {
|
|
199
|
+
return "Unauthorized - log in again";
|
|
200
|
+
}
|
|
201
|
+
if (!raw) {
|
|
202
|
+
return `HTTP ${response.status}`;
|
|
203
|
+
}
|
|
204
|
+
try {
|
|
205
|
+
const parsed = JSON.parse(raw) as {
|
|
206
|
+
error?: { message?: string };
|
|
207
|
+
message?: string;
|
|
208
|
+
};
|
|
209
|
+
const message = parsed.error?.message || parsed.message;
|
|
210
|
+
if (message) return `HTTP ${response.status}: ${message}`;
|
|
211
|
+
} catch {
|
|
212
|
+
// ignore JSON parse errors and fall back to raw text
|
|
213
|
+
}
|
|
214
|
+
return `HTTP ${response.status}: ${raw}`;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function classifyCodexQuotaKind(snapshot: CodexUsageSnapshot): {
|
|
218
|
+
kind: QuotaStatusKind;
|
|
219
|
+
score: number;
|
|
220
|
+
} {
|
|
221
|
+
const fiveHourLeft = getCodexWindowRemaining(snapshot.fiveHour);
|
|
222
|
+
const weeklyLeft = getCodexWindowRemaining(snapshot.weekly);
|
|
223
|
+
const values = [fiveHourLeft, weeklyLeft].filter((value): value is number => value !== undefined);
|
|
224
|
+
if (values.length === 0) {
|
|
225
|
+
return { kind: "error", score: 0 };
|
|
226
|
+
}
|
|
227
|
+
const bottleneck = Math.min(...values);
|
|
228
|
+
if (bottleneck <= 5) return { kind: "blocked", score: bottleneck };
|
|
229
|
+
if (bottleneck <= 15) return { kind: "low", score: bottleneck };
|
|
230
|
+
if (bottleneck <= 30) return { kind: "watch", score: bottleneck };
|
|
231
|
+
return { kind: "ready", score: bottleneck };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function formatQuotaKind(kind: QuotaStatusKind): string {
|
|
235
|
+
switch (kind) {
|
|
236
|
+
case "ready":
|
|
237
|
+
return "ready";
|
|
238
|
+
case "watch":
|
|
239
|
+
return "watch";
|
|
240
|
+
case "low":
|
|
241
|
+
return "low";
|
|
242
|
+
case "blocked":
|
|
243
|
+
return "blocked";
|
|
244
|
+
case "missing-auth":
|
|
245
|
+
return "not logged in";
|
|
246
|
+
default:
|
|
247
|
+
return "error";
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export function compareQuotaResults(left: QuotaCheckResult, right: QuotaCheckResult): number {
|
|
252
|
+
const rank = (kind: QuotaStatusKind): number => {
|
|
253
|
+
switch (kind) {
|
|
254
|
+
case "ready":
|
|
255
|
+
return 0;
|
|
256
|
+
case "watch":
|
|
257
|
+
return 1;
|
|
258
|
+
case "low":
|
|
259
|
+
return 2;
|
|
260
|
+
case "blocked":
|
|
261
|
+
return 3;
|
|
262
|
+
case "error":
|
|
263
|
+
return 4;
|
|
264
|
+
case "missing-auth":
|
|
265
|
+
return 5;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
return rank(left.kind) - rank(right.kind)
|
|
269
|
+
|| right.score - left.score
|
|
270
|
+
|| left.account.displayName.localeCompare(right.account.displayName);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function getQuotaStatusGlyph(kind: QuotaStatusKind): string {
|
|
274
|
+
switch (kind) {
|
|
275
|
+
case "ready":
|
|
276
|
+
return "✓";
|
|
277
|
+
case "watch":
|
|
278
|
+
return "◔";
|
|
279
|
+
case "low":
|
|
280
|
+
return "!";
|
|
281
|
+
case "blocked":
|
|
282
|
+
return "✕";
|
|
283
|
+
case "missing-auth":
|
|
284
|
+
return "○";
|
|
285
|
+
default:
|
|
286
|
+
return "?";
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function formatQuotaOverview(results: QuotaCheckResult[]): string {
|
|
291
|
+
const counts = {
|
|
292
|
+
ready: 0,
|
|
293
|
+
watch: 0,
|
|
294
|
+
low: 0,
|
|
295
|
+
blocked: 0,
|
|
296
|
+
error: 0,
|
|
297
|
+
missingAuth: 0,
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
for (const result of results) {
|
|
301
|
+
switch (result.kind) {
|
|
302
|
+
case "ready":
|
|
303
|
+
counts.ready++;
|
|
304
|
+
break;
|
|
305
|
+
case "watch":
|
|
306
|
+
counts.watch++;
|
|
307
|
+
break;
|
|
308
|
+
case "low":
|
|
309
|
+
counts.low++;
|
|
310
|
+
break;
|
|
311
|
+
case "blocked":
|
|
312
|
+
counts.blocked++;
|
|
313
|
+
break;
|
|
314
|
+
case "missing-auth":
|
|
315
|
+
counts.missingAuth++;
|
|
316
|
+
break;
|
|
317
|
+
default:
|
|
318
|
+
counts.error++;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const parts = [`${results.length} ${results.length === 1 ? "account" : "accounts"}`];
|
|
323
|
+
if (counts.ready > 0) parts.push(`${counts.ready} ready`);
|
|
324
|
+
if (counts.watch > 0) parts.push(`${counts.watch} watch`);
|
|
325
|
+
if (counts.low > 0) parts.push(`${counts.low} low`);
|
|
326
|
+
if (counts.blocked > 0) parts.push(`${counts.blocked} blocked`);
|
|
327
|
+
if (counts.error > 0) parts.push(`${counts.error} error`);
|
|
328
|
+
if (counts.missingAuth > 0) parts.push(`${counts.missingAuth} not logged in`);
|
|
329
|
+
|
|
330
|
+
const best = results[0];
|
|
331
|
+
if (best) {
|
|
332
|
+
parts.push(`best now: ${best.account.displayName}`);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return parts.join(" • ");
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export function formatQuotaCurrentHint(
|
|
339
|
+
results: QuotaCheckResult[],
|
|
340
|
+
currentProviderName: string | undefined,
|
|
341
|
+
): string | undefined {
|
|
342
|
+
if (!currentProviderName) return undefined;
|
|
343
|
+
|
|
344
|
+
const current = results.find((result) => result.account.providerName === currentProviderName);
|
|
345
|
+
if (!current) return undefined;
|
|
346
|
+
|
|
347
|
+
let hint = `Current: ${current.account.displayName} is ${formatQuotaKind(current.kind)}`;
|
|
348
|
+
const best = results[0];
|
|
349
|
+
if (best && best.account.providerName !== current.account.providerName) {
|
|
350
|
+
hint += ` • best available: ${best.account.displayName}`;
|
|
351
|
+
}
|
|
352
|
+
if (current.kind !== "ready") {
|
|
353
|
+
hint += " • snapshot only: auto-switch happens after a runtime rate-limit error";
|
|
354
|
+
}
|
|
355
|
+
return hint;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export function buildQuotaSelectItems(
|
|
359
|
+
results: QuotaCheckResult[],
|
|
360
|
+
currentProviderName: string | undefined,
|
|
361
|
+
): SelectItem[] {
|
|
362
|
+
const bestProviderName = results[0]?.account.providerName;
|
|
363
|
+
return results.map((result) => {
|
|
364
|
+
const badges: string[] = [];
|
|
365
|
+
if (result.account.providerName === currentProviderName) badges.push("current");
|
|
366
|
+
if (result.account.providerName === bestProviderName) badges.push("best now");
|
|
367
|
+
const badgeSuffix = badges.length > 0 ? ` • ${badges.join(" • ")}` : "";
|
|
368
|
+
|
|
369
|
+
return {
|
|
370
|
+
value: result.account.providerName,
|
|
371
|
+
label: `${getQuotaStatusGlyph(result.kind)} ${result.account.displayName}`,
|
|
372
|
+
description: `${result.summary}${badgeSuffix}`,
|
|
373
|
+
};
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export async function runQuotaChecks(
|
|
378
|
+
accounts: QuotaAccount[],
|
|
379
|
+
authStorage: AuthStorage,
|
|
380
|
+
signal?: AbortSignal,
|
|
381
|
+
): Promise<QuotaCheckResult[]> {
|
|
382
|
+
const results = await Promise.all(accounts.map(async (account) => {
|
|
383
|
+
const checker = PROVIDER_QUOTA_CHECKERS.find(
|
|
384
|
+
(candidate) => candidate.baseProvider === account.baseProvider,
|
|
385
|
+
);
|
|
386
|
+
if (!checker) return undefined;
|
|
387
|
+
return checker.check(account, authStorage, signal);
|
|
388
|
+
}));
|
|
389
|
+
|
|
390
|
+
return results
|
|
391
|
+
.filter((result): result is QuotaCheckResult => Boolean(result))
|
|
392
|
+
.sort(compareQuotaResults);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export async function loadQuotaResults(
|
|
396
|
+
ctx: ExtensionCommandContext,
|
|
397
|
+
accounts: QuotaAccount[],
|
|
398
|
+
authStorage: AuthStorage,
|
|
399
|
+
): Promise<QuotaCheckResult[] | null> {
|
|
400
|
+
if (!ctx.hasUI) {
|
|
401
|
+
return runQuotaChecks(accounts, authStorage);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
return ctx.ui.custom<QuotaCheckResult[] | null>((tui, theme, _kb, done) => {
|
|
405
|
+
const loader = new BorderedLoader(
|
|
406
|
+
tui,
|
|
407
|
+
theme,
|
|
408
|
+
`Checking limits across ${accounts.length} ${accounts.length === 1 ? "account" : "accounts"}...`,
|
|
409
|
+
);
|
|
410
|
+
loader.onAbort = () => done(null);
|
|
411
|
+
|
|
412
|
+
runQuotaChecks(accounts, authStorage, loader.signal)
|
|
413
|
+
.then(done)
|
|
414
|
+
.catch((error) => {
|
|
415
|
+
if (loader.signal.aborted) {
|
|
416
|
+
done(null);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
console.error("Failed to load quota checks", error);
|
|
420
|
+
done(null);
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
return loader;
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
export async function selectQuotaResult(
|
|
428
|
+
ctx: ExtensionCommandContext,
|
|
429
|
+
results: QuotaCheckResult[],
|
|
430
|
+
preferredProviderName?: string,
|
|
431
|
+
): Promise<QuotaCheckResult | undefined> {
|
|
432
|
+
const currentProviderName = preferredProviderName || ctx.model?.provider;
|
|
433
|
+
const selectedProviderName = await showWrappedSelect(ctx, {
|
|
434
|
+
title: "Subscription Limits",
|
|
435
|
+
subtitle: [
|
|
436
|
+
"Select an account to inspect its full quota windows.",
|
|
437
|
+
formatQuotaOverview(results),
|
|
438
|
+
formatQuotaCurrentHint(results, currentProviderName),
|
|
439
|
+
].filter(Boolean).join("\n"),
|
|
440
|
+
items: buildQuotaSelectItems(results, currentProviderName),
|
|
441
|
+
initialValue: currentProviderName,
|
|
442
|
+
confirmHint: "inspect",
|
|
443
|
+
cancelHint: "close",
|
|
444
|
+
});
|
|
445
|
+
if (!selectedProviderName) return undefined;
|
|
446
|
+
return results.find((result) => result.account.providerName === selectedProviderName);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export function normalizeGoogleRemainingPercent(value: unknown): number | undefined {
|
|
450
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
|
|
451
|
+
return Math.max(0, Math.min(100, Math.round(value * 100)));
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export function getGoogleProjectId(account: QuotaAccount, auth: AuthStorageEntry): string | undefined {
|
|
455
|
+
if (typeof auth.projectId === "string" && auth.projectId.length > 0) {
|
|
456
|
+
return auth.projectId;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
if (account.baseProvider === "google-antigravity") {
|
|
460
|
+
const projectId = process.env.GOOGLE_ANTIGRAVITY_PROJECT_ID || process.env.GOOGLE_ANTIGRAVITY_PROJECT;
|
|
461
|
+
if (projectId) return projectId;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const projectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT_ID;
|
|
465
|
+
return projectId || undefined;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
export function updateGoogleQuotaModel(
|
|
469
|
+
modelsByName: Map<string, GoogleQuotaModelSnapshot>,
|
|
470
|
+
model: string,
|
|
471
|
+
remainingPercent: number | undefined,
|
|
472
|
+
resetAt: number | undefined,
|
|
473
|
+
): void {
|
|
474
|
+
const existing = modelsByName.get(model);
|
|
475
|
+
if (!existing) {
|
|
476
|
+
modelsByName.set(model, { model, remainingPercent, resetAt });
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
let next = existing;
|
|
481
|
+
if (remainingPercent !== undefined) {
|
|
482
|
+
if (existing.remainingPercent === undefined || remainingPercent < existing.remainingPercent) {
|
|
483
|
+
next = { ...next, remainingPercent };
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (resetAt !== undefined) {
|
|
487
|
+
if (next.resetAt === undefined || resetAt < next.resetAt) {
|
|
488
|
+
next = { ...next, resetAt };
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
if (next !== existing) {
|
|
492
|
+
modelsByName.set(model, next);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
export function buildGoogleQuotaSnapshot(
|
|
497
|
+
endpoint: string,
|
|
498
|
+
projectId: string | undefined,
|
|
499
|
+
modelsByName: Map<string, GoogleQuotaModelSnapshot>,
|
|
500
|
+
): GoogleQuotaAccountSnapshot {
|
|
501
|
+
const models = [...modelsByName.values()];
|
|
502
|
+
const remainingPercents = models
|
|
503
|
+
.map((model) => model.remainingPercent)
|
|
504
|
+
.filter((value): value is number => value !== undefined);
|
|
505
|
+
const worstRemainingPercent = remainingPercents.length > 0
|
|
506
|
+
? Math.min(...remainingPercents)
|
|
507
|
+
: undefined;
|
|
508
|
+
|
|
509
|
+
return {
|
|
510
|
+
endpoint,
|
|
511
|
+
projectId,
|
|
512
|
+
models,
|
|
513
|
+
worstRemainingPercent,
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
export function getGoogleGeminiModelLabel(modelId: string | undefined): string {
|
|
518
|
+
if (!modelId) return "unknown";
|
|
519
|
+
const normalized = modelId.toLowerCase();
|
|
520
|
+
if (normalized.includes("pro")) return "Pro";
|
|
521
|
+
if (normalized.includes("flash")) return "Flash";
|
|
522
|
+
return modelId;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
export function parseGoogleGeminiQuotaSnapshot(
|
|
526
|
+
data: unknown,
|
|
527
|
+
projectId: string | undefined,
|
|
528
|
+
): GoogleQuotaAccountSnapshot {
|
|
529
|
+
const raw = getRecord(data) as GoogleGeminiQuotaResponse | undefined;
|
|
530
|
+
const buckets = Array.isArray(raw?.buckets) ? raw.buckets : [];
|
|
531
|
+
const modelsByName = new Map<string, GoogleQuotaModelSnapshot>();
|
|
532
|
+
|
|
533
|
+
for (const bucketValue of buckets) {
|
|
534
|
+
const bucket = getRecord(bucketValue);
|
|
535
|
+
const model = getGoogleGeminiModelLabel(
|
|
536
|
+
typeof bucket?.modelId === "string" ? bucket.modelId : undefined,
|
|
537
|
+
);
|
|
538
|
+
const remainingPercent = normalizeGoogleRemainingPercent(bucket?.remainingFraction);
|
|
539
|
+
const resetAt = typeof bucket?.resetTime === "string"
|
|
540
|
+
? parseIsoTimestampSeconds(bucket.resetTime)
|
|
541
|
+
: undefined;
|
|
542
|
+
if (remainingPercent === undefined && resetAt === undefined) continue;
|
|
543
|
+
updateGoogleQuotaModel(modelsByName, model, remainingPercent, resetAt);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
return buildGoogleQuotaSnapshot(GOOGLE_GEMINI_QUOTA_ENDPOINT, projectId, modelsByName);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
export function parseGoogleAntigravityQuotaSnapshot(
|
|
550
|
+
data: unknown,
|
|
551
|
+
endpoint: string,
|
|
552
|
+
projectId: string | undefined,
|
|
553
|
+
): GoogleQuotaAccountSnapshot {
|
|
554
|
+
const raw = getRecord(data) as GoogleAntigravityQuotaResponse | undefined;
|
|
555
|
+
const rawModels = getRecord(raw?.models);
|
|
556
|
+
const modelsByName = new Map<string, GoogleQuotaModelSnapshot>();
|
|
557
|
+
|
|
558
|
+
if (rawModels) {
|
|
559
|
+
for (const [modelKey, modelValue] of Object.entries(rawModels)) {
|
|
560
|
+
const model = getRecord(modelValue);
|
|
561
|
+
if (model?.isInternal === true) continue;
|
|
562
|
+
if (GOOGLE_ANTIGRAVITY_HIDDEN_MODELS.has(modelKey.toLowerCase())) continue;
|
|
563
|
+
const displayName = typeof model?.displayName === "string" && model.displayName.length > 0
|
|
564
|
+
? model.displayName
|
|
565
|
+
: typeof model?.model === "string" && model.model.length > 0
|
|
566
|
+
? model.model
|
|
567
|
+
: modelKey;
|
|
568
|
+
if (GOOGLE_ANTIGRAVITY_HIDDEN_MODELS.has(displayName.toLowerCase())) continue;
|
|
569
|
+
const quotaInfo = getRecord(model?.quotaInfo);
|
|
570
|
+
const remainingPercent = normalizeGoogleRemainingPercent(quotaInfo?.remainingFraction);
|
|
571
|
+
const resetAt = typeof quotaInfo?.resetTime === "string"
|
|
572
|
+
? parseIsoTimestampSeconds(quotaInfo.resetTime)
|
|
573
|
+
: undefined;
|
|
574
|
+
if (remainingPercent === undefined && resetAt === undefined) continue;
|
|
575
|
+
updateGoogleQuotaModel(modelsByName, displayName, remainingPercent, resetAt);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
return buildGoogleQuotaSnapshot(endpoint, projectId, modelsByName);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
export function classifyGoogleQuotaKind(snapshot: GoogleQuotaAccountSnapshot): {
|
|
583
|
+
kind: QuotaStatusKind;
|
|
584
|
+
score: number;
|
|
585
|
+
} {
|
|
586
|
+
const bottleneck = snapshot.worstRemainingPercent;
|
|
587
|
+
if (bottleneck === undefined) {
|
|
588
|
+
return { kind: "error", score: 0 };
|
|
589
|
+
}
|
|
590
|
+
if (bottleneck <= 5) return { kind: "blocked", score: bottleneck };
|
|
591
|
+
if (bottleneck <= 15) return { kind: "low", score: bottleneck };
|
|
592
|
+
if (bottleneck <= 30) return { kind: "watch", score: bottleneck };
|
|
593
|
+
return { kind: "ready", score: bottleneck };
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
export async function resolveGoogleQuotaAccess(
|
|
597
|
+
account: QuotaAccount,
|
|
598
|
+
auth: AuthStorageEntry,
|
|
599
|
+
authStorage: AuthStorage,
|
|
600
|
+
signal?: AbortSignal,
|
|
601
|
+
): Promise<{ accessToken: string; projectId?: string }> {
|
|
602
|
+
const projectId = getGoogleProjectId(account, auth);
|
|
603
|
+
const hasFreshAccess = typeof auth.access === "string"
|
|
604
|
+
&& auth.access.length > 0
|
|
605
|
+
&& (typeof auth.expires !== "number" || auth.expires > Date.now() + 60_000);
|
|
606
|
+
if (hasFreshAccess) {
|
|
607
|
+
return { accessToken: auth.access!, projectId };
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const access = await authStorage.getOAuthAccess(account.providerName, undefined, { signal });
|
|
611
|
+
if (!access) {
|
|
612
|
+
throw new Error("Unable to refresh Google OAuth credentials. Log in again.");
|
|
613
|
+
}
|
|
614
|
+
return {
|
|
615
|
+
accessToken: access.accessToken,
|
|
616
|
+
projectId: access.projectId || projectId,
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
export async function fetchGoogleGeminiQuotaSnapshot(
|
|
621
|
+
accessToken: string,
|
|
622
|
+
projectId: string | undefined,
|
|
623
|
+
signal?: AbortSignal,
|
|
624
|
+
): Promise<GoogleQuotaAccountSnapshot> {
|
|
625
|
+
const response = await fetch(GOOGLE_GEMINI_QUOTA_ENDPOINT, {
|
|
626
|
+
method: "POST",
|
|
627
|
+
headers: {
|
|
628
|
+
Authorization: `Bearer ${accessToken}`,
|
|
629
|
+
Accept: "application/json",
|
|
630
|
+
"Content-Type": "application/json",
|
|
631
|
+
...GOOGLE_GEMINI_HEADERS,
|
|
632
|
+
},
|
|
633
|
+
body: "{}",
|
|
634
|
+
signal,
|
|
635
|
+
});
|
|
636
|
+
if (!response.ok) {
|
|
637
|
+
throw new Error(await readResponseError(response));
|
|
638
|
+
}
|
|
639
|
+
return parseGoogleGeminiQuotaSnapshot(await response.json(), projectId);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
export async function fetchGoogleAntigravityQuotaSnapshot(
|
|
643
|
+
accessToken: string,
|
|
644
|
+
projectId: string | undefined,
|
|
645
|
+
signal?: AbortSignal,
|
|
646
|
+
): Promise<GoogleQuotaAccountSnapshot> {
|
|
647
|
+
let lastError = "Google quota lookup failed";
|
|
648
|
+
|
|
649
|
+
for (const endpoint of GOOGLE_ANTIGRAVITY_QUOTA_ENDPOINTS) {
|
|
650
|
+
const response = await fetch(endpoint, {
|
|
651
|
+
method: "POST",
|
|
652
|
+
headers: {
|
|
653
|
+
Authorization: `Bearer ${accessToken}`,
|
|
654
|
+
Accept: "application/json",
|
|
655
|
+
"Content-Type": "application/json",
|
|
656
|
+
...GOOGLE_ANTIGRAVITY_HEADERS,
|
|
657
|
+
},
|
|
658
|
+
body: JSON.stringify(projectId ? { project: projectId } : {}),
|
|
659
|
+
signal,
|
|
660
|
+
});
|
|
661
|
+
if (response.ok) {
|
|
662
|
+
return parseGoogleAntigravityQuotaSnapshot(await response.json(), endpoint, projectId);
|
|
663
|
+
}
|
|
664
|
+
lastError = await readResponseError(response);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
throw new Error(lastError);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
export function getGoogleQuotaBucketLabel(account: QuotaAccount, count: number): string {
|
|
671
|
+
if (account.baseProvider === "google-gemini-cli") {
|
|
672
|
+
return `${count} ${count === 1 ? "family" : "families"}`;
|
|
673
|
+
}
|
|
674
|
+
return `${count} ${count === 1 ? "model" : "models"}`;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
export function buildGoogleQuotaErrorDetails(
|
|
678
|
+
account: QuotaAccount,
|
|
679
|
+
message: string,
|
|
680
|
+
projectId?: string,
|
|
681
|
+
): string[] {
|
|
682
|
+
const details = [
|
|
683
|
+
`account: ${account.displayName}`,
|
|
684
|
+
`provider: ${account.providerName}`,
|
|
685
|
+
"status: error",
|
|
686
|
+
];
|
|
687
|
+
if (projectId) {
|
|
688
|
+
details.push(`project: ${projectId}`);
|
|
689
|
+
}
|
|
690
|
+
details.push(`details: ${message}`);
|
|
691
|
+
|
|
692
|
+
if (/401|unauthorized/i.test(message)) {
|
|
693
|
+
details.push("login: use /multi-auth login or /login to authenticate this account again");
|
|
694
|
+
return details;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
if (/403|permission/i.test(message)) {
|
|
698
|
+
if (account.baseProvider === "google-gemini-cli") {
|
|
699
|
+
details.push(
|
|
700
|
+
"hint: Google Cloud Code Assist rejected quota access for this account; try /multi-auth login again and verify this account still has Gemini quota access",
|
|
701
|
+
);
|
|
702
|
+
} else {
|
|
703
|
+
details.push(
|
|
704
|
+
"hint: Google rejected this Antigravity quota request; verify the saved project/account pairing is still valid and try /multi-auth login again",
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
return details;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
export function formatGoogleQuotaDetails(
|
|
713
|
+
account: QuotaAccount,
|
|
714
|
+
snapshot: GoogleQuotaAccountSnapshot,
|
|
715
|
+
kind: QuotaStatusKind,
|
|
716
|
+
): string[] {
|
|
717
|
+
const details = [
|
|
718
|
+
`account: ${account.displayName}`,
|
|
719
|
+
`provider: ${account.providerName}`,
|
|
720
|
+
`status: ${formatQuotaKind(kind)}`,
|
|
721
|
+
];
|
|
722
|
+
if (snapshot.projectId) {
|
|
723
|
+
details.push(`project: ${snapshot.projectId}`);
|
|
724
|
+
}
|
|
725
|
+
if (snapshot.worstRemainingPercent !== undefined) {
|
|
726
|
+
details.push(`bottleneck: ${formatRemainingPercent(snapshot.worstRemainingPercent)} left`);
|
|
727
|
+
}
|
|
728
|
+
for (const model of [...snapshot.models].sort((left, right) => {
|
|
729
|
+
const leftPercent = left.remainingPercent ?? 101;
|
|
730
|
+
const rightPercent = right.remainingPercent ?? 101;
|
|
731
|
+
return leftPercent - rightPercent || left.model.localeCompare(right.model);
|
|
732
|
+
})) {
|
|
733
|
+
details.push(
|
|
734
|
+
`${model.model}: ${formatRemainingPercent(model.remainingPercent)} left, resets ${formatResetLong(model.resetAt)}`,
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
details.push(`endpoint: ${snapshot.endpoint}`);
|
|
738
|
+
return details;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
export async function checkGoogleQuotaAccount(
|
|
742
|
+
account: QuotaAccount,
|
|
743
|
+
fetchSnapshot: (
|
|
744
|
+
accessToken: string,
|
|
745
|
+
projectId: string | undefined,
|
|
746
|
+
signal?: AbortSignal,
|
|
747
|
+
) => Promise<GoogleQuotaAccountSnapshot>,
|
|
748
|
+
authStorage: AuthStorage,
|
|
749
|
+
signal?: AbortSignal,
|
|
750
|
+
): Promise<QuotaCheckResult> {
|
|
751
|
+
const auth = account.auth;
|
|
752
|
+
if (!auth || auth.type !== "oauth") {
|
|
753
|
+
return {
|
|
754
|
+
account,
|
|
755
|
+
kind: "missing-auth",
|
|
756
|
+
summary: "not logged in",
|
|
757
|
+
details: [
|
|
758
|
+
`account: ${account.displayName}`,
|
|
759
|
+
`provider: ${account.providerName}`,
|
|
760
|
+
"status: not logged in",
|
|
761
|
+
"login: use /multi-auth login or /login to authenticate this account",
|
|
762
|
+
],
|
|
763
|
+
score: 0,
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
if ((typeof auth.access !== "string" || auth.access.length === 0)
|
|
767
|
+
&& (typeof auth.refresh !== "string" || auth.refresh.length === 0)) {
|
|
768
|
+
return {
|
|
769
|
+
account,
|
|
770
|
+
kind: "missing-auth",
|
|
771
|
+
summary: "missing Google tokens",
|
|
772
|
+
details: [
|
|
773
|
+
`account: ${account.displayName}`,
|
|
774
|
+
`provider: ${account.providerName}`,
|
|
775
|
+
"status: not logged in",
|
|
776
|
+
"details: saved Google credentials are missing both access and refresh tokens",
|
|
777
|
+
"login: use /multi-auth login or /login to authenticate this account again",
|
|
778
|
+
],
|
|
779
|
+
score: 0,
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
let projectId: string | undefined;
|
|
785
|
+
|
|
786
|
+
try {
|
|
787
|
+
const credentials = await resolveGoogleQuotaAccess(account, auth, authStorage, signal);
|
|
788
|
+
projectId = credentials.projectId;
|
|
789
|
+
const snapshot = await fetchSnapshot(credentials.accessToken, credentials.projectId, signal);
|
|
790
|
+
if (snapshot.models.length === 0 || snapshot.worstRemainingPercent === undefined) {
|
|
791
|
+
return {
|
|
792
|
+
account,
|
|
793
|
+
kind: "error",
|
|
794
|
+
summary: "no model quota data returned",
|
|
795
|
+
details: [
|
|
796
|
+
`account: ${account.displayName}`,
|
|
797
|
+
`provider: ${account.providerName}`,
|
|
798
|
+
"status: error",
|
|
799
|
+
...(projectId ? [`project: ${projectId}`] : []),
|
|
800
|
+
"details: Google returned no usable model quota data",
|
|
801
|
+
`endpoint: ${snapshot.endpoint}`,
|
|
802
|
+
],
|
|
803
|
+
score: 0,
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
const classification = classifyGoogleQuotaKind(snapshot);
|
|
808
|
+
return {
|
|
809
|
+
account,
|
|
810
|
+
kind: classification.kind,
|
|
811
|
+
summary: `${getGoogleQuotaBucketLabel(account, snapshot.models.length)} | bottleneck ${formatRemainingPercent(snapshot.worstRemainingPercent)} | ${formatQuotaKind(classification.kind)}`,
|
|
812
|
+
details: formatGoogleQuotaDetails(account, snapshot, classification.kind),
|
|
813
|
+
score: classification.score,
|
|
814
|
+
};
|
|
815
|
+
} catch (error: unknown) {
|
|
816
|
+
if (signal?.aborted || isAbortError(error)) throw error;
|
|
817
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
818
|
+
return {
|
|
819
|
+
account,
|
|
820
|
+
kind: "error",
|
|
821
|
+
summary: message,
|
|
822
|
+
details: buildGoogleQuotaErrorDetails(account, message, projectId),
|
|
823
|
+
score: 0,
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
export function normalizeQuotaAllowedProviderNames(cwd: string): string[] | undefined {
|
|
829
|
+
const project = loadProjectConfig(cwd);
|
|
830
|
+
if (!project?.allowedSubs || project.allowedSubs.length === 0) return undefined;
|
|
831
|
+
const normalized = [...new Set(project.allowedSubs.map((value) => value.trim()).filter(Boolean))];
|
|
832
|
+
return normalized.length > 0 ? normalized : undefined;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
export function collectQuotaAccounts(ctx: ExtensionContext, authStorage: AuthStorage): QuotaAccount[] {
|
|
836
|
+
const config = loadGlobalConfig();
|
|
837
|
+
const envEntries = parseEnvConfig();
|
|
838
|
+
const allSubs = normalizeEntries(mergeConfigs(config, envEntries));
|
|
839
|
+
const allowedProviderNames = normalizeQuotaAllowedProviderNames(ctx.cwd);
|
|
840
|
+
const allowed = allowedProviderNames ? new Set(allowedProviderNames) : undefined;
|
|
841
|
+
const seen = new Set<string>();
|
|
842
|
+
const accounts: QuotaAccount[] = [];
|
|
843
|
+
const pushAccount = (providerName: string, displayName: string) => {
|
|
844
|
+
if (allowed && !allowed.has(providerName)) return;
|
|
845
|
+
if (seen.has(providerName)) return;
|
|
846
|
+
seen.add(providerName);
|
|
847
|
+
accounts.push({
|
|
848
|
+
providerName,
|
|
849
|
+
baseProvider: getBaseProvider(providerName) || providerName,
|
|
850
|
+
displayName,
|
|
851
|
+
auth: authStorage.get(providerName) as AuthStorageEntry | undefined,
|
|
852
|
+
});
|
|
853
|
+
};
|
|
854
|
+
|
|
855
|
+
for (const checker of PROVIDER_QUOTA_CHECKERS) {
|
|
856
|
+
if (authStorage.hasAuth(checker.baseProvider)) {
|
|
857
|
+
pushAccount(
|
|
858
|
+
checker.baseProvider,
|
|
859
|
+
PROVIDER_TEMPLATES[checker.baseProvider]?.displayName || checker.baseProvider,
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
for (const entry of allSubs) {
|
|
863
|
+
if (entry.provider !== checker.baseProvider) continue;
|
|
864
|
+
pushAccount(subProviderName(entry), subDisplayName(entry));
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
return accounts;
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
export const codexQuotaChecker: ProviderQuotaChecker = {
|
|
872
|
+
baseProvider: "openai-codex",
|
|
873
|
+
async check(account: QuotaAccount, authStorage: AuthStorage, signal?: AbortSignal): Promise<QuotaCheckResult> {
|
|
874
|
+
const auth = account.auth;
|
|
875
|
+
if (!auth || auth.type !== "oauth" || typeof auth.access !== "string" || auth.access.length === 0) {
|
|
876
|
+
return {
|
|
877
|
+
account,
|
|
878
|
+
kind: "missing-auth",
|
|
879
|
+
summary: "not logged in",
|
|
880
|
+
details: [
|
|
881
|
+
`account: ${account.displayName}`,
|
|
882
|
+
`provider: ${account.providerName}`,
|
|
883
|
+
"status: not logged in",
|
|
884
|
+
"login: use /multi-auth login or /login to authenticate this account",
|
|
885
|
+
],
|
|
886
|
+
score: 0,
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
const tokenMetadata = getCodexTokenMetadata(auth.access);
|
|
891
|
+
const accountId = typeof auth.accountId === "string" && auth.accountId.length > 0
|
|
892
|
+
? auth.accountId
|
|
893
|
+
: tokenMetadata.accountId;
|
|
894
|
+
const baseUrl = (process.env.CHATGPT_BASE_URL || DEFAULT_CODEX_USAGE_BASE_URL).replace(/\/+$/, "");
|
|
895
|
+
const headers = new Headers({
|
|
896
|
+
Authorization: `Bearer ${auth.access}`,
|
|
897
|
+
Accept: "application/json",
|
|
898
|
+
"User-Agent": "omp-multi-auth",
|
|
899
|
+
});
|
|
900
|
+
if (accountId) {
|
|
901
|
+
headers.set("chatgpt-account-id", accountId);
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
try {
|
|
905
|
+
const response = await fetch(`${baseUrl}/wham/usage`, {
|
|
906
|
+
method: "GET",
|
|
907
|
+
headers,
|
|
908
|
+
signal,
|
|
909
|
+
});
|
|
910
|
+
if (!response.ok) {
|
|
911
|
+
const error = await readResponseError(response);
|
|
912
|
+
return {
|
|
913
|
+
account,
|
|
914
|
+
kind: "error",
|
|
915
|
+
summary: error,
|
|
916
|
+
details: [
|
|
917
|
+
`account: ${account.displayName}`,
|
|
918
|
+
`provider: ${account.providerName}`,
|
|
919
|
+
`status: error`,
|
|
920
|
+
`details: ${error}`,
|
|
921
|
+
],
|
|
922
|
+
score: 0,
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
const snapshot = parseCodexUsageSnapshot(await response.json());
|
|
927
|
+
if (!snapshot.email && tokenMetadata.email) snapshot.email = tokenMetadata.email;
|
|
928
|
+
if ((!snapshot.planType || snapshot.planType === "unknown") && tokenMetadata.planType) {
|
|
929
|
+
snapshot.planType = tokenMetadata.planType;
|
|
930
|
+
}
|
|
931
|
+
const fiveHourLeft = getCodexWindowRemaining(snapshot.fiveHour);
|
|
932
|
+
const weeklyLeft = getCodexWindowRemaining(snapshot.weekly);
|
|
933
|
+
const classification = classifyCodexQuotaKind(snapshot);
|
|
934
|
+
const summary = [
|
|
935
|
+
snapshot.planType !== "unknown" ? snapshot.planType : "plan unknown",
|
|
936
|
+
`5h ${formatRemainingPercent(fiveHourLeft)} (${formatResetShort(snapshot.fiveHour?.resetAt)})`,
|
|
937
|
+
`7d ${formatRemainingPercent(weeklyLeft)} (${formatResetShort(snapshot.weekly?.resetAt)})`,
|
|
938
|
+
formatQuotaKind(classification.kind),
|
|
939
|
+
].join(" | ");
|
|
940
|
+
const details = [
|
|
941
|
+
`account: ${account.displayName}`,
|
|
942
|
+
`provider: ${account.providerName}`,
|
|
943
|
+
`status: ${formatQuotaKind(classification.kind)}`,
|
|
944
|
+
`plan: ${snapshot.planType}`,
|
|
945
|
+
];
|
|
946
|
+
if (snapshot.email) {
|
|
947
|
+
details.push(`email: ${snapshot.email}`);
|
|
948
|
+
}
|
|
949
|
+
details.push(
|
|
950
|
+
`5-hour window: ${formatRemainingPercent(fiveHourLeft)} left, resets ${formatResetLong(snapshot.fiveHour?.resetAt)}`,
|
|
951
|
+
`7-day window: ${formatRemainingPercent(weeklyLeft)} left, resets ${formatResetLong(snapshot.weekly?.resetAt)}`,
|
|
952
|
+
`endpoint: ${baseUrl}/wham/usage`,
|
|
953
|
+
);
|
|
954
|
+
return {
|
|
955
|
+
account,
|
|
956
|
+
kind: classification.kind,
|
|
957
|
+
summary,
|
|
958
|
+
details,
|
|
959
|
+
score: classification.score,
|
|
960
|
+
};
|
|
961
|
+
} catch (error: unknown) {
|
|
962
|
+
if (signal?.aborted || isAbortError(error)) throw error;
|
|
963
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
964
|
+
return {
|
|
965
|
+
account,
|
|
966
|
+
kind: "error",
|
|
967
|
+
summary: message,
|
|
968
|
+
details: [
|
|
969
|
+
`account: ${account.displayName}`,
|
|
970
|
+
`provider: ${account.providerName}`,
|
|
971
|
+
"status: error",
|
|
972
|
+
`details: ${message}`,
|
|
973
|
+
],
|
|
974
|
+
score: 0,
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
},
|
|
978
|
+
};
|
|
979
|
+
|
|
980
|
+
export const googleGeminiCliQuotaChecker: ProviderQuotaChecker = {
|
|
981
|
+
baseProvider: "google-gemini-cli",
|
|
982
|
+
async check(account: QuotaAccount, authStorage: AuthStorage, signal?: AbortSignal): Promise<QuotaCheckResult> {
|
|
983
|
+
return checkGoogleQuotaAccount(account, fetchGoogleGeminiQuotaSnapshot, authStorage, signal);
|
|
984
|
+
},
|
|
985
|
+
};
|
|
986
|
+
|
|
987
|
+
export const googleAntigravityQuotaChecker: ProviderQuotaChecker = {
|
|
988
|
+
baseProvider: "google-antigravity",
|
|
989
|
+
async check(account: QuotaAccount, authStorage: AuthStorage, signal?: AbortSignal): Promise<QuotaCheckResult> {
|
|
990
|
+
return checkGoogleQuotaAccount(account, fetchGoogleAntigravityQuotaSnapshot, authStorage, signal);
|
|
991
|
+
},
|
|
992
|
+
};
|
|
993
|
+
|
|
994
|
+
export const PROVIDER_QUOTA_CHECKERS: ProviderQuotaChecker[] = [
|
|
995
|
+
codexQuotaChecker,
|
|
996
|
+
googleGeminiCliQuotaChecker,
|
|
997
|
+
googleAntigravityQuotaChecker,
|
|
998
|
+
];
|
|
999
|
+
|
|
1000
|
+
export async function showQuotaDetails(
|
|
1001
|
+
ctx: ExtensionCommandContext,
|
|
1002
|
+
result: QuotaCheckResult,
|
|
1003
|
+
): Promise<void> {
|
|
1004
|
+
await showWrappedSelect(ctx, {
|
|
1005
|
+
title: `Limit Details: ${result.account.displayName}`,
|
|
1006
|
+
subtitle: "Press Enter or Escape to go back to the limits list.",
|
|
1007
|
+
items: result.details.map((detail, index) => ({ value: `${index}:${detail}`, label: detail })),
|
|
1008
|
+
confirmHint: "back",
|
|
1009
|
+
cancelHint: "back",
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
export async function handleSubsLimits(ctx: ExtensionCommandContext): Promise<void> {
|
|
1014
|
+
const authStorage = getAuthStorage(ctx);
|
|
1015
|
+
const allowedProviderNames = normalizeQuotaAllowedProviderNames(ctx.cwd);
|
|
1016
|
+
const accounts = collectQuotaAccounts(ctx, authStorage);
|
|
1017
|
+
if (accounts.length === 0) {
|
|
1018
|
+
const suffix = allowedProviderNames && allowedProviderNames.length > 0
|
|
1019
|
+
? ` for this project restriction (${allowedProviderNames.join(", ")})`
|
|
1020
|
+
: "";
|
|
1021
|
+
ctx.ui.notify(
|
|
1022
|
+
`No supported subscription limits are available yet${suffix}. Login to a supported provider first.`,
|
|
1023
|
+
"info",
|
|
1024
|
+
);
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
const results = await loadQuotaResults(ctx, accounts, authStorage);
|
|
1029
|
+
if (!results) {
|
|
1030
|
+
ctx.ui.notify("Cancelled subscription limit check.", "info");
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
if (results.length === 0) {
|
|
1034
|
+
ctx.ui.notify("No supported quota checks matched the configured subscriptions.", "info");
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
let preferredProviderName = ctx.model?.provider;
|
|
1039
|
+
while (true) {
|
|
1040
|
+
const selected = await selectQuotaResult(ctx, results, preferredProviderName);
|
|
1041
|
+
if (!selected) return;
|
|
1042
|
+
preferredProviderName = selected.account.providerName;
|
|
1043
|
+
await showQuotaDetails(ctx, selected);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// ==========================================================================
|
|
1048
|
+
// Config persistence (~/.omp/agent/multi-auth.json)
|