quota: add provider quota parsers
2d9e59a74fc65abb69e81cd49b0e6d8217c334e0
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 3bdd96aa7ec1
bugabingas pi extensions
2d9e59a74fc65abb69e81cd49b0e6d8217c334e0
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+194 / −78 text lines
+21 / −0 text lines
import { __test } from "../index.ts"; it("parses stolen provider quota shapes", () => { expect(__test.parseCopilot({ quota_snapshots: { premium_interactions: { percent_remaining: 75 }, chat: { percent_remaining: 40 } } })).toMatchObject({ name: "GitHub Copilot", fiveH: { used: 25, total: 100, remaining: 75 }, weekly: { used: 60, total: 100, remaining: 40 }, }); expect(__test.parseGemini({ buckets: [{ modelId: "gemini-pro", remainingFraction: 0.25 }, { modelId: "gemini-flash", remainingFraction: 0.75 }] })).toMatchObject({ name: "Gemini", fiveH: { used: 75, total: 100, remaining: 25 }, weekly: { used: 25, total: 100, remaining: 75 }, }); expect(__test.parseMinimax({ base_resp: { status_code: 0, status_msg: "" }, model_remains: [{ model_name: "MiniMax-M2", current_interval_total_count: 100, current_interval_usage_count: 30, current_weekly_total_count: 1000, current_weekly_usage_count: 800 }] })).toMatchObject({ name: "MiniMax", fiveH: { used: 70, total: 100, remaining: 30 }, weekly: { used: 200, total: 1000, remaining: 800 }, }); });+173 / −78 text lines
* Supports: Anthropic, OpenAI Codex, MiniMax, Zai, Kimi. * Supports: Anthropic, OpenAI Codex, GitHub Copilot, Gemini CLI, MiniMax, MiniMax CN, Zai, Kimi.const REFRESH_MS = 5 * 60_000;interface CopilotResponse { quota_reset_date_utc?: string; quota_snapshots?: { premium_interactions?: { percent_remaining?: number }; chat?: { unlimited?: boolean; percent_remaining?: number }; };}interface GeminiResponse { buckets?: Array<{ modelId?: string; remainingFraction?: number }>;}async function fetchCopilot(key: string) { return fetchJson("https://api.github.com/copilot_internal/user", { headers: { "Editor-Version": "vscode/1.96.2", "User-Agent": "GitHubCopilotChat/0.26.7", "X-Github-Api-Version": "2025-04-01", Accept: "application/json", Authorization: `token ${key}`, }, }) as Promise<CopilotResponse>;}async function fetchGemini(key: string) { return fetchJson("https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota", { method: "POST", headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, body: "{}", }) as Promise<GeminiResponse>;}function parseMinimax(data: MinimaxResponse): ProviderUsage { const models = data.model_remains.filter(m => m.model_name.includes("MiniMax-M")); // API field is misleadingly named — it's actually the remaining count const remaining = models.reduce((s, m) => s + m.current_interval_usage_count, 0); const total = models.reduce((s, m) => s + m.current_interval_total_count, 0); const resetAt = models.find(m => m.remains_time)?.remains_time;function parseMinimax(data: MinimaxResponse, name = "MiniMax"): ProviderUsage { const models = data.model_remains.filter(m => /^minimax-m/i.test(m.model_name) || /minimax/i.test(m.model_name)); const bucket = models[0] ?? data.model_remains[0]; if (!bucket) return { name, fiveH: { used: 0, total: 0, remaining: 0 }, weekly: { used: 0, total: 0, remaining: 0 } }; // API field is misleadingly named — usage_count is remaining count. const total = Number(bucket.current_interval_total_count) || 0; const remaining = Number(bucket.current_interval_usage_count) || 0; const weeklyTotal = Number(bucket.current_weekly_total_count) || 0; const weeklyRemaining = Number(bucket.current_weekly_usage_count) || 0; name: "MiniMax", fiveH: { used: total - remaining, total, remaining, resetAt: resetAt ? Date.now() + resetAt : undefined }, weekly: { used: 0, total: 0, remaining: 0 }, name, fiveH: { used: total - remaining, total, remaining, resetAt: parseDateish(bucket.end_time) || (bucket.remains_time ? Date.now() + bucket.remains_time : undefined) }, weekly: { used: weeklyTotal - weeklyRemaining, total: weeklyTotal, remaining: weeklyRemaining, resetAt: parseDateish(bucket.weekly_end_time) || undefined }, };}function parseCopilot(data: CopilotResponse): ProviderUsage { const resetAt = parseDateish(data.quota_reset_date_utc) || undefined; const premiumLeft = Number(data.quota_snapshots?.premium_interactions?.percent_remaining ?? 0); const chat = data.quota_snapshots?.chat; const chatLeft = chat?.unlimited ? 100 : Number(chat?.percent_remaining ?? 0); return { name: "GitHub Copilot", fiveH: { used: Math.max(0, 100 - premiumLeft), total: 100, remaining: premiumLeft, resetAt }, weekly: { used: Math.max(0, 100 - chatLeft), total: chat?.unlimited ? 0 : 100, remaining: chatLeft, resetAt }, };}function parseGemini(data: GeminiResponse): ProviderUsage { let proLeft = 1; let flashLeft = 1; let hasPro = false; let hasFlash = false; for (const bucket of data.buckets ?? []) { const model = bucket.modelId?.toLowerCase() ?? ""; const left = Number(bucket.remainingFraction ?? 1); if (model.includes("pro")) { hasPro = true; proLeft = Math.min(proLeft, left); } if (model.includes("flash")) { hasFlash = true; flashLeft = Math.min(flashLeft, left); } } return { name: "Gemini", fiveH: hasPro ? { used: (1 - proLeft) * 100, total: 100, remaining: proLeft * 100 } : { used: 0, total: 0, remaining: 0 }, weekly: hasFlash ? { used: (1 - flashLeft) * 100, total: 100, remaining: flashLeft * 100 } : { used: 0, total: 0, remaining: 0 }, const cache = new Map<string, ProviderUsage>(); "minimax-cn": "MiniMax CN", function emptyProvider(name: string): ProviderUsage { return { name, fiveH: { used: 0, total: 0, remaining: 0 }, weekly: { used: 0, total: 0, remaining: 0 } }; async function keepCached(name: string, run: () => Promise<ProviderUsage>): Promise<ProviderUsage | undefined> { try { const usage = await run(); if (usage.fiveH.total > 0 || usage.weekly.total > 0) cache.set(name, usage); return usage; } catch { return cache.get(name); } } function activeProviderKey(ctx: ExtensionContext): string | undefined { return ctx.model?.provider?.toLowerCase(); } async function codexAccountId(ctx: ExtensionContext): Promise<string | undefined> { try { const cred = ctx.modelRegistry.authStorage.get("openai-codex") as any; if (typeof cred?.accountId === "string") return cred.accountId; } catch {} try { const raw = JSON.parse(readFileSync(join(homedir(), ".codex", "auth.json"), "utf8")) as any; return raw?.tokens?.account_id ?? raw?.tokens?.accountId; } catch {} return undefined; } async function fetchActive(ctx: ExtensionContext, key: string): Promise<ProviderUsage | undefined> { if (key === "anthropic") { const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key); return apiKey ? keepCached("Anthropic", async () => parseAnthropic(await fetchAnthropic(apiKey))) : undefined; } if (key === "github-copilot") { const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key); return apiKey ? keepCached("GitHub Copilot", async () => parseCopilot(await fetchCopilot(apiKey))) : undefined; } if (key === "google-gemini-cli") { const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key); return apiKey ? keepCached("Gemini", async () => parseGemini(await fetchGemini(apiKey))) : undefined; } if (key === "openai-codex") { const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key); const accountId = await codexAccountId(ctx); return apiKey && accountId ? keepCached("OpenAI Codex", async () => parseCodex(await fetchCodex(apiKey, accountId))) : undefined; } if (key === "minimax") { const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key); return apiKey ? keepCached("MiniMax", async () => parseMinimax(await fetchMinimax(apiKey))) : undefined; } if (key === "minimax-cn") { const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key); return apiKey ? keepCached("MiniMax CN", async () => parseMinimax(await fetchMinimax(apiKey, true), "MiniMax CN")) : undefined; } if (key === "zai") { const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key); return apiKey ? keepCached("Zai", async () => parseZai(await fetchZai(apiKey))) : undefined; } if (key === "kimi-coding") { const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key); return apiKey ? keepCached("Kimi", async () => parseKimi(await fetchKimi(apiKey))) : undefined; } return undefined; const results: ProviderUsage[] = []; const auth = ctx.modelRegistry.authStorage; // Anthropic (OAuth token) const anthKey = await ctx.modelRegistry.getApiKeyForProvider("anthropic"); if (anthKey) { try { results.push(parseAnthropic(await fetchAnthropic(anthKey))); } catch { results.push(emptyProvider("Anthropic")); } } // OpenAI Codex (needs key + accountId) const codexKey = await ctx.modelRegistry.getApiKeyForProvider("openai-codex"); if (codexKey) { let accountId: string | undefined; try { const cred = auth.get("openai-codex") as any; accountId = typeof cred?.accountId === "string" ? cred.accountId : undefined; } catch {} if (!accountId) { // Fallback: read from ~/.codex/auth.json try { const raw = JSON.parse(readFileSync(join(homedir(), ".codex", "auth.json"), "utf8")) as any; accountId = raw?.tokens?.account_id ?? raw?.tokens?.accountId; } catch {} } if (accountId) { try { results.push(parseCodex(await fetchCodex(codexKey, accountId))); } catch { results.push(emptyProvider("OpenAI Codex")); } } } // MiniMax const mmKey = await ctx.modelRegistry.getApiKeyForProvider("minimax"); if (mmKey) { try { results.push(parseMinimax(await fetchMinimax(mmKey))); } catch { results.push(emptyProvider("MiniMax")); } } // Zai const zaiKey = await ctx.modelRegistry.getApiKeyForProvider("zai"); if (zaiKey) { try { results.push(parseZai(await fetchZai(zaiKey))); } catch { results.push(emptyProvider("Zai")); } } // Kimi const kimiKey = await ctx.modelRegistry.getApiKeyForProvider("kimi-coding"); if (kimiKey) { try { results.push(parseKimi(await fetchKimi(kimiKey))); } catch { results.push(emptyProvider("Kimi")); } } providers = results; if (!force && fetchedAt && Date.now() - fetchedAt < 60_000) return; if (!force && fetchedAt && Date.now() - fetchedAt < REFRESH_MS) return; for (const p of providers.filter(p => p.fiveH.total > 0)) { for (const p of providers.filter(p => p.fiveH.total > 0).filter(p => !active || p.name.startsWith(active))) { variants: [`${label} ${used}%`, `${used}%`], for (const p of providers) { for (const p of providers.filter(p => !active || p.name.startsWith(active))) { ctx.ui.setWidget("usage", widgetLines(ctx)); try { await getOrFetch(ctx, true); updateFooter(ctx); } catch {} stopRefresh(); startRefresh(ctx); pi.on("model_select", async (_e, ctx) => updateFooter(ctx));