Skip to content

Commit 22de3b3

Browse files
committed
feat: add OpenCode Go quota usage
1 parent cce6311 commit 22de3b3

2 files changed

Lines changed: 147 additions & 0 deletions

File tree

‎src/providers/quota.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ export const QUOTA_RESPONSE_MAX_BYTES = 512 * 1024;
3939
const KIMI_CODE_BASE_URL = "https://api.kimi.com/coding/v1";
4040
const KIMI_CODE_USAGE_URL = `${KIMI_CODE_BASE_URL}/usages`;
4141
const A6API_BASE_URL = "https://api.a6api.com";
42+
const OPENCODE_GO_BASE_URL = "https://opencode.ai/zen/go/v1";
43+
const OPENCODE_GO_USAGE_URL = `${OPENCODE_GO_BASE_URL}/usage`;
4244
const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
4345
const DEEPSEEK_BASE_URL = "https://api.deepseek.com";
4446
const CLINE_BASE_URL = "https://api.cline.bot";
@@ -309,6 +311,10 @@ function isCanonicalA6apiBaseUrl(baseUrl: string): boolean {
309311
return normalized === A6API_BASE_URL || normalized === `${A6API_BASE_URL}/v1`;
310312
}
311313

314+
function isCanonicalOpenCodeGoBaseUrl(baseUrl: string): boolean {
315+
return normalizedBaseUrl(baseUrl) === OPENCODE_GO_BASE_URL;
316+
}
317+
312318
function isCanonicalOpenRouterBaseUrl(baseUrl: string): boolean {
313319
const normalized = normalizedBaseUrl(baseUrl);
314320
return normalized === OPENROUTER_BASE_URL;
@@ -456,6 +462,54 @@ async function fetchA6apiQuota(provider: string, config: OcxProviderConfig): Pro
456462
});
457463
}
458464

465+
function parseOpenCodeGoUsageWindow(value: unknown): { percent: number; resetAt?: number } | null {
466+
const row = asRecord(value);
467+
if (!row) return null;
468+
const percent = normalizePercent(row.percent);
469+
if (percent === undefined) return null;
470+
const resetAt = normalizeResetAt(row.resetsAt);
471+
return { percent, ...(resetAt !== undefined ? { resetAt } : {}) };
472+
}
473+
474+
async function fetchOpenCodeGoQuota(provider: string, config: OcxProviderConfig): Promise<ProviderQuotaProbeResult> {
475+
// Never send a configured API key when the provider destination is not the built-in Go endpoint.
476+
if (!isCanonicalOpenCodeGoBaseUrl(config.baseUrl)) return null;
477+
const apiKey = resolveEnvValue(config.apiKey)?.trim();
478+
if (!apiKey) return null;
479+
const response = await fetch(OPENCODE_GO_USAGE_URL, {
480+
headers: { Accept: "application/json", Authorization: `Bearer ${apiKey}` },
481+
redirect: "error",
482+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
483+
});
484+
if (!response.ok) {
485+
return response.status >= 400 && response.status < 500 && response.status !== 408 && response.status !== 429
486+
? TERMINAL_QUOTA_FAILURE
487+
: null;
488+
}
489+
const body = asRecord(await readQuotaJson(response));
490+
const usage = asRecord(body?.usage);
491+
if (!usage) return null;
492+
const rolling = parseOpenCodeGoUsageWindow(usage.rolling);
493+
const weekly = parseOpenCodeGoUsageWindow(usage.weekly);
494+
const monthly = parseOpenCodeGoUsageWindow(usage.monthly);
495+
const quota: ProviderQuota = {
496+
...(rolling ? {
497+
fiveHourPercent: rolling.percent,
498+
...(rolling.resetAt !== undefined ? { fiveHourResetAt: rolling.resetAt } : {}),
499+
} : {}),
500+
...(weekly ? {
501+
weeklyPercent: weekly.percent,
502+
...(weekly.resetAt !== undefined ? { weeklyResetAt: weekly.resetAt } : {}),
503+
} : {}),
504+
...(monthly ? {
505+
monthlyPercent: monthly.percent,
506+
...(monthly.resetAt !== undefined ? { monthlyResetAt: monthly.resetAt } : {}),
507+
} : {}),
508+
updatedAt: Date.now(),
509+
};
510+
return report(provider, "opencode-go:usage", quota);
511+
}
512+
459513
/**
460514
* OpenRouter `GET /api/v1/key` — the key's own credit balance and optional
461515
* per-key spending cap. `limit` is the configured cap (absent = uncapped);
@@ -1858,6 +1912,9 @@ async function maybeFetchProviderQuota(
18581912
if (provider.authMode === "key" && isCanonicalKimiCodeBaseUrl(provider.baseUrl)) {
18591913
return fetchKimiQuota(name, provider);
18601914
}
1915+
if ((provider.authMode ?? "key") === "key" && name === "opencode-go") {
1916+
return fetchOpenCodeGoQuota(name, provider);
1917+
}
18611918
if ((provider.authMode ?? "key") === "key" && isCanonicalA6apiBaseUrl(provider.baseUrl)) {
18621919
return fetchA6apiQuota(name, provider);
18631920
}

‎tests/opencode-go-quota.test.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+
import { clearProviderQuotaCache, fetchProviderQuotaReports } from "../src/providers/quota";
3+
import type { OcxConfig } from "../src/types";
4+
5+
const originalFetch = globalThis.fetch;
6+
7+
function openCodeGoConfig(baseUrl = "https://opencode.ai/zen/go/v1"): OcxConfig {
8+
return {
9+
defaultProvider: "opencode-go",
10+
providers: {
11+
"opencode-go": {
12+
adapter: "openai-chat",
13+
authMode: "key",
14+
baseUrl,
15+
apiKey: "opencode-go-secret",
16+
},
17+
},
18+
} as OcxConfig;
19+
}
20+
21+
beforeEach(() => {
22+
clearProviderQuotaCache();
23+
});
24+
25+
afterEach(() => {
26+
globalThis.fetch = originalFetch;
27+
clearProviderQuotaCache();
28+
});
29+
30+
describe("OpenCode Go provider quota", () => {
31+
test("maps the official usage endpoint into canonical quota windows", async () => {
32+
const seen: Array<{ url: string; authorization?: string; redirect?: RequestRedirect }> = [];
33+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
34+
const headers = init?.headers as Record<string, string> | undefined;
35+
seen.push({
36+
url: String(input),
37+
authorization: headers?.Authorization,
38+
redirect: init?.redirect,
39+
});
40+
return new Response(JSON.stringify({
41+
usage: {
42+
rolling: { status: "ok", percent: 12, resetsAt: "2026-08-12T20:00:00.000Z" },
43+
weekly: { status: "ok", percent: 8, resetsAt: "2026-08-17T00:00:00.000Z" },
44+
monthly: { status: "ok", percent: 35, resetsAt: "2026-09-01T00:00:00.000Z" },
45+
},
46+
}), { status: 200, headers: { "content-type": "application/json" } });
47+
}) as typeof fetch;
48+
49+
const result = await fetchProviderQuotaReports(openCodeGoConfig(), true);
50+
51+
expect(result.reports).toHaveLength(1);
52+
expect(result.reports[0]?.provider).toBe("opencode-go");
53+
expect(result.reports[0]?.source).toBe("opencode-go:usage");
54+
expect(result.reports[0]?.quota).toEqual({
55+
fiveHourPercent: 12,
56+
fiveHourResetAt: Date.parse("2026-08-12T20:00:00.000Z"),
57+
weeklyPercent: 8,
58+
weeklyResetAt: Date.parse("2026-08-17T00:00:00.000Z"),
59+
monthlyPercent: 35,
60+
monthlyResetAt: Date.parse("2026-09-01T00:00:00.000Z"),
61+
updatedAt: expect.any(Number),
62+
});
63+
expect(seen).toEqual([{
64+
url: "https://opencode.ai/zen/go/v1/usage",
65+
authorization: "Bearer opencode-go-secret",
66+
redirect: "error",
67+
}]);
68+
expect(JSON.stringify(result)).not.toContain("opencode-go-secret");
69+
});
70+
71+
test("does not probe quota for a noncanonical OpenCode Go destination", async () => {
72+
let fetchCalls = 0;
73+
globalThis.fetch = (async () => {
74+
fetchCalls += 1;
75+
return new Response(JSON.stringify({
76+
usage: {
77+
rolling: { percent: 1, resetsAt: "2026-08-12T20:00:00.000Z" },
78+
},
79+
}), { status: 200, headers: { "content-type": "application/json" } });
80+
}) as typeof fetch;
81+
82+
const result = await fetchProviderQuotaReports(
83+
openCodeGoConfig("https://example.invalid/zen/go/v1"),
84+
true,
85+
);
86+
87+
expect(fetchCalls).toBe(0);
88+
expect(result.reports).toEqual([]);
89+
});
90+
});

0 commit comments

Comments
 (0)