New package @magpie-community/opencode-copilot-auth 0.1.0 (provider id
github-copilot), from kurtleee. It adapts opencode-copilot-auth 0.0.12 (MIT):
GitHub.com and GHE.com device sign-in, Copilot token renewal, request
signing with initiator and vision headers. Client versions match magpie's
native Copilot (vscode/1.140.0, copilot-chat/0.68.0). Host headers are
read as a Headers object, which is how magpie's host.js passes them. When the
sign-in isn't OAuth, the request goes on to plain fetch.
It adds magpie's auth.usage hook. The hook reads GET
api.<host>/copilot_internal/user with the GitHub OAuth token
(redirect: "error", 15s timeout) and turns the reply into windows the way
magpie's built-in Copilot reader does. It reads only the chat, completions
and premium_interactions snapshots. Credits are fractional, and string
counters are accepted. An exhausted unlimited pool counts as 100% used.
Managed seats block when spent, and personal seats with overage are aside.
credits_used is never divided by the entitlement. An unlimited pool's
credits_used goes in the display, aside and with no limit. Data that can't
be read is unknown, and only HTTP 401 expires the sign-in.
Run at head c7fb3abd, merged onto main 6a2ade35 (Bun 1.4.2, sandbox HOME
and TMPDIR, HTTP(S)_PROXY pointed at a closed port):
- packages/copilot bun test: 40 pass, 0 fail. Full repo bun test: 2838
pass, 3 skip, 0 fail. bun scripts/check.mjs: all ok.
- A probe sent fetch to a local Bun server, using magpie's real Copilot
quota bytes (internal/provider/copilot_usage_test.go). Max token billing:
"0.1 / 20,000 credits used". Enterprise pool spent: 100%, blocking. Pro in
overage: 300/300, aside. 401: signIn expired. A GHE sign-in reads
api.<host>. The loader with a host-style Headers object renewed through
v2/token with Bearer <oauth>. The chat request went out with content-type,
accept and the extra header kept. Incoming authorization and x-api-key
were replaced. Vision and X-Initiator were set, and the renewed token was
saved under github-copilot.
- PR CI (approved at c7fb3abd): test and on-npm pass.
Not tried: a real GitHub or Enterprise account. Not changed: the device
flow treats slow_down as a failure. This comes from upstream.
165 lines
6.7 KiB
JavaScript
165 lines
6.7 KiB
JavaScript
import { HEADERS, getUrls } from "./endpoints.mjs";
|
|
|
|
const names = {
|
|
premium_interactions: "Premium requests",
|
|
chat: "Chat",
|
|
completions: "Completions",
|
|
};
|
|
|
|
const numeric = (value) => {
|
|
if (typeof value === "string" && /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(value.trim())) {
|
|
value = Number(value);
|
|
}
|
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
};
|
|
const count = (value) => {
|
|
const n = numeric(value);
|
|
return n !== undefined && n >= 0 ? n : undefined;
|
|
};
|
|
const format = (value) =>
|
|
new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(value);
|
|
|
|
function resetDate(value) {
|
|
if (!value || !["string", "number"].includes(typeof value)) return undefined;
|
|
const timestamp = numeric(value);
|
|
if (timestamp !== undefined) {
|
|
if (timestamp <= 0) return undefined;
|
|
value = timestamp;
|
|
}
|
|
const date = new Date(
|
|
typeof value === "number" && value < 1e11 ? value * 1000 : value,
|
|
);
|
|
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
|
|
}
|
|
|
|
export function parseUsage(data) {
|
|
const windows = [];
|
|
const rootReset = resetDate(data.quota_reset_date_utc) ??
|
|
resetDate(data.quota_reset_date) ?? resetDate(data.limited_user_reset_date);
|
|
let balance;
|
|
const plan = typeof data.copilot_plan === "string" ? data.copilot_plan : "";
|
|
const managed = ["business", "enterprise"].includes(plan.toLowerCase());
|
|
const aside = (id, quota) => id === "completions" ||
|
|
id === "premium_interactions" && quota.overage_permitted === true && !managed;
|
|
const snapshots = data.quota_snapshots;
|
|
if (snapshots && typeof snapshots === "object" && !Array.isArray(snapshots)) {
|
|
// Unknown snapshots may describe unrelated allowances and must not gate chat.
|
|
for (const id of Object.keys(names)) {
|
|
const quota = snapshots[id];
|
|
if (!quota || typeof quota !== "object") continue;
|
|
const credits = id === "premium_interactions" &&
|
|
(quota.token_based_billing ?? data.token_based_billing) === true;
|
|
const name = id === "premium_interactions" && credits
|
|
? "Premium credits" : names[id];
|
|
const resetsAt = resetDate(quota.quota_reset_at) ?? rootReset;
|
|
if (quota.unlimited === true) {
|
|
// A managed pool is labelled unlimited even after it is spent.
|
|
// Chat/completions may say has_quota=false while still unlimited.
|
|
if (id === "premium_interactions" && quota.has_quota === false) {
|
|
windows.push({ name, used: 100, resetsAt, span: 2592000, aside: aside(id, quota) });
|
|
continue;
|
|
}
|
|
const creditsUsed = credits ? count(quota.credits_used) : undefined;
|
|
windows.push({
|
|
name, used: 0, aside: true,
|
|
display: creditsUsed !== undefined
|
|
? `${format(creditsUsed)} credits used` : "Unlimited",
|
|
});
|
|
continue;
|
|
}
|
|
const limit = count(quota.entitlement);
|
|
// has_quota is not the existence of an allowance: GitHub returns false
|
|
// for exhausted seats, and for usable token-billed seats too (#1063).
|
|
if (limit === 0) continue;
|
|
// New credit billing retains an integer `remaining` alongside the
|
|
// more precise `quota_remaining`; never round away fractional credits.
|
|
const remaining = count(quota.quota_remaining) ?? count(quota.remaining);
|
|
const percentRemaining = numeric(quota.percent_remaining);
|
|
const amount = limit !== undefined && remaining !== undefined
|
|
? Math.max(0, limit - remaining) : undefined;
|
|
let used = limit > 0 && amount !== undefined ? amount / limit * 100 : undefined;
|
|
if (used === undefined && percentRemaining !== undefined) {
|
|
used = Math.max(0, 100 - percentRemaining);
|
|
}
|
|
if (used === undefined) continue;
|
|
used = Math.min(100, used);
|
|
const unit = credits ? "credits" : "requests";
|
|
const display = [
|
|
amount !== undefined && limit !== undefined
|
|
? `${format(amount)} / ${format(limit)} ${unit} used` : undefined,
|
|
remaining !== undefined ? `${format(remaining)} ${unit} remaining` : undefined,
|
|
].filter(Boolean).join("; ");
|
|
const window = {
|
|
name, used,
|
|
resetsAt,
|
|
...(display ? { display } : {}),
|
|
...(amount !== undefined ? { amount } : {}),
|
|
...(limit !== undefined && amount !== undefined ? { limit } : {}),
|
|
unit, span: 2592000, aside: aside(id, quota),
|
|
};
|
|
windows.push(window);
|
|
if (id === "premium_interactions" && remaining !== undefined) {
|
|
balance = `${format(remaining)} ${unit} remaining`;
|
|
}
|
|
}
|
|
} else if (data.monthly_quotas && data.limited_user_quotas) {
|
|
for (const [id, label] of [["chat", "Chat"], ["completions", "Completions"]]) {
|
|
const limit = count(data.monthly_quotas[id]);
|
|
const remaining = count(data.limited_user_quotas[id]);
|
|
if (!(limit > 0) || remaining === undefined) continue;
|
|
const amount = Math.max(0, limit - remaining);
|
|
windows.push({
|
|
name: label, used: amount / limit * 100, amount, limit, unit: "requests",
|
|
resetsAt: rootReset, span: 2592000, aside: id === "completions",
|
|
display: `${format(amount)} / ${format(limit)} requests used; ${format(remaining)} requests remaining`,
|
|
});
|
|
}
|
|
}
|
|
return {
|
|
...(typeof data.copilot_plan === "string" ? { plan: data.copilot_plan } : {}),
|
|
...(typeof data.login === "string" ? { user: data.login } : {}),
|
|
...(balance ? { balance } : {}),
|
|
windows,
|
|
signIn: "kept",
|
|
...(!windows.length ? { error: "GitHub did not return readable Copilot quota data" } : {}),
|
|
};
|
|
}
|
|
|
|
export async function readUsage(getAuth) {
|
|
try {
|
|
const auth = await getAuth();
|
|
if (auth?.type !== "oauth" || !auth.refresh) {
|
|
return { windows: [], error: "No GitHub OAuth sign-in is available", signIn: "kept" };
|
|
}
|
|
// This endpoint uses the GitHub OAuth token, not the short-lived
|
|
// Copilot inference token. It works on the account's own GHE host too.
|
|
const response = await fetch(getUrls(auth.enterpriseUrl).USER_URL, {
|
|
headers: {
|
|
...HEADERS,
|
|
Accept: "application/json",
|
|
Authorization: `token ${auth.refresh}`,
|
|
},
|
|
redirect: "error",
|
|
signal: AbortSignal.timeout(15000),
|
|
});
|
|
if (!response.ok) {
|
|
return {
|
|
windows: [],
|
|
error: `GitHub Copilot quota request failed (HTTP ${response.status})`,
|
|
signIn: response.status === 401 ? "expired" : "kept",
|
|
};
|
|
}
|
|
const data = await response.json();
|
|
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
throw new Error("Invalid quota response");
|
|
}
|
|
return parseUsage(data);
|
|
} catch {
|
|
// Never include request headers, OAuth tokens or response bodies in errors.
|
|
return {
|
|
windows: [], error: "Unable to read GitHub Copilot quota; retry later",
|
|
signIn: "kept",
|
|
};
|
|
}
|
|
}
|