copilot 0.1.0: GitHub Copilot with premium request and credit quota (#411)

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.
This commit is contained in:
Kurt Lee
2026-10-27 16:04:15 +08:00
committed by GitHub
parent 6a2ade35ef
commit 67407cf00f
10 changed files with 1325 additions and 0 deletions
+1
View File
@@ -14,6 +14,7 @@ subscription and makes its requests. The packages work in OpenCode and in
| [cline](packages/cline) | Cline (cline.bot): usage-billed models, ClinePass's and Cline's free ones, with Cline's device sign-in or an API key | `cline` |
| [codearts](packages/codearts) | Huawei Cloud CodeArts (码道) coding plans (Trial, personal and enterprise credits), with Huawei Cloud OAuth sign-in (unofficial) | `codearts` |
| [commandcode](packages/commandcode) | Command Code plans (Pro, GOAT, Max, Ultra, Go, Teams Pro) | `commandcode-plan` |
| [copilot](packages/copilot) | GitHub Copilot on GitHub.com or GitHub Enterprise, with premium request or credit quotas | `github-copilot` |
| [cursor](packages/cursor) | Cursor subscriptions (Pro, Pro+, Ultra, Teams), on the API cursor-agent talks to | `cursor` |
| [devin](packages/devin) | Devin subscription (the devin CLI's account) | `devin` |
| [factory](packages/factory) | Factory (Droid) subscription | `factory` |
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 SST
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+137
View File
@@ -0,0 +1,137 @@
# GitHub Copilot
An unofficial OpenCode provider plugin for GitHub Copilot on GitHub.com and
GitHub Enterprise (including GHE.com). In magpie it also shows the account's
premium request or credit quota: used, remaining, the included allowance and
when it resets. It does not change the subscription or enable paid overage.
The authentication and request implementation is adapted from
[`opencode-copilot-auth` 0.0.12](https://www.npmjs.com/package/opencode-copilot-auth)
([source](https://github.com/anomalyco/opencode-copilot-auth)), under its MIT
license, retained in `LICENSE`. It keeps the device flow, request signing,
initiator detection and vision headers, with client versions matching magpie's
native Copilot implementation. No runtime dependency on another installed plugin
or local file is needed.
## Install and sign in
```sh
magpie plugin add @magpie-community/opencode-copilot-auth
magpie plugin login github-copilot
```
Choose GitHub.com or GitHub Enterprise; for Enterprise enter your own GitHub
host, such as `company.ghe.com`. Complete GitHub's device authorization in
the browser. Host inputs must be HTTPS origins without credentials, paths,
query strings or custom ports. As in the upstream plugin, Enterprise API and
inference hosts are `api.<host>` and `copilot-api.<host>`; deployments with
different endpoint layouts are not covered.
For OpenCode, add `@magpie-community/opencode-copilot-auth` to `plugin` in
`opencode.json`, then run `opencode auth login`.
The provider id is `github-copilot` for both deployments. GitHub's OAuth token
is stored in the host's auth store as `refresh`; the short-lived Copilot token
is stored as `access` with `expires`. In magpie this is `plugin-auth.json`,
scoped by the host to the selected account, including additional `#slot`
accounts. Enterprise sign-ins keep `enterpriseUrl` through token renewal.
Models come from the host's existing `github-copilot` catalog.
If the original `opencode-copilot-auth` is already installed in magpie, keep
it and explicitly choose which plugin serves the existing provider:
```sh
magpie plugin use @magpie-community/opencode-copilot-auth github-copilot
```
The shared provider id lets the new plugin reuse the existing sign-in and
model picks; there is no automatic migration from magpie's separate built-in
`copilot` provider or from a legacy `github-copilot-enterprise` auth entry.
## Quota reporting
magpie calls `auth.usage(getAuth, provider)` independently of model requests.
It reads `GET /copilot_internal/user` on `api.github.com` or the account's
`api.<enterpriseUrl>` using the GitHub OAuth token, **not** the short-lived
inference token. Reading quota neither renews nor persists either token.
OpenCode ignores magpie's additional hook.
- Only `chat`, `completions` and `premium_interactions` snapshots are read;
unknown quota types cannot block chat model routing.
- Snapshot counters accept numbers or numeric strings. Fractional
`quota_remaining` takes precedence over the rounded legacy `remaining`;
`remaining` is the fallback when the canonical field is absent. Used amount
is entitlement minus remaining. Organization-pool `credits_used` has no
per-seat denominator and is never divided by entitlement. Without remaining
counters or a percentage, a finite seat's utilization is unknown.
- Snapshot amounts determine the percentage when known; otherwise
`percent_remaining` gives a percentage without inventing an absolute balance.
- `quota_reset_at`, `quota_reset_date_utc` and `quota_reset_date` supply resets;
date-only values mean UTC midnight. Legacy free-plan monthly counters are
supported too.
- `has_quota: false` does not hide a usable or exhausted seat. A zero
entitlement means no included allowance. An exhausted premium pool may say
`unlimited: true, has_quota: false`; it is shown as 100% used, not unlimited.
- Unlimited chat and completion allowances are labelled `Unlimited`, not
`0 / 0`. An unlimited premium credit pool with readable `credits_used` shows
that usage as informational (`aside`), without inventing a seat limit or
percentage. Completion quotas do not block chat model routing. For finite
premium allowances, only unmanaged seats with vendor-permitted overage are
informational (`aside`); Business and Enterprise exhaustion remains blocking,
as in magpie's native Copilot implementation. The plugin never changes the
overage permission or adds the separate overage counter to included usage.
- Empty, malformed or unavailable quota data is unknown, not zero usage.
Only an explicit HTTP 401 marks the sign-in expired. Network errors, rate
limits, 403s and server errors keep the sign-in. No response body or token is
included in error messages. Quota requests have a timeout and reject redirects.
GitHub's quota endpoint is internal and may change. An organization may not
expose all balances to a seat; missing data is not an estimate of its budget.
## Network and credential scope
The new network operation is a read of `GET /copilot_internal/user`. It sends
the account's GitHub OAuth token only to `https://api.github.com` or, for an
Enterprise sign-in, `https://api.<enterpriseUrl>`. Enter only the GitHub host
your organization trusts: HTTPS validation does not establish ownership of a
domain. The quota request rejects redirects, and sends no prompt, model
request, local file or inference token.
The inherited device flow posts the public OAuth client id and device code
to the selected GitHub host's `/login/device/code` and
`/login/oauth/access_token`. Inference token renewal sends the OAuth token to
`/copilot_internal/v2/token` on that account's API host. Model requests use
the Copilot inference token at `https://api.githubcopilot.com` or the
Enterprise `https://copilot-api.<enterpriseUrl>` origin. These operations are
separate from reading quota.
The plugin gets credentials from the host's `getAuth`; it does not scan
credential files, a keychain or agent configurations. Only the existing
inference token renewal calls `client.auth.set`. No dependency, install
script, telemetry, relay or account migration is added.
Request signing preserves host headers (including `Content-Type`, `Accept` and
`chat.headers`) supplied as a `Headers` object, plain object or tuples. It replaces
authorization and removes `x-api-key` case-insensitively. If the host stops
returning OAuth credentials, requests pass through without Copilot signing.
## Tests
```sh
(
verification_home=$(mktemp -d) || exit
trap 'rm -rf "$verification_home"' EXIT
HOME="$verification_home" bun test packages/copilot
)
bun scripts/check.mjs copilot
```
Tests use synthetic accounts, mocked vendor responses and a loopback HTTP server:
public and Enterprise device flows, token refresh, outgoing request headers and
body, non-OAuth passthrough, fractional credits, legacy requests, unlimited
allowances, organization-pool credits, resets, unknown quota types and read failures.
They read no real auth files and consume no Copilot allowance.
The quota read test also uses an expired inference token and asserts the exact
single OAuth quota request, no auth persistence and unchanged input credentials.
Live inference and Enterprise access require separate verification against a
real account; these offline tests are not evidence of vendor acceptance.
+33
View File
@@ -0,0 +1,33 @@
export const HEADERS = {
"User-Agent": "GitHubCopilotChat/0.68.0",
"Editor-Version": "vscode/1.140.0",
"Editor-Plugin-Version": "copilot-chat/0.68.0",
"Copilot-Integration-Id": "vscode-chat",
};
export function normalizeDomain(value) {
if (typeof value !== "string" || !value.trim()) {
throw new Error("GitHub host is required");
}
const input = value.trim();
const url = new URL(input.includes("://") ? input : `https://${input}`);
if (
url.protocol !== "https:" || url.username || url.password || url.port ||
url.search || url.hash || url.pathname !== "/" ||
!/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/i.test(url.hostname)
) {
throw new Error("Expected an HTTPS GitHub host without credentials, port or path");
}
return url.hostname;
}
export function getUrls(domain = "github.com") {
const host = normalizeDomain(domain);
const api = `https://api.${host}`;
return {
DEVICE_CODE_URL: `https://${host}/login/device/code`,
ACCESS_TOKEN_URL: `https://${host}/login/oauth/access_token`,
COPILOT_API_KEY_URL: `${api}/copilot_internal/v2/token`,
USER_URL: `${api}/copilot_internal/user`,
};
}
+289
View File
@@ -0,0 +1,289 @@
// Adapted from opencode-copilot-auth 0.0.12 (MIT, copyright SST).
// Keep the upstream request signing and initiator detection; add magpie usage.
import { HEADERS, normalizeDomain, getUrls } from "./endpoints.mjs";
import { readUsage } from "./usage.mjs";
/**
* @type {import('@opencode-ai/plugin').Plugin}
*/
export async function CopilotAuthPlugin({ client }) {
const CLIENT_ID = "Iv1.b507a08c87ecfe98";
const RESPONSES_API_ALTERNATE_INPUT_TYPES = [
"file_search_call",
"computer_call",
"computer_call_output",
"web_search_call",
"function_call",
"function_call_output",
"image_generation_call",
"code_interpreter_call",
"local_shell_call",
"local_shell_call_output",
"mcp_list_tools",
"mcp_approval_request",
"mcp_approval_response",
"mcp_call",
"reasoning",
];
return {
auth: {
provider: "github-copilot",
usage: readUsage,
loader: async (getAuth, provider) => {
let info = await getAuth();
if (!info || info.type !== "oauth") return {};
if (provider && provider.models) {
for (const model of Object.values(provider.models)) {
model.cost = {
input: 0,
output: 0,
cache: {
read: 0,
write: 0,
},
};
}
}
// Set baseURL based on deployment type
const enterpriseUrl = info.enterpriseUrl;
const baseURL = enterpriseUrl
? `https://copilot-api.${normalizeDomain(enterpriseUrl)}`
: "https://api.githubcopilot.com";
return {
baseURL,
apiKey: "",
async fetch(input, init) {
const info = await getAuth();
if (info?.type !== "oauth") return fetch(input, init);
if (!info.access || info.expires < Date.now()) {
const domain = info.enterpriseUrl
? normalizeDomain(info.enterpriseUrl)
: "github.com";
const urls = getUrls(domain);
const response = await fetch(urls.COPILOT_API_KEY_URL, {
headers: {
Accept: "application/json",
Authorization: `Bearer ${info.refresh}`,
...HEADERS,
},
});
if (!response.ok) {
throw new Error(`Token refresh failed: ${response.status}`);
}
const tokenData = await response.json();
// Use the hook's provider id for both deployments. The host
// scopes this write to the selected account (including #slots).
const saveProviderID = "github-copilot";
await client.auth.set({
path: {
id: saveProviderID,
},
body: {
type: "oauth",
refresh: info.refresh,
access: tokenData.token,
expires: tokenData.expires_at * 1000 - 5 * 60 * 1000,
...(info.enterpriseUrl && {
enterpriseUrl: info.enterpriseUrl,
}),
},
});
info.access = tokenData.token;
}
let isAgentCall = false;
let isVisionRequest = false;
try {
const body =
typeof init?.body === "string"
? JSON.parse(init.body)
: init?.body;
if (body?.messages) {
if (body.messages.length > 0) {
const lastMessage = body.messages[body.messages.length - 1];
isAgentCall = lastMessage.role && ["tool", "assistant"].includes(lastMessage.role);
}
isVisionRequest = body.messages.some(
(msg) =>
Array.isArray(msg.content) &&
msg.content.some((part) => part.type === "image_url"),
);
}
if (body?.input) {
const lastInput = body.input[body.input.length - 1];
const isAssistant = lastInput?.role === "assistant";
const hasAgentType = lastInput?.type
? RESPONSES_API_ALTERNATE_INPUT_TYPES.includes(lastInput.type)
: false;
isAgentCall = isAssistant || hasAgentType;
isVisionRequest =
Array.isArray(lastInput?.content) &&
lastInput.content.some((part) => part.type === "input_image");
}
} catch {}
const headers = new Headers(init?.headers);
headers.delete("x-api-key");
headers.delete("authorization");
for (const [key, value] of Object.entries(HEADERS)) {
headers.set(key, value);
}
headers.set("Authorization", `Bearer ${info.access}`);
headers.set("Openai-Intent", "conversation-edits");
headers.set("X-Initiator", isAgentCall ? "agent" : "user");
if (isVisionRequest) {
headers.set("Copilot-Vision-Request", "true");
}
return fetch(input, {
...init,
headers,
});
},
};
},
methods: [
{
type: "oauth",
label: "Login with GitHub Copilot",
prompts: [
{
type: "select",
key: "deploymentType",
message: "Select GitHub deployment type",
options: [
{
label: "GitHub.com",
value: "github.com",
hint: "Public",
},
{
label: "GitHub Enterprise",
value: "enterprise",
hint: "Data residency or self-hosted",
},
],
},
{
type: "text",
key: "enterpriseUrl",
message: "Enter your GitHub Enterprise URL or domain",
placeholder: "company.ghe.com or https://company.ghe.com",
condition: (inputs) => inputs.deploymentType === "enterprise",
validate: (value) => {
if (!value) return "URL or domain is required";
try {
const url = value.includes("://")
? new URL(value)
: new URL(`https://${value}`);
if (!url.hostname)
return "Please enter a valid URL or domain";
normalizeDomain(value);
return undefined;
} catch {
return "Please enter a valid URL (e.g., company.ghe.com or https://company.ghe.com)";
}
},
},
],
async authorize(inputs = {}) {
const deploymentType = inputs.deploymentType || "github.com";
let domain = "github.com";
if (deploymentType === "enterprise") {
const enterpriseUrl = inputs.enterpriseUrl;
domain = normalizeDomain(enterpriseUrl);
}
const urls = getUrls(domain);
const deviceResponse = await fetch(urls.DEVICE_CODE_URL, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"User-Agent": HEADERS["User-Agent"],
},
body: JSON.stringify({
client_id: CLIENT_ID,
scope: "read:user",
}),
});
if (!deviceResponse.ok) {
throw new Error("Failed to initiate device authorization");
}
const deviceData = await deviceResponse.json();
return {
url: deviceData.verification_uri,
instructions: `Enter code: ${deviceData.user_code}`,
method: "auto",
callback: async () => {
while (true) {
const response = await fetch(urls.ACCESS_TOKEN_URL, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"User-Agent": HEADERS["User-Agent"],
},
body: JSON.stringify({
client_id: CLIENT_ID,
device_code: deviceData.device_code,
grant_type:
"urn:ietf:params:oauth:grant-type:device_code",
}),
});
if (!response.ok) return { type: "failed" };
const data = await response.json();
if (data.access_token) {
const result = {
type: "success",
refresh: data.access_token,
access: "",
expires: 0,
};
if (deploymentType === "enterprise") {
result.enterpriseUrl = domain;
}
return result;
}
if (data.error === "authorization_pending") {
await new Promise((resolve) =>
setTimeout(resolve, deviceData.interval * 1000),
);
continue;
}
if (data.error) return { type: "failed" };
await new Promise((resolve) =>
setTimeout(resolve, deviceData.interval * 1000),
);
continue;
}
},
};
},
},
],
},
};
}
+262
View File
@@ -0,0 +1,262 @@
import { afterEach, test } from "bun:test";
import assert from "node:assert/strict";
import { CopilotAuthPlugin } from "./index.mjs";
import { getUrls, normalizeDomain } from "./endpoints.mjs";
const originalFetch = globalThis.fetch;
afterEach(() => { globalThis.fetch = originalFetch; });
const reply = (data) => new Response(JSON.stringify(data));
const signedIn = (extra = {}) => ({
type: "oauth", refresh: "mock-github-oauth", access: "mock-copilot-token",
expires: Date.now() + 60000, ...extra,
});
async function withLocalEndpoint(check) {
const server = Bun.serve({
hostname: "127.0.0.1", port: 0,
async fetch(request) {
return Response.json({
method: request.method, headers: Object.fromEntries(request.headers),
body: await request.text(),
});
},
});
try {
await check(`http://127.0.0.1:${server.port}/responses`);
} finally {
server.stop(true);
}
}
function assertClientHeaders(input) {
const headers = new Headers(input);
assert.equal(headers.get("user-agent"), "GitHubCopilotChat/0.68.0");
assert.equal(headers.get("editor-version"), "vscode/1.140.0");
assert.equal(headers.get("editor-plugin-version"), "copilot-chat/0.68.0");
assert.equal(headers.get("copilot-integration-id"), "vscode-chat");
}
test("one provider id, OAuth login and magpie's usage hook", async () => {
const hooks = await CopilotAuthPlugin({ client: {} });
assert.deepEqual(Object.keys(hooks), ["auth"]);
assert.equal(hooks.auth.provider, "github-copilot");
assert.equal(typeof hooks.auth.usage, "function");
assert.equal(typeof hooks.auth.loader, "function");
assert.equal(hooks.auth.methods[0].type, "oauth");
});
test("host parsing accepts GHE domains or HTTPS origins, not credential-bearing URLs", () => {
for (const input of ["company.ghe.com", "https://company.ghe.com/", " COMPANY.GHE.COM "]) {
assert.equal(normalizeDomain(input), "company.ghe.com");
}
for (const input of ["", undefined, "http://company.ghe.com", "https://user@company.ghe.com",
"https://company.ghe.com/path", "https://company.ghe.com?x=1", "https://company.ghe.com#x",
"https://company.ghe.com:8443", "https://localhost"]) {
assert.throws(() => normalizeDomain(input));
}
assert.equal(getUrls().USER_URL, "https://api.github.com/copilot_internal/user");
assert.equal(getUrls("company.ghe.com").USER_URL,
"https://api.company.ghe.com/copilot_internal/user");
});
test("loader preserves public and Enterprise inference origins and zero token pricing", async () => {
for (const [enterpriseUrl, baseURL] of [
[undefined, "https://api.githubcopilot.com"],
["company.ghe.com", "https://copilot-api.company.ghe.com"],
]) {
globalThis.fetch = async () => assert.fail("loader must not make a model request");
const hooks = await CopilotAuthPlugin({ client: {} });
const provider = { models: { mock: { cost: { input: 1, output: 2 } } } };
const loader = await hooks.auth.loader(async () => signedIn({ enterpriseUrl }), provider);
assert.equal(loader.baseURL, baseURL);
assert.equal(loader.apiKey, "");
assert.deepEqual(provider.models.mock.cost,
{ input: 0, output: 0, cache: { read: 0, write: 0 } });
}
});
test("request signing preserves body, initiator and vision headers without a quota request", async () => {
for (const [body, initiator, vision] of [
[{ messages: [{ role: "user", content: "hello" }] }, "user", false],
[{ messages: [{ role: "tool", content: "done" }] }, "agent", false],
[{ input: [{ type: "function_call_output", output: "done" }] }, "agent", false],
[{ input: [{ role: "user", content: [{ type: "input_image", image_url: "mock" }] }] }, "user", true],
]) {
const seen = [];
const saved = [];
globalThis.fetch = async (url, init) => {
seen.push({ url, init });
return new Response("mock-ok");
};
const hooks = await CopilotAuthPlugin({ client: { auth: { set: async (v) => saved.push(v) } } });
const loader = await hooks.auth.loader(async () => signedIn(), { models: {} });
const result = await loader.fetch("https://api.githubcopilot.com/responses", {
method: "POST", headers: { authorization: "wrong", "x-api-key": "wrong" },
body: JSON.stringify(body),
});
assert.equal(await result.text(), "mock-ok");
assert.equal(seen.length, 1);
const headers = new Headers(seen[0].init.headers);
assert.equal(headers.get("authorization"), "Bearer mock-copilot-token");
assert.equal(headers.get("x-api-key"), null);
assert.equal(headers.get("x-initiator"), initiator);
assert.equal(headers.get("copilot-vision-request"), vision ? "true" : null);
assert.equal(seen[0].init.body, JSON.stringify(body));
assert.deepEqual(saved, []);
}
});
test("outgoing requests preserve host Headers, objects and tuples without duplicate signing headers", async () => {
await withLocalEndpoint(async (url) => {
const hooks = await CopilotAuthPlugin({ client: {} });
const loader = await hooks.auth.loader(async () => signedIn(), { models: {} });
const hostHeaders = {
"Content-Type": "application/json", Accept: "text/event-stream",
"X-From-Chat-Headers": "1", "AUTHORIZATION": "wrong", "X-API-Key": "wrong",
"x-initiator": "wrong", "openai-intent": "wrong", "user-agent": "wrong",
"editor-version": "wrong", "editor-plugin-version": "wrong",
"copilot-integration-id": "wrong",
};
const body = JSON.stringify({ messages: [{ role: "user", content: "hello" }] });
for (const headers of [new Headers(hostHeaders), hostHeaders, Object.entries(hostHeaders)]) {
const before = [...new Headers(headers)];
const result = await loader.fetch(url, { method: "POST", headers, body });
const sent = await result.json();
assert.equal(sent.headers["content-type"], "application/json");
assert.equal(sent.headers.accept, "text/event-stream");
assert.equal(sent.headers["x-from-chat-headers"], "1");
assert.equal(sent.headers.authorization, "Bearer mock-copilot-token");
assert.equal(sent.headers["x-api-key"], undefined);
assert.equal(sent.headers["x-initiator"], "user");
assert.equal(sent.headers["openai-intent"], "conversation-edits");
assertClientHeaders(sent.headers);
assert.equal(sent.method, "POST");
assert.equal(sent.body, body);
assert.deepEqual([...new Headers(headers)], before);
}
});
});
test("outgoing Chat and Responses requests carry the signed initiator and vision headers", async () => {
await withLocalEndpoint(async (url) => {
const hooks = await CopilotAuthPlugin({ client: {} });
const loader = await hooks.auth.loader(async () => signedIn(), { models: {} });
for (const [body, initiator, vision] of [
[{ messages: [{ role: "user", content: "hello" }] }, "user", false],
[{ messages: [{ role: "tool", content: "done" }] }, "agent", false],
[{ messages: [{ role: "assistant", content: "continue" }] }, "agent", false],
[{ messages: [{ role: "user", content: [{ type: "image_url", image_url: "mock" }] }] }, "user", true],
[{ input: [{ type: "function_call_output", output: "done" }] }, "agent", false],
[{ input: [{ role: "assistant", content: "continue" }] }, "agent", false],
[{ input: [{ role: "user", content: [{ type: "input_image", image_url: "mock" }] }] }, "user", true],
]) {
const result = await loader.fetch(url, {
method: "POST", headers: new Headers({ "Content-Type": "application/json" }),
body: JSON.stringify(body),
});
const sent = await result.json();
assert.equal(sent.headers.authorization, "Bearer mock-copilot-token");
assert.equal(sent.headers["x-initiator"], initiator);
assert.equal(sent.headers["copilot-vision-request"], vision ? "true" : undefined);
assert.equal(sent.body, JSON.stringify(body));
}
});
});
test("outgoing requests pass through as Responses when auth stops being OAuth", async () => {
await withLocalEndpoint(async (url) => {
let auth = signedIn();
const hooks = await CopilotAuthPlugin({ client: { auth: {
set: async () => assert.fail("non-OAuth passthrough must not persist auth"),
} } });
const loader = await hooks.auth.loader(async () => auth, { models: {} });
for (auth of [{ type: "api", key: "mock-api-key" }, null, undefined]) {
const result = await loader.fetch(url, {
method: "POST", headers: new Headers({
"Content-Type": "application/json", Authorization: "Bearer mock-host-token",
"X-From-Chat-Headers": "1",
}), body: "{}",
});
assert.ok(result instanceof Response);
const sent = await result.json();
assert.equal(sent.headers.authorization, "Bearer mock-host-token");
assert.equal(sent.headers["content-type"], "application/json");
assert.equal(sent.headers["x-from-chat-headers"], "1");
assert.equal(sent.headers["editor-version"], undefined);
assert.equal(sent.headers["x-initiator"], undefined);
assert.equal(sent.method, "POST");
assert.equal(sent.body, "{}");
}
});
});
test("outgoing requests without init use the native magpie Copilot client versions", async () => {
await withLocalEndpoint(async (url) => {
const hooks = await CopilotAuthPlugin({ client: {} });
const loader = await hooks.auth.loader(async () => signedIn(), { models: {} });
const result = await loader.fetch(url);
const sent = await result.json();
assertClientHeaders(sent.headers);
assert.equal(sent.headers.authorization, "Bearer mock-copilot-token");
assert.equal(sent.method, "GET");
});
});
test("refresh saves public and Enterprise tokens under the hook's provider id", async () => {
for (const enterpriseUrl of [undefined, "company.ghe.com"]) {
const auth = signedIn({ access: "", expires: 0, enterpriseUrl });
const saved = [];
const seen = [];
const expires = Math.floor(Date.now() / 1000) + 3600;
globalThis.fetch = async (url, init) => {
seen.push({ url, init });
if (url.endsWith("/copilot_internal/v2/token")) return reply({ token: "mock-new-token", expires_at: expires });
return new Response("mock-ok");
};
const hooks = await CopilotAuthPlugin({ client: { auth: { set: async (v) => saved.push(v) } } });
const loader = await hooks.auth.loader(async () => ({ ...auth }), { models: {} });
await loader.fetch(`${loader.baseURL}/responses`, { body: "{}", headers: {} });
assert.equal(seen.length, 2);
assert.equal(seen[0].url, getUrls(enterpriseUrl).COPILOT_API_KEY_URL);
assert.equal(seen[0].init.headers.Authorization, "Bearer mock-github-oauth");
assertClientHeaders(seen[0].init.headers);
assert.equal(new Headers(seen[1].init.headers).get("authorization"), "Bearer mock-new-token");
assertClientHeaders(seen[1].init.headers);
assert.equal(saved.length, 1);
assert.equal(saved[0].path.id, "github-copilot");
assert.equal(saved[0].body.enterpriseUrl, enterpriseUrl);
assert.equal(saved[0].body.expires, expires * 1000 - 300000);
assert.equal(saved[0].body.refresh, "mock-github-oauth");
}
});
test("device flow keeps Enterprise metadata without redirecting auth to another provider", async () => {
for (const [inputs, host] of [
[{}, "github.com"],
[{ deploymentType: "enterprise", enterpriseUrl: "https://company.ghe.com/" }, "company.ghe.com"],
]) {
const seen = [];
globalThis.fetch = async (url, init) => {
seen.push({ url, body: JSON.parse(init.body), headers: new Headers(init.headers) });
if (url.endsWith("/login/device/code")) return reply({
verification_uri: `https://${host}/login/device`, user_code: "MOCK-CODE",
device_code: "mock-device-code", interval: 1,
});
return reply({ access_token: "mock-github-oauth" });
};
const hooks = await CopilotAuthPlugin({ client: {} });
const flow = await hooks.auth.methods[0].authorize(inputs);
const result = await flow.callback();
assert.equal(flow.url, `https://${host}/login/device`);
assert.equal(result.type, "success");
assert.equal(result.provider, undefined);
assert.equal(result.refresh, "mock-github-oauth");
assert.equal(result.enterpriseUrl, host === "github.com" ? undefined : host);
assert.equal(seen[0].url, `https://${host}/login/device/code`);
assert.equal(seen[1].url, `https://${host}/login/oauth/access_token`);
assert.equal(seen[1].body.device_code, "mock-device-code");
for (const { headers } of seen) {
assert.equal(headers.get("user-agent"), "GitHubCopilotChat/0.68.0");
}
}
});
+16
View File
@@ -0,0 +1,16 @@
{
"name": "@magpie-community/opencode-copilot-auth",
"version": "0.1.0",
"description": "GitHub Copilot on GitHub.com and GitHub Enterprise, with account quota and credit balances for magpie",
"type": "module",
"main": "./index.mjs",
"files": ["index.mjs", "endpoints.mjs", "usage.mjs", "README.md", "LICENSE"],
"keywords": ["opencode", "opencode-plugin", "github", "copilot", "magpie"],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/magpie-community/plugins",
"directory": "packages/copilot"
},
"scripts": { "test": "bun test" }
}
+164
View File
@@ -0,0 +1,164 @@
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",
};
}
}
+400
View File
@@ -0,0 +1,400 @@
import { afterEach, test } from "bun:test";
import assert from "node:assert/strict";
import { parseUsage } from "./usage.mjs";
import { CopilotAuthPlugin } from "./index.mjs";
const originalFetch = globalThis.fetch;
afterEach(() => { globalThis.fetch = originalFetch; });
async function readUsage(getAuth, fetcher) {
globalThis.fetch = fetcher;
const hooks = await CopilotAuthPlugin({ client: {} });
return hooks.auth.usage(getAuth);
}
const auth = { type: "oauth", refresh: "mock-oauth", access: "mock-inference" };
const getAuth = async () => ({ ...auth });
const response = (data, status = 200) => new Response(JSON.stringify(data), { status });
const premium = (quota, extra = {}) => ({
copilot_plan: "business", login: "test-user", quota_reset_date: "2026-11-01",
quota_snapshots: { premium_interactions: quota }, ...extra,
});
test("fractional credit quota, plan, identity and UTC reset", () => {
const result = parseUsage(premium({
token_based_billing: true, entitlement: 10000, quota_remaining: 7654.32,
remaining: 7654, credits_used: 2346, percent_remaining: 76.5,
quota_reset_at: 0, overage_permitted: true,
}));
const [window] = result.windows;
assert.ok(Math.abs(window.amount - 2345.68) < 1e-8);
assert.ok(Math.abs(window.used - 23.4568) < 1e-8);
assert.equal(window.limit, 10000);
assert.equal(window.name, "Premium credits");
assert.equal(window.resetsAt, "2026-11-01T00:00:00.000Z");
assert.equal(window.display, "2,345.68 / 10,000 credits used; 7,654.32 credits remaining");
assert.equal(window.aside, false);
assert.equal(result.balance, "7,654.32 credits remaining");
assert.equal(result.plan, "business");
assert.equal(result.user, "test-user");
});
test("legacy premium requests and zero remaining are not unlimited", () => {
const [window] = parseUsage(premium({ entitlement: 300, remaining: 0 })).windows;
assert.equal(window.used, 100);
assert.equal(window.amount, 300);
assert.equal(window.unit, "requests");
});
test("unlimited allowances are explicitly labelled and non-blocking", () => {
const result = parseUsage({ quota_snapshots: {
chat: { unlimited: true, entitlement: 0, remaining: 0 },
completions: { unlimited: true },
} });
assert.equal(result.windows.length, 2);
for (const window of result.windows) {
assert.equal(window.display, "Unlimited");
assert.equal(window.aside, true);
assert.equal(window.used, 0);
assert.equal(window.limit, undefined);
}
});
test("unlimited premium credits show usage without inventing a seat budget", () => {
for (const [creditsUsed, display] of [
[0, "0 credits used"],
[1234.5, "1,234.5 credits used"],
["1234.5", "1,234.5 credits used"],
]) {
for (const hasQuota of [true, undefined]) {
for (const [billing, root] of [
[{ token_based_billing: true }, {}],
[{}, { token_based_billing: true }],
]) {
const result = parseUsage(premium({
unlimited: true, has_quota: hasQuota, entitlement: "-1",
percent_remaining: 100, credits_used: creditsUsed, ...billing,
}, { copilot_plan: "enterprise", ...root }));
assert.equal(result.windows.length, 1);
const [window] = result.windows;
assert.equal(window.display, display);
assert.equal(window.name, "Premium credits");
assert.equal(window.used, 0);
assert.equal(window.aside, true);
assert.equal(window.amount, undefined);
assert.equal(window.limit, undefined);
assert.equal(result.balance, undefined);
assert.equal(result.error, undefined);
}
}
}
});
test("unlimited allowances ignore unreadable credits and non-credit counters", () => {
for (const creditsUsed of [undefined, null, "many", -1, NaN, Infinity, true]) {
const [window] = parseUsage(premium({
unlimited: true, credits_used: creditsUsed,
}, { token_based_billing: true })).windows;
assert.equal(window.display, "Unlimited");
assert.equal(window.aside, true);
assert.equal(window.limit, undefined);
}
const [requests] = parseUsage(premium({
unlimited: true, token_based_billing: false, credits_used: 1234.5,
}, { token_based_billing: true })).windows;
assert.equal(requests.display, "Unlimited");
const result = parseUsage({ token_based_billing: true, quota_snapshots: {
chat: { unlimited: true, credits_used: 1234.5 },
completions: { unlimited: true, credits_used: 1234.5 },
} });
assert.ok(result.windows.every((window) => window.display === "Unlimited"));
});
test("per-window resets override root reset in seconds and milliseconds", () => {
for (const value of [1793491200, 1793491200000, "2026-11-01T00:00:00Z"]) {
const [window] = parseUsage(premium({ percent_remaining: 50, quota_reset_at: value })).windows;
assert.equal(window.resetsAt, "2026-11-01T00:00:00.000Z");
assert.equal(window.used, 50);
}
});
test("monthly free-plan legacy fields", () => {
const result = parseUsage({
monthly_quotas: { chat: 50, completions: 2000 },
limited_user_quotas: { chat: 30, completions: 0 },
limited_user_reset_date: "2026-11-01",
});
assert.deepEqual(result.windows.map((w) => w.used), [40, 100]);
});
test("paid overage is not added to the included allowance", () => {
const [window] = parseUsage(premium({ entitlement: 300, remaining: 0, overage_count: 20 })).windows;
assert.equal(window.amount, 300);
assert.equal(window.used, 100);
});
test("unknown or malformed quota never becomes zero usage", () => {
for (const quota of [{}, { entitlement: "many", remaining: "some" },
{ entitlement: 0, remaining: 0 }, { percent_remaining: NaN }]) {
const result = parseUsage(premium(quota));
assert.deepEqual(result.windows, []);
assert.ok(result.error);
}
});
test("unknown snapshot types do not create routing windows", () => {
for (const quota of [
{ entitlement: 10, quota_remaining: 0, percent_remaining: 0, unlimited: false },
{ unlimited: true },
]) {
const result = parseUsage({
copilot_plan: "individual", quota_snapshots: { code_review: quota },
});
assert.deepEqual(result.windows, []);
assert.ok(result.error);
assert.equal(result.signIn, "kept");
}
});
test("unknown snapshots do not change known chat and premium quotas", () => {
const data = { quota_snapshots: {
premium_interactions: { entitlement: 300, quota_remaining: 200 },
chat: { unlimited: true },
completions: { entitlement: 2000, remaining: 0 },
} };
const expected = parseUsage(data);
data.quota_snapshots.code_review = { entitlement: 10, quota_remaining: 0 };
assert.deepEqual(parseUsage(data), expected);
});
test("credits used alone cannot determine a finite seat's utilization", () => {
for (const creditsUsed of [0, 400, "400", 2000]) {
const result = parseUsage(premium({
unlimited: false, entitlement: "1000", credits_used: creditsUsed,
}, { token_based_billing: true }));
assert.deepEqual(result.windows, []);
assert.ok(result.error);
assert.equal(result.balance, undefined);
assert.equal(result.signIn, "kept");
}
});
test("organization credits do not supply a denominator for a percent-only seat", () => {
const result = parseUsage(premium({
entitlement: "1000", percent_remaining: 25, credits_used: 1234.5,
}, { token_based_billing: true }));
const [window] = result.windows;
assert.equal(window.used, 75);
assert.equal(window.amount, undefined);
assert.equal(window.limit, undefined);
assert.equal(window.display, undefined);
assert.equal(result.balance, undefined);
});
test("GitHub.com and Enterprise use their own OAuth endpoint without redirecting", async () => {
for (const [enterpriseUrl, origin] of [
[undefined, "https://api.github.com"],
["company.ghe.com", "https://api.company.ghe.com"],
["https://company.ghe.com/", "https://api.company.ghe.com"],
]) {
let called = false;
const result = await readUsage(async () => ({ ...auth, enterpriseUrl }), async (url, init) => {
called = true;
assert.equal(url, `${origin}/copilot_internal/user`);
assert.equal(init.headers.Authorization, "token mock-oauth");
assert.equal(init.redirect, "error");
assert.ok(init.signal instanceof AbortSignal);
return response(premium({ entitlement: 300, remaining: 200 }));
});
assert.ok(called);
assert.equal(result.error, undefined);
}
});
test("unsafe Enterprise URLs are rejected before sending credentials", async () => {
for (const enterpriseUrl of ["http://company.ghe.com", "https://user@company.ghe.com",
"https://company.ghe.com/path", "https://company.ghe.com?query=1"]) {
let called = false;
const result = await readUsage(async () => ({ ...auth, enterpriseUrl }), async () => {
called = true;
return response({});
});
assert.equal(called, false);
assert.ok(result.error);
assert.equal(result.signIn, "kept");
}
});
test("root billing flag is a fallback, the snapshot's explicit flag takes precedence", () => {
const data = premium({ entitlement: 300, remaining: 200, quota_remaining: 0,
token_based_billing: false }, { token_based_billing: true });
const [legacy] = parseUsage(data).windows;
assert.equal(legacy.amount, 300);
assert.equal(legacy.unit, "requests");
delete data.quota_snapshots.premium_interactions.token_based_billing;
const [credits] = parseUsage(data).windows;
assert.equal(credits.amount, 300);
assert.equal(credits.unit, "credits");
});
test("a percent-only snapshot does not invent an absolute balance", () => {
const result = parseUsage(premium({ percent_remaining: 25 }));
assert.equal(result.windows[0].used, 75);
assert.equal(result.windows[0].amount, undefined);
assert.equal(result.windows[0].limit, undefined);
assert.equal(result.balance, undefined);
});
test("an entitlement with only a percentage does not display a fabricated zero count", () => {
const result = parseUsage(premium({ entitlement: "1000", percent_remaining: 25 }));
assert.equal(result.windows[0].used, 75);
// The host defaults a missing amount to 0, so a limit must be omitted too.
assert.equal(result.windows[0].limit, undefined);
assert.equal(result.windows[0].amount, undefined);
});
test("personal premium overage is informational, limited completions never block chat", () => {
const result = parseUsage(premium({ entitlement: 300, remaining: 0,
overage_permitted: true }, { copilot_plan: "individual" }));
assert.equal(result.windows[0].used, 100);
assert.equal(result.windows[0].aside, true);
const completions = parseUsage({ quota_snapshots: {
completions: { entitlement: 2000, remaining: 0 },
} }).windows[0];
assert.equal(completions.used, 100);
assert.equal(completions.aside, true);
});
test("numeric-string reset timestamps work and nonpositive timestamps fall back", () => {
for (const value of ["1793491200", "1793491200000", "0", -1]) {
const [window] = parseUsage(premium({ percent_remaining: 50, quota_reset_at: value })).windows;
assert.equal(window.resetsAt, "2026-11-01T00:00:00.000Z");
}
});
test("a quota read never persists or renews either token", async () => {
const saved = [];
const requests = [];
const expired = { ...auth, access: "", expires: 0 };
const before = structuredClone(expired);
const hooks = await CopilotAuthPlugin({ client: { auth: { set: async (x) => saved.push(x) } } });
globalThis.fetch = async (url, init) => {
requests.push({ url, authorization: new Headers(init?.headers).get("authorization") });
return response(premium({ entitlement: 300, remaining: 150 }));
};
const result = await hooks.auth.usage(async () => expired, { id: "github-copilot" });
assert.equal(result.windows[0]?.used, 50);
assert.deepEqual(requests, [{
url: "https://api.github.com/copilot_internal/user", authorization: "token mock-oauth",
}]);
assert.deepEqual(saved, []);
assert.deepEqual(expired, before);
});
test("an unreadable sign-in stays unknown without sending a request or exposing its error", async () => {
let called = false;
const result = await readUsage(async () => {
throw new Error("mock-oauth credential store could not be read");
}, async () => {
called = true;
return response({});
});
assert.equal(called, false);
assert.equal(result.signIn, "kept");
assert.deepEqual(result.windows, []);
assert.ok(result.error);
assert.ok(!JSON.stringify(result).includes("mock-oauth"));
});
test("only an explicit HTTP 401 expires the sign-in", async () => {
for (const status of [401, 403, 429, 500]) {
const result = await readUsage(getAuth, async () => response({}, status));
assert.equal(result.signIn, status === 401 ? "expired" : "kept");
assert.deepEqual(result.windows, []);
assert.match(result.error, new RegExp(String(status)));
}
});
test("network and invalid JSON errors do not reveal tokens or mark account expired", async () => {
for (const fetcher of [
async () => { throw new Error("mock-oauth secret request headers"); },
async () => new Response("not json"),
async () => response(null),
]) {
const result = await readUsage(getAuth, fetcher);
assert.equal(result.signIn, "kept");
assert.ok(result.error);
assert.ok(!JSON.stringify(result).includes("mock-oauth"));
assert.deepEqual(result.windows, []);
}
});
test("missing sign-in does not make a request or change auth", async () => {
for (const value of [undefined, {}, { type: "api", key: "mock" }]) {
let called = false;
const result = await readUsage(async () => value, async () => {
called = true;
return response({});
});
assert.equal(called, false);
assert.ok(result.error);
assert.equal(result.signIn, "kept");
}
});
// These seat shapes also occur in magpie's built-in Copilot regression tests
// (internal/provider/copilot_usage_test.go, #1063); all values here are synthetic.
test("Business string counters still count when has_quota is false", () => {
const result = parseUsage(premium({
unlimited: false, has_quota: false, entitlement: "1000",
quota_remaining: "250", percent_remaining: 25,
}, { token_based_billing: true }));
assert.equal(result.windows.length, 1);
assert.equal(result.windows[0].used, 75);
assert.equal(result.windows[0].amount, 750);
assert.equal(result.windows[0].limit, 1000);
assert.equal(result.balance, "250 credits remaining");
});
test("managed seats remain blocking even when overage_permitted is true", () => {
for (const plan of ["business", "enterprise"]) {
const result = parseUsage(premium({
unlimited: false, has_quota: false, entitlement: "1000",
percent_remaining: 0, overage_permitted: true,
}, { copilot_plan: plan }));
assert.equal(result.windows[0]?.used, 100);
assert.ok(!result.windows[0]?.aside);
}
});
test("an exhausted Enterprise pool is not unlimited", () => {
const result = parseUsage(premium({
unlimited: true, has_quota: false, entitlement: "0", percent_remaining: 0,
credits_used: 1234.5,
}, { copilot_plan: "enterprise", token_based_billing: true }));
assert.equal(result.windows[0]?.used, 100);
assert.notEqual(result.windows[0]?.display, "Unlimited");
assert.ok(!result.windows[0]?.aside);
assert.equal(result.windows[0]?.resetsAt, "2026-11-01T00:00:00.000Z");
});
test("unlimited chat remains unlimited when has_quota is false", () => {
const result = parseUsage({ quota_snapshots: {
chat: { unlimited: true, has_quota: false, entitlement: "0" },
completions: { unlimited: true, has_quota: false, entitlement: "0" },
} });
assert.equal(result.windows.length, 2);
assert.ok(result.windows.every((w) => w.display === "Unlimited" && w.aside));
});
test("a free seat omits absent premium allowance but counts chat and completion percentages", () => {
const result = parseUsage({ copilot_plan: "free", token_based_billing: true,
quota_snapshots: {
chat: { unlimited: false, has_quota: false, entitlement: "200", percent_remaining: 80 },
completions: { unlimited: false, has_quota: false, entitlement: "4000", percent_remaining: 100 },
premium_interactions: { unlimited: false, has_quota: false, entitlement: "0", percent_remaining: 0 },
},
});
assert.deepEqual(result.windows.map((w) => w.name), ["Chat", "Completions"]);
assert.deepEqual(result.windows.map((w) => w.used), [20, 0]);
assert.equal(result.windows[1].aside, true);
});
+2
View File
@@ -1,6 +1,8 @@
{
"version": 1,
"plugins": [
{ "package": "@magpie-community/opencode-copilot-auth", "name": "GitHub Copilot", "providers": ["github-copilot"], "community": true,
"summary": { "en": "GitHub Copilot on GitHub.com or GitHub Enterprise, with premium request or credit usage, remaining allowance and quota reset dates.", "zh": "GitHub Copilot:支持 GitHub.com 与 GitHub Enterprise,显示高级请求或积分用量、剩余额度和重置时间。" } },
{ "package": "@magpie-community/opencode-joycode-auth", "name": "JoyCode", "providers": ["joycode"], "community": true,
"summary": { "en": "Unofficial JoyCode provider: JD account browser sign-in, live models and credit multipliers, plan credits and streaming tool calls.", "zh": "非官方 JoyCode 插件:京东账号浏览器登录,动态模型与积分倍率、套餐额度及流式工具调用。" } },
{"package": "@magpie-community/opencode-kimi-work-auth", "name": "Kimi Work", "icon": "kimi", "providers": ["kimi-work"], "community": true, "summary": {"en": "Kimi desktop Work subscription through its local sign-in, with live Work models and shared membership usage. Separate from Kimi Code.", "zh": "使用本机普通 Kimi 桌面版的 Work 登录,自动读取 Work 模型和会员共享用量;独立于 Kimi Code。"}},