import { fetchJson } from "../http.ts"; import { amount, finite, isoTime, label, object, percent, windowBucket, } from "../parse.ts"; import type { ProviderQuota, QuotaBucket, QuotaProvider } from "../types.ts"; /** Best effort: internal snapshots vary across legacy request and credit plans. */ export function parseCopilot(data: unknown): ProviderQuota { const d = object(data); const buckets: QuotaBucket[] = []; for (const [key, raw] of Object.entries(object(d["quota_snapshots"])).slice( 0, 256, )) { if (raw == null) continue; const q = object(raw); const title = ( { premium_interactions: "Premium requests", chat: "Chat", completions: "Completions", } as Record )[key] ?? label(key.replaceAll("_", " ")) ?? "Quota"; const knownRequests = [ "premium_interactions", "chat", "completions", ].includes(key); let value = q["unlimited"] === true ? { state: "unlimited" as const } : amount( knownRequests ? "requests" : "unknown", finite(q["used"]), finite(q["entitlement"]), finite(q["remaining"]), ); const remainingPercent = finite(q["percent_remaining"]); if (remainingPercent !== undefined && value.state !== "unlimited") { if (value.state === "measured") value.usedPercent = Math.min(100, Math.max(0, 100 - remainingPercent)); else value = percent(100 - remainingPercent); } const bucket = windowBucket( key, title, value, undefined, isoTime(q["quota_reset_at"]) ?? isoTime(d["quota_reset_date_utc"]), ); bucket.period = { label: "Monthly", resetsAt: bucket.period?.resetsAt }; buckets.push(bucket); } return { provider: "github-copilot", name: "GitHub Copilot", buckets, observedAt: Date.now(), }; } export const copilot: QuotaProvider = { name: "GitHub Copilot", async fetch(key) { return parseCopilot( await 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}`, }, }), ); }, };