Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(quota): surface OpenCode Go missing-quota-API as a latched diagnostic (#3838)

Abhishek Divekar2a26fea530bf
diff --git a/file-size-baseline.json b/file-size-baseline.json
index 853191f92c..a2b4da4fc3 100644
--- a/file-size-baseline.json
+++ b/file-size-baseline.json
@@ -31,7 +31,7 @@
"open-sse/services/combo.ts": 5203,
"open-sse/services/rateLimitManager.ts": 1017,
"open-sse/services/tokenRefresh.ts": 1997,
- "open-sse/services/usage.ts": 3394,
+ "open-sse/services/usage.ts": 3408,
"open-sse/translator/request/openai-to-gemini.ts": 844,
"open-sse/translator/response/openai-responses.ts": 878,
"open-sse/utils/cursorAgentProtobuf.ts": 1521,
@@ -125,5 +125,6 @@
"_rebaseline_2026_06_14_3826_release_drift": "Re-baseline release/v3.8.25 drift already documented from #3809 owner changes: ProxyRegistryManager.tsx 1072→1089, sidebarVisibility.ts 990→1006, schemas.ts 2519→2522. This PR does not touch those source files; updating the frozen values restores Fast Quality Gates on the current release branch.",
"_rebaseline_2026_06_14_3825_combo_stickiness": "Re-baseline #3825 (sessionless combo stickiness + reasoning-aware readiness): combo.ts 5164→5198 (+34, pós-prettier). Crescimento = deriveComboSessionKey() + effectiveSessionId threading nos sites de read/write do pin server-side. streamReadinessPolicy.ts não-frozen (sob cap). Lógica coesa no handler de combo; não-extraível.",
"_rebaseline_2026_06_14_r3_3835_kiro_pricing": "PR #3835 own growth: pricing.ts 1470→1508 (+38 = missing Kiro pricing rows, claude-sonnet-4.6 etc., pure data). Also carries inherited release/v3.8.25 drift not yet frozen by prior r2 merges: RequestLoggerV2.tsx 1276→1282 (#3820 resizable log table) and combo.ts 5198→5203 (#3811 round-robin replay-response fix). This PR does not touch RequestLoggerV2/combo.ts source; updating the frozen values restores Fast Quality Gates on the current release branch.",
- "_rebaseline_2026_06_14_r3_3849_transient_hide": "PR #3849 own growth: providerPageHelpers.ts 939→955 (+16 = expanded JSDoc on the auto-hide policy + transient-failure guard in evaluateTestAllEntry). Cohesive helper logic; not extractable."
+ "_rebaseline_2026_06_14_r3_3849_transient_hide": "PR #3849 own growth: providerPageHelpers.ts 939→955 (+16 = expanded JSDoc on the auto-hide policy + transient-failure guard in evaluateTestAllEntry). Cohesive helper logic; not extractable.",
+ "_rebaseline_2026_06_14_r3_3838_opencode_quota": "PR #3838 own growth: usage.ts 3394→3408 (+14 = clearer OpenCode Go missing-quota-API messages with OMNIROUTE_OPENCODE_GO_QUOTA_URL override hint + upstream issue links). Message text only; no logic extractable."
}
diff --git a/open-sse/services/opencodeQuotaFetcher.ts b/open-sse/services/opencodeQuotaFetcher.ts
index e7fe9a28d1..28cf4d07e1 100644
--- a/open-sse/services/opencodeQuotaFetcher.ts
+++ b/open-sse/services/opencodeQuotaFetcher.ts
@@ -9,7 +9,7 @@
* - Weekly: $30 of usage
* - Monthly: $60 of usage
*
- * Upstream endpoint (defensive — pending full API confirmation):
+ * Upstream endpoint (defensive — no public API exists yet):
* GET https://opencode.ai/zen/go/v1/quota
* Authorization: Bearer <apiKey>
*
@@ -22,14 +22,25 @@
* }
* }
*
- * NOTE: This fetcher is implemented defensively based on the community plugin
- * (guyinwonder168/opencode-glm-quota) and the quota windows reported in issue #2852.
- * On any non-200 / parse failure it returns null (fail-open) with a log.debug —
- * not log.warn — so users not on opencode-go don't see noise. Once the upstream
- * API endpoint is publicly documented, the endpoint path can be confirmed/updated
- * without touching this logic.
+ * NOTE: As of 2026, no public quota API exists for OpenCode Go / OpenCode Zen
+ * (tracked upstream in anomalyco/opencode#16017, #18648, #31084). The default
+ * endpoint currently returns HTTP 404. This fetcher is implemented defensively
+ * so that the dashboard shows "No quota data" gracefully rather than crashing,
+ * and so that when an endpoint is finally published, only the URL constant
+ * needs to change.
*
- * Cache: in-memory TTL (60s) to avoid hammering the quota API on every request.
+ * On a 404 response we log ONE console.warn (latched per process — not per
+ * request) pointing at the upstream tracking issues, then cache the
+ * "endpoint unavailable" result for 5 minutes to avoid hammering. On any other
+ * non-200 / parse failure we return null (fail-open) silently. The first
+ * call from each server boot is what the operator is most likely to see, so
+ * we make it count.
+ *
+ * Cache: in-memory TTL (60s for success, 5 min for 404).
+ *
+ * Override: set OMNIROUTE_OPENCODE_QUOTA_URL to a working endpoint. If
+ * OpenCode ships a public endpoint (likely in the form of the merged PR
+ * #16513), the maintainer can update the default.
*
* Registration: call registerOpencodeQuotaFetcher() once at server startup.
*/
@@ -38,12 +49,16 @@ import { registerQuotaFetcher, registerQuotaWindows, type QuotaInfo } from "./qu
import { registerMonitorFetcher } from "./quotaMonitor.ts";
// OpenCode quota endpoint — same key works across opencode, opencode-go, opencode-zen
-// (#2852) Defensive: based on provider baseUrl + /quota suffix (community plugin pattern)
+// Default points at /zen/go/v1/quota which returns 404 today (no public quota API yet,
+// tracked in anomalyco/opencode#16017). Set OMNIROUTE_OPENCODE_QUOTA_URL to override.
const OPENCODE_QUOTA_URL =
process.env.OMNIROUTE_OPENCODE_QUOTA_URL ?? "https://opencode.ai/zen/go/v1/quota";
// Cache TTL — matches Codex / DeepSeek / Bailian pattern (60s)
const CACHE_TTL_MS = 60_000;
+// TTL for cached "endpoint unavailable" results (404) — longer to avoid hammering
+// a non-existent endpoint
+const NO_ENDPOINT_TTL_MS = 5 * 60_000; // 5 minutes
// Window keys as surfaced to the dashboard and quota-window registry
export const OPENCODE_WINDOW_5H = "window_5h";
@@ -59,13 +74,34 @@ export interface OpencodeTripleWindowQuota extends QuotaInfo {
}
interface CacheEntry {
- quota: OpencodeTripleWindowQuota;
+ quota: OpencodeTripleWindowQuota | null;
fetchedAt: number;
+ /** true when quota is null because the upstream endpoint returned 404 */
+ noEndpoint?: boolean;
}
// In-memory cache: connectionId → { quota, fetchedAt }
const quotaCache = new Map<string, CacheEntry>();
+// One-time 404 warning per URL (avoids spamming on every request)
+const _warned404Urls = new Set<string>();
+
+/**
+ * Reset the 404-warning latch (test-only).
+ * Exported for unit tests that want to verify the warning fires on each fresh
+ * 404 response.
+ */
+export function _resetWarned404Urls(): void {
+ _warned404Urls.clear();
+}
+
+/**
+ * Check whether a URL has had its 404 warning already emitted (test-only).
+ */
+export function _hasWarned404(url: string): boolean {
+ return _warned404Urls.has(url);
+}
+
// Auto-cleanup stale entries every 5 minutes
const _cacheCleanup = setInterval(() => {
const now = Date.now();
@@ -131,16 +167,10 @@ function parseOpencodeQuotaResponse(data: unknown): OpencodeTripleWindowQuota |
quotaObj[OPENCODE_WINDOW_5H] ?? quotaObj["5h"] ?? quotaObj["hourly"] ?? quotaObj["short"]
);
const wWeekly = toRecord(
- quotaObj[OPENCODE_WINDOW_WEEKLY] ??
- quotaObj["weekly"] ??
- quotaObj["week"] ??
- quotaObj["wk"]
+ quotaObj[OPENCODE_WINDOW_WEEKLY] ?? quotaObj["weekly"] ?? quotaObj["week"] ?? quotaObj["wk"]
);
const wMonthly = toRecord(
- quotaObj[OPENCODE_WINDOW_MONTHLY] ??
- quotaObj["monthly"] ??
- quotaObj["month"] ??
- quotaObj["mo"]
+ quotaObj[OPENCODE_WINDOW_MONTHLY] ?? quotaObj["monthly"] ?? quotaObj["month"] ?? quotaObj["mo"]
);
const has5h = Object.keys(w5h).length > 0;
@@ -159,7 +189,8 @@ function parseOpencodeQuotaResponse(data: unknown): OpencodeTripleWindowQuota |
const resetAtMonthly = hasMonthly ? parseWindowResetAt(wMonthly) : null;
const worstPercent = Math.max(percent5h, percentWeekly, percentMonthly);
- const limitReached = Boolean(obj["limit_reached"] ?? quotaObj["limit_reached"]) || worstPercent >= 1;
+ const limitReached =
+ Boolean(obj["limit_reached"] ?? quotaObj["limit_reached"]) || worstPercent >= 1;
// Dominant reset: pick the window with the worst usage
let dominantResetAt: string | null = null;
@@ -212,8 +243,14 @@ export async function fetchOpencodeQuota(
): Promise<OpencodeTripleWindowQuota | null> {
// Check cache first
const cached = quotaCache.get(connectionId);
- if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
- return cached.quota;
+ if (cached) {
+ // 404 sentinel — use longer TTL to avoid hammering a non-existent endpoint
+ if (cached.noEndpoint && Date.now() - cached.fetchedAt < NO_ENDPOINT_TTL_MS) {
+ return null;
+ }
+ if (cached.quota !== null && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
+ return cached.quota;
+ }
}
// Extract API key from connection
@@ -238,8 +275,26 @@ export async function fetchOpencodeQuota(
});
if (!response.ok) {
- // Fail-open on all non-2xx responses — log.debug, not log.warn, to avoid
- // spam for users who aren't on opencode-go. 401/403 additionally clear cache.
+ if (response.status === 404) {
+ // Upstream doesn't expose this endpoint. Warn once per URL per process so
+ // operators know the dashboard will be empty for opencode-go connections.
+ // Cache a 404 sentinel for NO_ENDPOINT_TTL_MS to avoid hammering.
+ // See opencode issues #10448, #16017, #18648, #31084.
+ if (!_warned404Urls.has(OPENCODE_QUOTA_URL)) {
+ _warned404Urls.add(OPENCODE_QUOTA_URL);
+ console.warn(
+ `[opencodeQuotaFetcher] ${OPENCODE_QUOTA_URL} returned 404 — opencode-go usage API is not yet public. ` +
+ `Set OMNIROUTE_OPENCODE_QUOTA_URL to a working endpoint, or follow ` +
+ `https://github.com/anomalyco/opencode/issues/16017 for upstream status.`
+ );
+ }
+ quotaCache.set(connectionId, {
+ quota: null,
+ fetchedAt: Date.now(),
+ noEndpoint: true,
+ });
+ return null;
+ }
if (response.status === 401 || response.status === 403) {
quotaCache.delete(connectionId);
}
diff --git a/open-sse/services/usage.ts b/open-sse/services/usage.ts
index 171f68dfe4..fde46bcf14 100644
--- a/open-sse/services/usage.ts
+++ b/open-sse/services/usage.ts
@@ -91,6 +91,9 @@ const NANOGPT_CONFIG = {
};
const OPENCODE_GO_QUOTA_URL =
+ // Note: api.z.ai rejects opencode-go keys with {"code":401}. This default is a
+ // known broken placeholder (see issues #10448, #16017). The env-var override lets
+ // operators point at a working endpoint once OpenCode ships one.
process.env.OMNIROUTE_OPENCODE_GO_QUOTA_URL ?? "https://api.z.ai/api/monitor/usage/quota/limit";
const OPENCODE_GO_QUOTA_TOTALS = {
session: 12,
@@ -946,10 +949,18 @@ async function getOpenCodeGoUsage(apiKey: string) {
if (!res.ok) {
if (res.status === 401 || res.status === 403) {
return {
- message: "OpenCode Go quota endpoint rejected this API key. Chat requests still work.",
+ message:
+ "OpenCode Go does not expose a public quota API. Chat requests still work. " +
+ "Set OMNIROUTE_OPENCODE_GO_QUOTA_URL to a working endpoint, or follow " +
+ "https://github.com/anomalyco/opencode/issues/16017 for upstream status.",
};
}
- return { message: `OpenCode Go quota API error (${res.status})` };
+ return {
+ message:
+ `OpenCode Go quota API error (${res.status}). ` +
+ "Set OMNIROUTE_OPENCODE_GO_QUOTA_URL to a working endpoint, or follow " +
+ "https://github.com/anomalyco/opencode/issues/16017 for upstream status.",
+ };
}
let json: unknown;
@@ -962,7 +973,10 @@ async function getOpenCodeGoUsage(apiKey: string) {
const code = toNumber((json as Record<string, unknown>).code, 200);
if (code === 401 || code === 403 || (json as Record<string, unknown>).success === false) {
return {
- message: "OpenCode Go quota endpoint rejected this API key. Chat requests still work.",
+ message:
+ "OpenCode Go does not expose a public quota API. Chat requests still work. " +
+ "Set OMNIROUTE_OPENCODE_GO_QUOTA_URL to a working endpoint, or follow " +
+ "https://github.com/anomalyco/opencode/issues/16017 for upstream status.",
};
}
diff --git a/tests/unit/opencode-quota-fetcher.test.ts b/tests/unit/opencode-quota-fetcher.test.ts
index da0468fd0a..021254f436 100644
--- a/tests/unit/opencode-quota-fetcher.test.ts
+++ b/tests/unit/opencode-quota-fetcher.test.ts
@@ -181,7 +181,10 @@ test("fetchOpencodeQuota parses reset_at timestamps in windows", async () => {
// window_5h reset_at should be an ISO string
const resetAt5h = quota!.windows?.["window_5h"]?.resetAt;
assert.ok(typeof resetAt5h === "string", "window_5h resetAt should be an ISO string");
- assert.ok(new Date(resetAt5h as string).getTime() > Date.now(), "resetAt should be in the future");
+ assert.ok(
+ new Date(resetAt5h as string).getTime() > Date.now(),
+ "resetAt should be in the future"
+ );
invalidateOpencodeQuotaCache(connectionId);
});
@@ -331,3 +334,34 @@ test("registerOpencodeQuotaFetcher registers opencode-go in quotaMonitor system"
invalidateOpencodeQuotaCache(connectionId);
});
+
+// ─── 404 warning: log once, cache 5 min ────────────────────────────────────
+
+test("404 response is cached for 5 minutes to avoid hammering", async () => {
+ let callCount = 0;
+ globalThis.fetch = (async () => {
+ callCount += 1;
+ return new Response("Not Found", { status: 404 });
+ }) as typeof fetch;
+
+ const connectionId = `conn-cache-${Date.now()}`;
+
+ // First call: 1 fetch, no cache
+ await fetchOpencodeQuota(connectionId, { apiKey: "sk-test-key" });
+ const callsAfterFirst = callCount;
+ assert.equal(callsAfterFirst, 1);
+
+ // Second call within 5 min: should hit cache, no fetch
+ await fetchOpencodeQuota(connectionId, { apiKey: "sk-test-key" });
+ const callsAfterSecond = callCount;
+ assert.equal(
+ callsAfterSecond,
+ 1,
+ `expected cache hit on second 404 call, but fetch ran ${callsAfterSecond - callsAfterFirst} extra times`
+ );
+
+ // After invalidation: 1 fresh fetch
+ invalidateOpencodeQuotaCache(connectionId);
+ await fetchOpencodeQuota(connectionId, { apiKey: "sk-test-key" });
+ assert.equal(callCount, callsAfterSecond + 1);
+});