repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

quota: add provider quota parsers

2d9e59a74fc65abb69e81cd49b0e6d8217c334e0

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

+194 / −78 text lines

Diff layout

extensions/quota/__tests__/harness.test.ts

Modified

+21 / −0 text lines

11import { afterEach, describe, expect, it } from "bun:test";
22import path from "node:path";
33import { createTestSession, type TestSession } from "@marcfargas/pi-test-harness";
4import { __test } from "../index.ts";
56describe("quota pi-test-harness", () => {
67 let t: TestSession | undefined;
1718 expect(t.session.extensionRunner.extensions).toHaveLength(1);
1819 expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
1920 }, 15000);
22 it("parses stolen provider quota shapes", () => {
23 expect(__test.parseCopilot({ quota_snapshots: { premium_interactions: { percent_remaining: 75 }, chat: { percent_remaining: 40 } } })).toMatchObject({
24 name: "GitHub Copilot",
25 fiveH: { used: 25, total: 100, remaining: 75 },
26 weekly: { used: 60, total: 100, remaining: 40 },
27 });
29 expect(__test.parseGemini({ buckets: [{ modelId: "gemini-pro", remainingFraction: 0.25 }, { modelId: "gemini-flash", remainingFraction: 0.75 }] })).toMatchObject({
30 name: "Gemini",
31 fiveH: { used: 75, total: 100, remaining: 25 },
32 weekly: { used: 25, total: 100, remaining: 75 },
33 });
35 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({
36 name: "MiniMax",
37 fiveH: { used: 70, total: 100, remaining: 30 },
38 weekly: { used: 200, total: 1000, remaining: 800 },
39 });
40 });
2041});

extensions/quota/index.ts

Modified

+173 / −78 text lines

11/**
22 * /quota — subscription plan usage across providers.
33 * Emits quota summary into footer llm zone; /quota toggles detailed widget.
4 * Supports: Anthropic, OpenAI Codex, MiniMax, Zai, Kimi.
4 * Supports: Anthropic, OpenAI Codex, GitHub Copilot, Gemini CLI, MiniMax, MiniMax CN, Zai, Kimi.
55 * Providers without configured keys are silently skipped.
66 */
1313const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
1414const STATUS_ID = "quota";
15const REFRESH_MS = 5 * 60_000;
1617// ── Types ─────────────────────────────────────────────────────────────────
2122 model_name: string;
2223 current_interval_total_count: number;
2324 current_interval_usage_count: number;
25 current_weekly_total_count?: number;
26 current_weekly_usage_count?: number;
2427 remains_time?: number;
28 start_time?: number;
29 end_time?: number;
30 weekly_start_time?: number;
31 weekly_end_time?: number;
2532 }>;
35interface CopilotResponse {
36 quota_reset_date_utc?: string;
37 quota_snapshots?: {
38 premium_interactions?: { percent_remaining?: number };
39 chat?: { unlimited?: boolean; percent_remaining?: number };
40 };
41}
43interface GeminiResponse {
44 buckets?: Array<{ modelId?: string; remainingFraction?: number }>;
45}
2847interface ZaiResponse {
2948 code: number;
3049 data: {
100119 });
103async function fetchMinimax(key: string) {
104 const r = await fetch("https://api.minimax.io/v1/api/openplatform/coding_plan/remains", {
122async function fetchMinimax(key: string, cn = false) {
123 const endpoint = cn
124 ? "https://api.minimaxi.com/v1/api/openplatform/coding_plan/remains"
125 : "https://api.minimax.io/v1/api/openplatform/coding_plan/remains";
126 const r = await fetch(endpoint, {
105127 headers: {
106128 Authorization: `Bearer ${key}`,
107129 "Content-Type": "application/json",
115137 return data;
140async function fetchCopilot(key: string) {
141 return fetchJson("https://api.github.com/copilot_internal/user", {
142 headers: {
143 "Editor-Version": "vscode/1.96.2",
144 "User-Agent": "GitHubCopilotChat/0.26.7",
145 "X-Github-Api-Version": "2025-04-01",
146 Accept: "application/json",
147 Authorization: `token ${key}`,
148 },
149 }) as Promise<CopilotResponse>;
150}
152async function fetchGemini(key: string) {
153 return fetchJson("https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota", {
154 method: "POST",
155 headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
156 body: "{}",
157 }) as Promise<GeminiResponse>;
158}
118160async function fetchZai(key: string) {
119161 const r = await fetch("https://api.z.ai/api/monitor/usage/quota/limit", {
120162 headers: { Authorization: key, "Content-Type": "application/json" },
182224 };
185function parseMinimax(data: MinimaxResponse): ProviderUsage {
186 const models = data.model_remains.filter(m => m.model_name.includes("MiniMax-M"));
187 // API field is misleadingly named — it's actually the remaining count
188 const remaining = models.reduce((s, m) => s + m.current_interval_usage_count, 0);
189 const total = models.reduce((s, m) => s + m.current_interval_total_count, 0);
190 const resetAt = models.find(m => m.remains_time)?.remains_time;
227function parseMinimax(data: MinimaxResponse, name = "MiniMax"): ProviderUsage {
228 const models = data.model_remains.filter(m => /^minimax-m/i.test(m.model_name) || /minimax/i.test(m.model_name));
229 const bucket = models[0] ?? data.model_remains[0];
230 if (!bucket) return { name, fiveH: { used: 0, total: 0, remaining: 0 }, weekly: { used: 0, total: 0, remaining: 0 } };
232 // API field is misleadingly named — usage_count is remaining count.
233 const total = Number(bucket.current_interval_total_count) || 0;
234 const remaining = Number(bucket.current_interval_usage_count) || 0;
235 const weeklyTotal = Number(bucket.current_weekly_total_count) || 0;
236 const weeklyRemaining = Number(bucket.current_weekly_usage_count) || 0;
191237 return {
192 name: "MiniMax",
193 fiveH: { used: total - remaining, total, remaining, resetAt: resetAt ? Date.now() + resetAt : undefined },
194 weekly: { used: 0, total: 0, remaining: 0 },
238 name,
239 fiveH: { used: total - remaining, total, remaining, resetAt: parseDateish(bucket.end_time) || (bucket.remains_time ? Date.now() + bucket.remains_time : undefined) },
240 weekly: { used: weeklyTotal - weeklyRemaining, total: weeklyTotal, remaining: weeklyRemaining, resetAt: parseDateish(bucket.weekly_end_time) || undefined },
241 };
242}
244function parseCopilot(data: CopilotResponse): ProviderUsage {
245 const resetAt = parseDateish(data.quota_reset_date_utc) || undefined;
246 const premiumLeft = Number(data.quota_snapshots?.premium_interactions?.percent_remaining ?? 0);
247 const chat = data.quota_snapshots?.chat;
248 const chatLeft = chat?.unlimited ? 100 : Number(chat?.percent_remaining ?? 0);
249 return {
250 name: "GitHub Copilot",
251 fiveH: { used: Math.max(0, 100 - premiumLeft), total: 100, remaining: premiumLeft, resetAt },
252 weekly: { used: Math.max(0, 100 - chatLeft), total: chat?.unlimited ? 0 : 100, remaining: chatLeft, resetAt },
253 };
254}
256function parseGemini(data: GeminiResponse): ProviderUsage {
257 let proLeft = 1;
258 let flashLeft = 1;
259 let hasPro = false;
260 let hasFlash = false;
261 for (const bucket of data.buckets ?? []) {
262 const model = bucket.modelId?.toLowerCase() ?? "";
263 const left = Number(bucket.remainingFraction ?? 1);
264 if (model.includes("pro")) { hasPro = true; proLeft = Math.min(proLeft, left); }
265 if (model.includes("flash")) { hasFlash = true; flashLeft = Math.min(flashLeft, left); }
266 }
267 return {
268 name: "Gemini",
269 fiveH: hasPro ? { used: (1 - proLeft) * 100, total: 100, remaining: proLeft * 100 } : { used: 0, total: 0, remaining: 0 },
270 weekly: hasFlash ? { used: (1 - flashLeft) * 100, total: 100, remaining: flashLeft * 100 } : { used: 0, total: 0, remaining: 0 },
195271 };
262338 let fetchPromise: Promise<void> | null = null;
263339 let widgetVisible = false;
264340 let refreshTimer: ReturnType<typeof setInterval> | null = null;
341 const cache = new Map<string, ProviderUsage>();
266343 const PROVIDERS: Record<string, string> = {
267344 anthropic: "Anthropic",
268345 "openai-codex": "OpenAI Codex",
346 "github-copilot": "GitHub Copilot",
347 "google-gemini-cli": "Gemini",
269348 minimax: "MiniMax",
349 "minimax-cn": "MiniMax CN",
270350 zai: "Zai",
271351 "kimi-coding": "Kimi",
272352 };
274 function emptyProvider(name: string): ProviderUsage {
275 return { name, fiveH: { used: 0, total: 0, remaining: 0 }, weekly: { used: 0, total: 0, remaining: 0 } };
354 async function keepCached(name: string, run: () => Promise<ProviderUsage>): Promise<ProviderUsage | undefined> {
355 try {
356 const usage = await run();
357 if (usage.fiveH.total > 0 || usage.weekly.total > 0) cache.set(name, usage);
358 return usage;
359 } catch {
360 return cache.get(name);
361 }
362 }
364 function activeProviderKey(ctx: ExtensionContext): string | undefined {
365 return ctx.model?.provider?.toLowerCase();
366 }
368 async function codexAccountId(ctx: ExtensionContext): Promise<string | undefined> {
369 try {
370 const cred = ctx.modelRegistry.authStorage.get("openai-codex") as any;
371 if (typeof cred?.accountId === "string") return cred.accountId;
372 } catch {}
373 try {
374 const raw = JSON.parse(readFileSync(join(homedir(), ".codex", "auth.json"), "utf8")) as any;
375 return raw?.tokens?.account_id ?? raw?.tokens?.accountId;
376 } catch {}
377 return undefined;
378 }
380 async function fetchActive(ctx: ExtensionContext, key: string): Promise<ProviderUsage | undefined> {
381 if (key === "anthropic") {
382 const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key);
383 return apiKey ? keepCached("Anthropic", async () => parseAnthropic(await fetchAnthropic(apiKey))) : undefined;
384 }
385 if (key === "github-copilot") {
386 const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key);
387 return apiKey ? keepCached("GitHub Copilot", async () => parseCopilot(await fetchCopilot(apiKey))) : undefined;
388 }
389 if (key === "google-gemini-cli") {
390 const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key);
391 return apiKey ? keepCached("Gemini", async () => parseGemini(await fetchGemini(apiKey))) : undefined;
392 }
393 if (key === "openai-codex") {
394 const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key);
395 const accountId = await codexAccountId(ctx);
396 return apiKey && accountId ? keepCached("OpenAI Codex", async () => parseCodex(await fetchCodex(apiKey, accountId))) : undefined;
397 }
398 if (key === "minimax") {
399 const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key);
400 return apiKey ? keepCached("MiniMax", async () => parseMinimax(await fetchMinimax(apiKey))) : undefined;
401 }
402 if (key === "minimax-cn") {
403 const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key);
404 return apiKey ? keepCached("MiniMax CN", async () => parseMinimax(await fetchMinimax(apiKey, true), "MiniMax CN")) : undefined;
405 }
406 if (key === "zai") {
407 const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key);
408 return apiKey ? keepCached("Zai", async () => parseZai(await fetchZai(apiKey))) : undefined;
409 }
410 if (key === "kimi-coding") {
411 const apiKey = await ctx.modelRegistry.getApiKeyForProvider(key);
412 return apiKey ? keepCached("Kimi", async () => parseKimi(await fetchKimi(apiKey))) : undefined;
413 }
414 return undefined;
276415 }
278417 async function fetchAll(ctx: ExtensionContext) {
279 const results: ProviderUsage[] = [];
280 const auth = ctx.modelRegistry.authStorage;
282 // Anthropic (OAuth token)
283 const anthKey = await ctx.modelRegistry.getApiKeyForProvider("anthropic");
284 if (anthKey) {
285 try { results.push(parseAnthropic(await fetchAnthropic(anthKey))); }
286 catch { results.push(emptyProvider("Anthropic")); }
287 }
289 // OpenAI Codex (needs key + accountId)
290 const codexKey = await ctx.modelRegistry.getApiKeyForProvider("openai-codex");
291 if (codexKey) {
292 let accountId: string | undefined;
293 try {
294 const cred = auth.get("openai-codex") as any;
295 accountId = typeof cred?.accountId === "string" ? cred.accountId : undefined;
296 } catch {}
297 if (!accountId) {
298 // Fallback: read from ~/.codex/auth.json
299 try {
300 const raw = JSON.parse(readFileSync(join(homedir(), ".codex", "auth.json"), "utf8")) as any;
301 accountId = raw?.tokens?.account_id ?? raw?.tokens?.accountId;
302 } catch {}
303 }
304 if (accountId) {
305 try { results.push(parseCodex(await fetchCodex(codexKey, accountId))); }
306 catch { results.push(emptyProvider("OpenAI Codex")); }
307 }
308 }
310 // MiniMax
311 const mmKey = await ctx.modelRegistry.getApiKeyForProvider("minimax");
312 if (mmKey) {
313 try { results.push(parseMinimax(await fetchMinimax(mmKey))); }
314 catch { results.push(emptyProvider("MiniMax")); }
315 }
317 // Zai
318 const zaiKey = await ctx.modelRegistry.getApiKeyForProvider("zai");
319 if (zaiKey) {
320 try { results.push(parseZai(await fetchZai(zaiKey))); }
321 catch { results.push(emptyProvider("Zai")); }
322 }
324 // Kimi
325 const kimiKey = await ctx.modelRegistry.getApiKeyForProvider("kimi-coding");
326 if (kimiKey) {
327 try { results.push(parseKimi(await fetchKimi(kimiKey))); }
328 catch { results.push(emptyProvider("Kimi")); }
329 }
331 providers = results;
418 const key = activeProviderKey(ctx);
419 const usage = key ? await fetchActive(ctx, key) : undefined;
420 if (key !== activeProviderKey(ctx)) return;
421 providers = usage ? [usage] : [];
332422 fetchedAt = Date.now();
333423 }
335425 async function getOrFetch(ctx: ExtensionContext, force = false) {
336 if (!force && fetchedAt && Date.now() - fetchedAt < 60_000) return;
426 if (!force && fetchedAt && Date.now() - fetchedAt < REFRESH_MS) return;
337427 if (fetchPromise) return fetchPromise;
338428 fetchPromise = fetchAll(ctx).finally(() => { fetchPromise = null; });
339429 await fetchPromise;
340430 }
342432 function activeProvider(ctx: ExtensionContext): string | null {
343 const p = ctx.model?.provider;
344 return p ? (PROVIDERS[p.toLowerCase()] ?? p) : null;
433 const p = activeProviderKey(ctx);
434 return p ? (PROVIDERS[p] ?? p) : null;
345435 }
347437 // ── Footer llm segment ──────────────────────────────────────────────────
381471 ctx.ui.setStatus(STATUS_ID, undefined);
382472 const seen = new Set<string>();
384 for (const p of providers.filter(p => p.fiveH.total > 0)) {
474 for (const p of providers.filter(p => p.fiveH.total > 0).filter(p => !active || p.name.startsWith(active))) {
385475 const used = Math.round((p.fiveH.used / p.fiveH.total) * 100);
386476 const isActive = !!active && p.name.startsWith(active);
387477 const label = p.name.split(" ")[0];
394484 id,
395485 icon: isActive ? "●" : "◌",
396486 text: `${label} ${used}%${reset ? ` ↻${reset}` : ""}`,
487 variants: [`${label} ${used}%`, `${used}%`],
397488 color: isActive ? color(used) : "muted",
398489 zone: "llm",
399490 order: 4,
414505 const active = activeProvider(ctx);
415506 const lines: string[] = [];
417 for (const p of providers) {
508 for (const p of providers.filter(p => !active || p.name.startsWith(active))) {
418509 if (p.fiveH.total === 0) continue;
419510 const isActive = active && p.name.startsWith(active);
420511 const label = p.name.split(" ")[0].padEnd(7);
443534 refreshTimer = setInterval(async () => {
444535 try {
445536 await getOrFetch(ctx, true);
446 ctx.ui.setWidget("usage", widgetLines(ctx));
537 updateFooter(ctx);
538 if (widgetVisible) ctx.ui.setWidget("usage", widgetLines(ctx));
447539 } catch {}
448 }, 5000);
540 }, REFRESH_MS);
449541 }
451543 function stopRefresh() {
461553 widgetVisible = !widgetVisible;
462554 if (widgetVisible) {
463555 ctx.ui.setWidget("usage", widgetLines(ctx));
464 startRefresh(ctx);
465 try { await getOrFetch(ctx, true); } catch {}
556 try { await getOrFetch(ctx, true); updateFooter(ctx); } catch {}
466557 ctx.ui.setWidget("usage", widgetLines(ctx));
467558 } else {
468 stopRefresh();
469559 ctx.ui.setWidget("usage", undefined);
470560 }
471561 },
476566 pi.on("session_start", async (_e, ctx) => {
477567 fetchedAt = 0; widgetVisible = false; clearFooter(); ctx.ui.setStatus(STATUS_ID, undefined);
568 startRefresh(ctx);
478569 try { await getOrFetch(ctx); updateFooter(ctx); }
479570 catch { if (!providers.length) { clearFooter(); ctx.ui.setStatus(STATUS_ID, undefined); } }
480571 });
482573 pi.on("agent_start", async (_e, ctx) => updateFooter(ctx));
483574 pi.on("agent_end", async (_e, ctx) => {
575 try { await getOrFetch(ctx); updateFooter(ctx); } catch {}
576 });
577 pi.on("model_select", async (_e, ctx) => {
484578 try { await getOrFetch(ctx, true); updateFooter(ctx); } catch {}
485579 });
486 pi.on("model_select", async (_e, ctx) => updateFooter(ctx));
488581 pi.on("session_shutdown", async (_e, ctx) => {
489582 stopRefresh();
493586 ctx.ui.setWidget("usage", undefined);
494587 });
590export const __test = { parseCopilot, parseGemini, parseMinimax };