1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
// ─── GitHub Copilot Usage Tracking ───────────────────────────
// Uses the internal GitHub Copilot user endpoint (same one the
// official VS Code Copilot extension calls).
export interface CopilotUsageReport {
tokensConsumed?: number;
tokensRemaining?: number;
percentUsed?: number; // 0-100
resetAt?: number; // Unix timestamp ms
plan?: string;
}
export async function fetchCopilotUsage(
token: string,
_baseUrl: string,
): Promise<CopilotUsageReport | null> {
const url = "https://api.github.com/copilot_internal/user";
const headers: Record<string, string> = {
authorization: `Bearer ${token}`,
accept: "application/json",
};
try {
const response = await fetch(url, { headers });
if (!response.ok) return null;
const data = (await response.json()) as Record<string, unknown>;
const plan = typeof data.copilot_plan === "string" ? data.copilot_plan : undefined;
const resetDate = typeof data.quota_reset_date === "string" ? data.quota_reset_date : undefined;
const resetAt = resetDate ? Date.parse(resetDate) : undefined;
const qs = data.quota_snapshots as Record<string, unknown> | undefined;
const pi = qs?.premium_interactions as Record<string, unknown> | undefined;
const entitlement = typeof pi?.entitlement === "number" ? pi.entitlement : undefined;
const remaining = typeof pi?.remaining === "number" ? pi.remaining : undefined;
const percentRemaining =
typeof pi?.percent_remaining === "number" ? pi.percent_remaining : undefined;
if (entitlement === undefined && remaining === undefined) {
return null;
}
const tokensConsumed =
entitlement !== undefined && remaining !== undefined ? entitlement - remaining : undefined;
const percentUsed =
percentRemaining !== undefined
? Math.round((100 - percentRemaining) * 100) / 100
: tokensConsumed !== undefined && entitlement !== undefined && entitlement > 0
? Math.round((tokensConsumed / entitlement) * 10000) / 100
: undefined;
return {
tokensConsumed,
tokensRemaining: remaining,
percentUsed,
resetAt: resetAt && !Number.isNaN(resetAt) ? resetAt : undefined,
plan,
};
} catch {
return null;
}
}
|