Skip to content

Commit 9855b0d

Browse files
committed
feat: add best-effort OpenCode Go quota adapter
Display the OpenCode Go plan's rolling 5h, weekly, and monthly usage windows in the footer and /quota output for the active opencode-go model. Usage comes from GET https://opencode.ai/zen/go/v1/usage using the active provider credential (or $OPENCODE_API_KEY). The endpoint is unofficial (anomalyco/opencode#31084 was closed without an official API) and reports only percentages, so the adapter is best effort and keeps the last good snapshot on failure.
1 parent 4fbd815 commit 9855b0d

5 files changed

Lines changed: 92 additions & 1 deletion

File tree

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,15 @@ A [pi](https://pi.dev) extension that displays quota for the **currently selecte
99
| Z.ai (`zai`) | Coding-plan quota windows | Pi provider auth, or `$ZAI_API_KEY` / `$Z_AI_API_KEY` | Unofficial usage endpoint |
1010
| OpenAI Codex (`openai-codex`) | Rate-limit windows and reset countdowns | Pi ChatGPT OAuth / subscription auth | Private ChatGPT backend endpoint |
1111
| GitHub Copilot (`github-copilot`) | Monthly premium interactions quota | Pi GitHub Copilot auth | Undocumented endpoint; best effort |
12+
| OpenCode Go (`opencode-go`) | Rolling 5h / weekly / monthly plan windows | Pi `opencode-go` auth, or `$OPENCODE_API_KEY` | Unofficial workspace usage endpoint |
1213

1314
Codex usage is only shown for `openai-codex` OAuth/subscription auth. An OpenAI API key uses a different billing system and is not represented as a Codex subscription quota. Codex window labels come from their reported durations, not assumed primary/secondary positions.
1415

1516
The GitHub Copilot adapter uses `GET https://api.github.com/copilot_internal/user`. This endpoint is undocumented and may change. Pi's resolved Copilot API token is not accepted by this endpoint, so the adapter reads the original GitHub OAuth token from the active Pi `auth.json` entry (using Pi's configured agent directory) and sends it only to GitHub's API host. It is never logged or persisted by this extension. The adapter is best effort and retains the last successful display if a later refresh fails.
1617

1718
## Display and commands
1819

19-
- Footer examples: `Codex 5h 16% (3h) · 1w 3% (6d 22h)` and `GitHub Copilot 1mo 54% (12d)`. The Copilot display omits chat and code-completion quotas.
20+
- Footer examples: `Codex 5h 16% (3h) · 1w 3% (6d 22h)`, `GitHub Copilot 1mo 54% (12d)`, and `OpenCode Go 5h 1% (2h) · 1w 0% (6d) · 1mo 0% (30d)`. The Copilot display omits chat and code-completion quotas.
2021
- Percentages are usage percentages, colored warning at ≥70% and error at ≥90%; reset countdowns are dim.
2122
- The built-in footer is preserved; quota text is right-aligned on its last line, or given its own line if needed.
2223
- Refreshes on session start, provider/model switch, after each turn (throttled), and every 5 minutes while quota data is available. Responses are cached for 60 seconds.
@@ -39,6 +40,7 @@ Shared results and the `QuotaProvider` contract live in `quota-types.ts`; common
3940
- Z.ai calls `GET https://api.z.ai/api/monitor/usage/quota/limit` using the active provider's credential (or the Z.ai environment fallback).
4041
- Codex calls `GET https://chatgpt.com/backend-api/wham/usage` with the OAuth bearer token and `ChatGPT-Account-Id` extracted from the token claims. This is a private backend endpoint, not a documented OpenAI API.
4142
- GitHub Copilot calls `GET https://api.github.com/copilot_internal/user` with the original OAuth token from Pi's active `github-copilot` auth entry. It displays only `quota_snapshots.premium_interactions`, labeled `1mo` to identify its monthly window.
43+
- OpenCode Go calls `GET https://opencode.ai/zen/go/v1/usage` with the active `opencode-go` credential. The endpoint reports only usage percentages for `rolling` (5h), `weekly`, and `monthly` windows, so each sample is shown as a percent against an implicit 100. It is an unofficial workspace endpoint (no public API exists; see `anomalyco/opencode#31084`), so the adapter is best effort and keeps the last successful display on failure.
4244

4345
No provider credential is copied or persisted by this extension. It asks Pi's model registry for active-provider auth and, for the GitHub Copilot endpoint only, reads the existing OAuth token from the auth file Pi uses for the active agent directory.
4446

‎providers/opencode-go.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2+
import type { QuotaProvider, QuotaSample, QuotaSnapshot } from "../quota-types.ts";
3+
import { asRecord, clampPercent, fetchJson, finiteNumber, getProviderToken, timestampMs } from "../quota-utils.ts";
4+
5+
const PROVIDER_ID = "opencode-go";
6+
const USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
7+
8+
/** Server window key -> display label. The endpoint reports only percentages. */
9+
const WINDOWS: ReadonlyArray<readonly [key: string, label: string]> = [
10+
["rolling", "5h"],
11+
["weekly", "1w"],
12+
["monthly", "1mo"],
13+
];
14+
15+
function parseWindow(value: unknown, label: string): QuotaSample | undefined {
16+
const window = asRecord(value);
17+
if (!window) return undefined;
18+
const percent = finiteNumber(window.percent);
19+
if (percent === undefined) return undefined;
20+
return {
21+
label,
22+
percent: clampPercent(percent),
23+
used: percent,
24+
total: 100,
25+
resetMs: timestampMs(window.resetsAt ?? window.resets_at),
26+
};
27+
}
28+
29+
export function parseOpenCodeUsage(payload: unknown, now = Date.now()): QuotaSnapshot {
30+
const usage = asRecord(asRecord(payload)?.usage);
31+
if (!usage) throw new Error("Unexpected OpenCode Go usage response: missing usage");
32+
const samples = WINDOWS
33+
.map(([key, label]) => parseWindow(usage[key], label))
34+
.filter((sample): sample is QuotaSample => sample !== undefined);
35+
if (samples.length === 0) throw new Error("OpenCode Go response contained no usage windows");
36+
return { fetchedAt: now, provider: "OpenCode Go", samples };
37+
}
38+
39+
async function fetch(ctx: ExtensionContext): Promise<QuotaSnapshot | undefined> {
40+
if (!ctx.model || ctx.model.provider !== PROVIDER_ID) return undefined;
41+
const token = await getProviderToken(ctx, PROVIDER_ID) ?? process.env.OPENCODE_API_KEY;
42+
if (!token) return undefined;
43+
const payload = await fetchJson(USAGE_URL, token);
44+
return parseOpenCodeUsage(payload);
45+
}
46+
47+
export const openCodeGoQuotaProvider: QuotaProvider = { providerId: PROVIDER_ID, fetch };

‎quota-providers.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
22
import type { QuotaProvider, QuotaSnapshot } from "./quota-types.ts";
33
import { githubCopilotQuotaProvider } from "./providers/github-copilot.ts";
44
import { openAICodexQuotaProvider } from "./providers/openai-codex.ts";
5+
import { openCodeGoQuotaProvider } from "./providers/opencode-go.ts";
56
import { zaiQuotaProvider } from "./providers/zai.ts";
67

78
/** Provider registry; adapters each implement the shared QuotaProvider contract. */
89
export const quotaProviders: readonly QuotaProvider[] = [
910
zaiQuotaProvider,
1011
openAICodexQuotaProvider,
1112
githubCopilotQuotaProvider,
13+
openCodeGoQuotaProvider,
1214
];
1315

1416
const providersById = new Map(quotaProviders.map((provider) => [provider.providerId, provider]));

‎quota.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* - Z.ai: coding-plan quota endpoint (provider `zai`)
66
* - OpenAI Codex: ChatGPT subscription usage endpoint (provider `openai-codex` + OAuth)
77
* - GitHub Copilot: undocumented quota endpoint (provider `github-copilot`, best effort)
8+
* - OpenCode Go: unofficial workspace usage endpoint (provider `opencode-go`, best effort)
89
*
910
* Each adapter normalizes its response into shared quota samples. No matching
1011
* provider credential means no quota is fetched or rendered.

‎test/provider-test.mjs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@ const quota = await jiti.import(new URL("../quota-providers.ts", import.meta.url
1010
const zai = await jiti.import(new URL("../providers/zai.ts", import.meta.url).pathname);
1111
const codex = await jiti.import(new URL("../providers/openai-codex.ts", import.meta.url).pathname);
1212
const copilot = await jiti.import(new URL("../providers/github-copilot.ts", import.meta.url).pathname);
13+
const opencodeGo = await jiti.import(new URL("../providers/opencode-go.ts", import.meta.url).pathname);
1314

1415
test("provider registry contains one adapter per supported provider", () => {
1516
assert.deepEqual(quota.quotaProviders.map((provider) => provider.providerId), [
1617
"zai",
1718
"openai-codex",
1819
"github-copilot",
20+
"opencode-go",
1921
]);
2022
});
2123

@@ -136,6 +138,43 @@ test("Copilot adapter uses the stored original OAuth token for its undocumented
136138
assert.equal(authorization, "Bearer raw-github-oauth-token");
137139
});
138140

141+
test("OpenCode Go response parses the rolling/weekly/monthly windows", () => {
142+
const snapshot = opencodeGo.parseOpenCodeUsage({
143+
usage: {
144+
rolling: { status: "ok", percent: 40, resetsAt: "2026-05-01T12:00:00.000Z" },
145+
weekly: { status: "ok", percent: 78 },
146+
monthly: { status: "ok", percent: 82, resetsAt: "2026-06-01T00:00:00.000Z" },
147+
},
148+
}, 1234);
149+
assert.equal(snapshot.provider, "OpenCode Go");
150+
assert.deepEqual(snapshot.samples.map(({ label, percent, used, total, resetMs }) => ({ label, percent, used, total, resetMs })), [
151+
{ label: "5h", percent: 40, used: 40, total: 100, resetMs: Date.parse("2026-05-01T12:00:00.000Z") },
152+
{ label: "1w", percent: 78, used: 78, total: 100, resetMs: undefined },
153+
{ label: "1mo", percent: 82, used: 82, total: 100, resetMs: Date.parse("2026-06-01T00:00:00.000Z") },
154+
]);
155+
assert.throws(() => opencodeGo.parseOpenCodeUsage({}), /missing usage/i);
156+
assert.throws(() => opencodeGo.parseOpenCodeUsage({ usage: {} }), /no usage windows/i);
157+
});
158+
159+
test("OpenCode Go adapter calls the workspace usage endpoint with active-provider auth", async (t) => {
160+
let requested;
161+
const originalFetch = globalThis.fetch;
162+
globalThis.fetch = async (url, init) => {
163+
requested = { url, init };
164+
return new Response(JSON.stringify({
165+
usage: { rolling: { percent: 12, resetsAt: "2026-05-01T12:00:00.000Z" } },
166+
}), { status: 200 });
167+
};
168+
t.after(() => { globalThis.fetch = originalFetch; });
169+
170+
const snapshot = await quota.fetchCurrentQuota(context("opencode-go", { token: "go-workspace-key" }));
171+
assert.equal(snapshot.provider, "OpenCode Go");
172+
assert.equal(snapshot.samples[0].percent, 12);
173+
assert.equal(requested.url, "https://opencode.ai/zen/go/v1/usage");
174+
assert.equal(requested.init.headers.Authorization, "Bearer go-workspace-key");
175+
assert.equal(await quota.fetchCurrentQuota(context("opencode-go")), undefined);
176+
});
177+
139178
test("ChatGPT account id is extracted from Codex OAuth JWT", () => {
140179
const token = makeJwt({ "https://api.openai.com/auth": { chatgpt_account_id: " acct-123 " } });
141180
assert.equal(codex.extractChatGptAccountId(token), "acct-123");

0 commit comments

Comments
 (0)