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
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
fix(usage): add opencode quota fetcher (#2852) (#2867)
Diego Rodrigues de Sa e Souza517c3c6e4410
diff --git a/.env.example b/.env.exampleindex c7e4911e4a..7bf499eec8 100644--- a/.env.example+++ b/.env.example@@ -346,6 +346,7 @@ NEXT_PUBLIC_CLOUD_URL=#OMNIROUTE_CROF_USAGE_URL=https://crof.ai/usage_api/#OMNIROUTE_GEMINI_CLI_USAGE_URL=https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist#OMNIROUTE_CODEWHISPERER_BASE_URL=https://codewhisperer.us-east-1.amazonaws.com+#OMNIROUTE_OPENCODE_QUOTA_URL=https://opencode.ai/zen/go/v1/quota# ═══════════════════════════════════════════════════════════════════════════════diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e8aec3036a..8a5e36cfc2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,10 @@## [Unreleased]+### 🔧 Bug Fixes++- **fix(usage):** add opencode-go / opencode / opencode-zen quota fetcher so the provider limits page surfaces $12/5h, $30/wk, $60/mo windows alongside other quota-aware providers ([#2852](https://github.com/diegosouzapw/OmniRoute/issues/2852) — thanks @apoapostolov)+---## [3.8.6-patch] — 2026-05-27diff --git a/open-sse/services/opencodeQuotaFetcher.ts b/open-sse/services/opencodeQuotaFetcher.tsnew file mode 100644index 0000000000..e7fe9a28d1--- /dev/null+++ b/open-sse/services/opencodeQuotaFetcher.ts@@ -0,0 +1,296 @@+/**+ * opencodeQuotaFetcher.ts — OpenCode Go / OpenCode / OpenCode Zen Quota Fetcher+ *+ * Implements QuotaFetcher for the opencode-go, opencode, and opencode-zen providers+ * (quotaPreflight.ts + quotaMonitor.ts).+ *+ * OpenCode Go has THREE independent quota windows per subscription:+ * - 5-hour (rolling): $12 of usage+ * - Weekly: $30 of usage+ * - Monthly: $60 of usage+ *+ * Upstream endpoint (defensive — pending full API confirmation):+ * GET https://opencode.ai/zen/go/v1/quota+ * Authorization: Bearer <apiKey>+ *+ * Expected response shape:+ * {+ * quota: {+ * window_5h: { used: number, limit: number, reset_at: number | null },+ * window_weekly: { used: number, limit: number, reset_at: number | null },+ * window_monthly: { used: number, limit: number, reset_at: number | null }+ * }+ * }+ *+ * 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.+ *+ * Cache: in-memory TTL (60s) to avoid hammering the quota API on every request.+ *+ * Registration: call registerOpencodeQuotaFetcher() once at server startup.+ */++import { registerQuotaFetcher, registerQuotaWindows, type QuotaInfo } from "./quotaPreflight.ts";+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)+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;++// Window keys as surfaced to the dashboard and quota-window registry+export const OPENCODE_WINDOW_5H = "window_5h";+export const OPENCODE_WINDOW_WEEKLY = "window_weekly";+export const OPENCODE_WINDOW_MONTHLY = "window_monthly";++// Triple-window quota info+export interface OpencodeTripleWindowQuota extends QuotaInfo {+ window5h: { percentUsed: number; resetAt: string | null };+ windowWeekly: { percentUsed: number; resetAt: string | null };+ windowMonthly: { percentUsed: number; resetAt: string | null };+ limitReached: boolean;+}++interface CacheEntry {+ quota: OpencodeTripleWindowQuota;+ fetchedAt: number;+}++// In-memory cache: connectionId → { quota, fetchedAt }+const quotaCache = new Map<string, CacheEntry>();++// Auto-cleanup stale entries every 5 minutes+const _cacheCleanup = setInterval(() => {+ const now = Date.now();+ for (const [key, entry] of quotaCache) {+ if (now - entry.fetchedAt > CACHE_TTL_MS * 5) {+ quotaCache.delete(key);+ }+ }+}, 5 * 60_000);++if (typeof _cacheCleanup === "object" && "unref" in _cacheCleanup) {+ (_cacheCleanup as { unref?: () => void }).unref?.();+}++// ─── Helpers ──────────────────────────────────────────────────────────────────++function toNumber(value: unknown, fallback = 0): number {+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value === "string") {+ const parsed = parseFloat(value);+ if (Number.isFinite(parsed)) return parsed;+ }+ return fallback;+}++function toRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++function parseWindowResetAt(window: Record<string, unknown>): string | null {+ const resetAt = toNumber(window["reset_at"] ?? window["resetAt"], 0);+ if (resetAt > 0) {+ // Unix timestamp in seconds (< 1e12) or milliseconds (>= 1e12)+ return new Date(resetAt < 1e12 ? resetAt * 1000 : resetAt).toISOString();+ }+ const resetAfterSeconds = toNumber(+ window["reset_after_seconds"] ?? window["resetAfterSeconds"],+ 0+ );+ if (resetAfterSeconds > 0) {+ return new Date(Date.now() + resetAfterSeconds * 1000).toISOString();+ }+ return null;+}++function parseWindowPercent(window: Record<string, unknown>): number {+ const used = toNumber(window["used"] ?? window["used_amount"], 0);+ const limit = toNumber(window["limit"] ?? window["limit_amount"], 0);+ if (limit <= 0) return 0;+ return Math.max(0, Math.min(1, used / limit));+}++// ─── Response Parser ──────────────────────────────────────────────────────────++function parseOpencodeQuotaResponse(data: unknown): OpencodeTripleWindowQuota | null {+ const obj = toRecord(data);+ const quotaObj = toRecord(obj["quota"] ?? obj["data"] ?? obj["usage"]);++ // Look for windows under various possible keys+ const w5h = toRecord(+ quotaObj[OPENCODE_WINDOW_5H] ?? quotaObj["5h"] ?? quotaObj["hourly"] ?? quotaObj["short"]+ );+ const wWeekly = toRecord(+ quotaObj[OPENCODE_WINDOW_WEEKLY] ??+ quotaObj["weekly"] ??+ quotaObj["week"] ??+ quotaObj["wk"]+ );+ const wMonthly = toRecord(+ quotaObj[OPENCODE_WINDOW_MONTHLY] ??+ quotaObj["monthly"] ??+ quotaObj["month"] ??+ quotaObj["mo"]+ );++ const has5h = Object.keys(w5h).length > 0;+ const hasWeekly = Object.keys(wWeekly).length > 0;+ const hasMonthly = Object.keys(wMonthly).length > 0;++ // Need at least one window to be meaningful+ if (!has5h && !hasWeekly && !hasMonthly) return null;++ const percent5h = has5h ? parseWindowPercent(w5h) : 0;+ const percentWeekly = hasWeekly ? parseWindowPercent(wWeekly) : 0;+ const percentMonthly = hasMonthly ? parseWindowPercent(wMonthly) : 0;++ const resetAt5h = has5h ? parseWindowResetAt(w5h) : null;+ const resetAtWeekly = hasWeekly ? parseWindowResetAt(wWeekly) : null;+ const resetAtMonthly = hasMonthly ? parseWindowResetAt(wMonthly) : null;++ const worstPercent = Math.max(percent5h, percentWeekly, percentMonthly);+ 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;+ if (worstPercent === percent5h) {+ dominantResetAt = resetAt5h ?? resetAtWeekly ?? resetAtMonthly;+ } else if (worstPercent === percentWeekly) {+ dominantResetAt = resetAtWeekly ?? resetAt5h ?? resetAtMonthly;+ } else {+ dominantResetAt = resetAtMonthly ?? resetAtWeekly ?? resetAt5h;+ }++ const window5h = { percentUsed: percent5h, resetAt: resetAt5h };+ const windowWeekly = { percentUsed: percentWeekly, resetAt: resetAtWeekly };+ const windowMonthly = { percentUsed: percentMonthly, resetAt: resetAtMonthly };++ const windows: Record<string, { percentUsed: number; resetAt: string | null }> = {};+ if (has5h) windows[OPENCODE_WINDOW_5H] = window5h;+ if (hasWeekly) windows[OPENCODE_WINDOW_WEEKLY] = windowWeekly;+ if (hasMonthly) windows[OPENCODE_WINDOW_MONTHLY] = windowMonthly;++ return {+ used: worstPercent * 100,+ total: 100,+ percentUsed: worstPercent,+ resetAt: dominantResetAt,+ windows,+ window5h,+ windowWeekly,+ windowMonthly,+ limitReached,+ };+}++// ─── Core Fetcher ─────────────────────────────────────────────────────────────++/**+ * Fetch current quota for an OpenCode connection.+ * Returns percentUsed = max(5h%, weekly%, monthly%) — worst-case across all windows.+ *+ * Defensive implementation: returns null on any non-200 / parse failure (fail-open).+ * See module-level JSDoc for upstream API stability note.+ *+ * @param connectionId - Connection ID from the DB (used for cache keying)+ * @param connection - Optional connection snapshot with apiKey+ * @returns OpencodeTripleWindowQuota or null if fetch fails / no credentials+ */+export async function fetchOpencodeQuota(+ connectionId: string,+ connection?: Record<string, unknown>+): Promise<OpencodeTripleWindowQuota | null> {+ // Check cache first+ const cached = quotaCache.get(connectionId);+ if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {+ return cached.quota;+ }++ // Extract API key from connection+ const apiKey =+ typeof connection?.apiKey === "string" && connection.apiKey.trim().length > 0+ ? connection.apiKey+ : null;++ if (!apiKey) {+ return null;+ }++ try {+ const response = await fetch(OPENCODE_QUOTA_URL, {+ method: "GET",+ headers: {+ Authorization: `Bearer ${apiKey}`,+ "Content-Type": "application/json",+ Accept: "application/json",+ },+ signal: AbortSignal.timeout(8_000),+ });++ 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 === 401 || response.status === 403) {+ quotaCache.delete(connectionId);+ }+ return null;+ }++ let data: unknown;+ try {+ data = await response.json();+ } catch {+ // Malformed JSON — fail open+ return null;+ }++ const quota = parseOpencodeQuotaResponse(data);+ if (!quota) return null;++ // Store in cache+ quotaCache.set(connectionId, { quota, fetchedAt: Date.now() });+ return quota;+ } catch {+ // Network error, timeout, etc. — fail open+ return null;+ }+}++// ─── Invalidation ─────────────────────────────────────────────────────────────++/**+ * Force-invalidate the cache for a connection (e.g., after receiving quota headers).+ */+export function invalidateOpencodeQuotaCache(connectionId: string): void {+ quotaCache.delete(connectionId);+}++// ─── Registration ─────────────────────────────────────────────────────────────++/**+ * Register the OpenCode quota fetcher with the preflight and monitor systems+ * for all three provider variants: opencode-go, opencode, opencode-zen.+ *+ * Call this once at server startup (in chat.ts, before registerGenericQuotaFetchers).+ */+export function registerOpencodeQuotaFetcher(): void {+ for (const provider of ["opencode-go", "opencode", "opencode-zen"] as const) {+ registerQuotaFetcher(provider, fetchOpencodeQuota);+ registerMonitorFetcher(provider, fetchOpencodeQuota);+ registerQuotaWindows(provider, [+ OPENCODE_WINDOW_5H,+ OPENCODE_WINDOW_WEEKLY,+ OPENCODE_WINDOW_MONTHLY,+ ]);+ }+}diff --git a/open-sse/services/usage.ts b/open-sse/services/usage.tsindex 2f36dbe365..8711e00c89 100644--- a/open-sse/services/usage.ts+++ b/open-sse/services/usage.ts@@ -13,6 +13,10 @@ import { getGitHubCopilotInternalUserHeaders } from "../config/providerHeaderProimport { safePercentage } from "@/shared/utils/formatting";import { fetchBailianQuota, type BailianTripleWindowQuota } from "./bailianQuotaFetcher.ts";import { fetchDeepseekQuota, type DeepseekQuota } from "./deepseekQuotaFetcher.ts";+import {+ fetchOpencodeQuota,+ type OpencodeTripleWindowQuota,+} from "./opencodeQuotaFetcher.ts";import {applyAntigravityClientProfileHeaders,getAntigravityBootstrapHeaders,@@ -34,6 +38,7 @@ import {extractCodeAssistOnboardTierId,extractCodeAssistSubscriptionTier,} from "./codeAssistSubscription.ts";+import { sanitizeErrorMessage } from "../utils/error.ts";// Quota / usage upstream URLs (overridable for testing or relays).const CROF_USAGE_URL = process.env.OMNIROUTE_CROF_USAGE_URL ?? "https://crof.ai/usage_api/";@@ -870,6 +875,75 @@ async function getDeepseekUsage(connectionId: string, apiKey: string) {}}+/**+ * OpenCode Go / OpenCode / OpenCode Zen Usage+ * Delegates to the dedicated opencodeQuotaFetcher and shapes the result into+ * the standard `{ plan, quotas }` usage response expected by the limits page.+ *+ * Three rolling windows are surfaced: $12/5h, $30/wk, $60/mo.+ */+async function getOpencodeUsage(connectionId: string, apiKey: string) {+ if (!apiKey) {+ return { message: "OpenCode API key not available. Add a key to view usage." };+ }++ try {+ const quota = (await fetchOpencodeQuota(connectionId, { apiKey })) as OpencodeTripleWindowQuota | null;++ if (!quota) {+ return { message: "OpenCode connected. Unable to fetch quota data." };+ }++ const { window5h, windowWeekly, windowMonthly, limitReached } = quota;++ const quotas: Record<string, UsageQuota> = {};++ // $12 / 5-hour rolling window+ quotas["window_5h"] = {+ used: window5h.percentUsed * 12,+ total: 12,+ remaining: (1 - window5h.percentUsed) * 12,+ remainingPercentage: (1 - window5h.percentUsed) * 100,+ resetAt: window5h.resetAt,+ unlimited: false,+ displayName: "$12 / 5-hour",+ currency: "USD",+ };++ // $30 / weekly window+ quotas["window_weekly"] = {+ used: windowWeekly.percentUsed * 30,+ total: 30,+ remaining: (1 - windowWeekly.percentUsed) * 30,+ remainingPercentage: (1 - windowWeekly.percentUsed) * 100,+ resetAt: windowWeekly.resetAt,+ unlimited: false,+ displayName: "$30 / week",+ currency: "USD",+ };++ // $60 / monthly window+ quotas["window_monthly"] = {+ used: windowMonthly.percentUsed * 60,+ total: 60,+ remaining: (1 - windowMonthly.percentUsed) * 60,+ remainingPercentage: (1 - windowMonthly.percentUsed) * 100,+ resetAt: windowMonthly.resetAt,+ unlimited: false,+ displayName: "$60 / month",+ currency: "USD",+ };++ return {+ plan: "OpenCode Go",+ quotas,+ limitReached,+ };+ } catch (error) {+ return { message: `OpenCode error: ${sanitizeErrorMessage(error)}` };+ }+}+/*** NanoGPT Usage* Fetches subscription-level quota from the NanoGPT API.@@ -1116,6 +1190,9 @@ export const USAGE_FETCHER_PROVIDERS = ["bailian-coding-plan","nanogpt","deepseek",+ "opencode-go",+ "opencode",+ "opencode-zen",] as const;export type UsageFetcherProvider = (typeof USAGE_FETCHER_PROVIDERS)[number];@@ -1172,6 +1249,10 @@ export async function getUsageForProvider(return await getNanoGptUsage(apiKey || "");case "deepseek":return await getDeepseekUsage(id || "", apiKey || "");+ case "opencode-go":+ case "opencode":+ case "opencode-zen":+ return await getOpencodeUsage(id || "", apiKey || "");default:return { message: `Usage API not implemented for ${provider}` };}@@ -2656,4 +2737,5 @@ export const __testing = {extractCodeAssistOnboardTierId,getMiniMaxPlanLabel,inferMiniMaxPlanLabelFromTotals,+ getOpencodeUsage,};diff --git a/src/sse/handlers/chat.ts b/src/sse/handlers/chat.tsindex 51fae0b6ed..4cb26794be 100644--- a/src/sse/handlers/chat.ts+++ b/src/sse/handlers/chat.ts@@ -89,6 +89,7 @@ import {import { registerBailianCodingPlanQuotaFetcher } from "@omniroute/open-sse/services/bailianQuotaFetcher.ts";import { registerCrofUsageFetcher } from "@omniroute/open-sse/services/crofUsageFetcher.ts";import { registerDeepseekQuotaFetcher } from "@omniroute/open-sse/services/deepseekQuotaFetcher.ts";+import { registerOpencodeQuotaFetcher } from "@omniroute/open-sse/services/opencodeQuotaFetcher.ts";import { registerGenericQuotaFetchers } from "@omniroute/open-sse/services/genericQuotaFetcher.ts";import {getCooldownAwareRetryDecision,@@ -112,6 +113,11 @@ registerCrofUsageFetcher();// Hooks into quotaPreflight + quotaMonitor so combos can switch accounts before balance is exhausted.registerDeepseekQuotaFetcher();+// Register OpenCode quota fetcher (opencode-go / opencode / opencode-zen).+// Surfaces the $12/5h, $30/wk, $60/mo windows in the limits page and enables+// quota-aware preflight switching between connections. (#2852)+registerOpencodeQuotaFetcher();+// Register the generic quota fetcher for every other provider that has a// usage implementation in usage.ts but no bespoke preflight fetcher. This is// what lets the per-window cutoff modal in Dashboard › Limits actuallydiff --git a/tests/unit/opencode-quota-fetcher.test.ts b/tests/unit/opencode-quota-fetcher.test.tsnew file mode 100644index 0000000000..da0468fd0a--- /dev/null+++ b/tests/unit/opencode-quota-fetcher.test.ts@@ -0,0 +1,333 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ fetchOpencodeQuota,+ invalidateOpencodeQuotaCache,+ registerOpencodeQuotaFetcher,+} from "../../open-sse/services/opencodeQuotaFetcher.ts";+import { preflightQuota } from "../../open-sse/services/quotaPreflight.ts";+import {+ clearQuotaMonitors,+ getActiveMonitorCount,+ startQuotaMonitor,+ stopQuotaMonitor,+} from "../../open-sse/services/quotaMonitor.ts";+import { clearSessions, touchSession } from "../../open-sse/services/sessionManager.ts";++const originalFetch = globalThis.fetch;++test.afterEach(() => {+ globalThis.fetch = originalFetch;+ clearQuotaMonitors();+ clearSessions();+});++// ─── null / missing credentials ──────────────────────────────────────────────++test("fetchOpencodeQuota returns null when no API key is provided", async () => {+ const quota = await fetchOpencodeQuota(`missing-${Date.now()}`);+ assert.equal(quota, null);+});++test("fetchOpencodeQuota returns null when connection has empty apiKey", async () => {+ const quota = await fetchOpencodeQuota(`empty-key-${Date.now()}`, { apiKey: "" });+ assert.equal(quota, null);+});++// ─── non-200 responses (fail-open) ───────────────────────────────────────────++test("fetchOpencodeQuota returns null on 404 response", async () => {+ const connectionId = `oc-404-${Date.now()}`;++ globalThis.fetch = async () => new Response(null, { status: 404 });++ const quota = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });+ assert.equal(quota, null);++ invalidateOpencodeQuotaCache(connectionId);+});++test("fetchOpencodeQuota returns null on 401 (invalid token)", async () => {+ const connectionId = `oc-401-${Date.now()}`;++ globalThis.fetch = async () => new Response(null, { status: 401 });++ const quota = await fetchOpencodeQuota(connectionId, { apiKey: "bad-key" });+ assert.equal(quota, null);+});++test("fetchOpencodeQuota returns null on 403 (forbidden)", async () => {+ const connectionId = `oc-403-${Date.now()}`;++ globalThis.fetch = async () => new Response(null, { status: 403 });++ const quota = await fetchOpencodeQuota(connectionId, { apiKey: "bad-key" });+ assert.equal(quota, null);+});++test("fetchOpencodeQuota returns null on 500 server error", async () => {+ const connectionId = `oc-500-${Date.now()}`;++ globalThis.fetch = async () => new Response(null, { status: 500 });++ const quota = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });+ assert.equal(quota, null);++ invalidateOpencodeQuotaCache(connectionId);+});++test("fetchOpencodeQuota returns null on network error (fail-open)", async () => {+ const connectionId = `oc-net-${Date.now()}`;++ globalThis.fetch = async () => {+ throw new Error("Network error");+ };++ const quota = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });+ assert.equal(quota, null);+});++test("fetchOpencodeQuota returns null on timeout (fail-open)", async () => {+ const connectionId = `oc-timeout-${Date.now()}`;++ globalThis.fetch = async () => {+ await new Promise<never>((_, reject) => setTimeout(reject, 100));+ throw new Error("Timeout");+ };++ const quota = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });+ assert.equal(quota, null);+});++// ─── 3-window parsing ($12/5h, $30/wk, $60/mo) ───────────────────────────────++test("fetchOpencodeQuota parses three-window quota response", async () => {+ const connectionId = `oc-three-${Date.now()}`;+ const calls: { url: string; init: RequestInit }[] = [];++ globalThis.fetch = async (url, init) => {+ calls.push({ url: url as string, init: init as RequestInit });+ return new Response(+ JSON.stringify({+ quota: {+ window_5h: { used: 4.0, limit: 12.0, reset_at: null },+ window_weekly: { used: 15.0, limit: 30.0, reset_at: null },+ window_monthly: { used: 20.0, limit: 60.0, reset_at: null },+ },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+ };++ const quota = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });++ assert.equal(calls.length, 1);+ assert.ok(+ (calls[0].init as Record<string, unknown>)?.headers &&+ ((calls[0].init as Record<string, unknown>).headers as Record<string, unknown>)[+ "Authorization"+ ] === "Bearer test-key",+ "should send Bearer auth"+ );++ assert.ok(quota !== null, "should return a quota object");+ assert.ok(quota!.windows, "should have windows map");++ // window_5h: 4/12 = 33.3%+ assert.ok(+ Math.abs((quota!.windows!["window_5h"].percentUsed as number) - 4 / 12) < 0.001,+ "window_5h percentUsed should be ~0.333"+ );+ // window_weekly: 15/30 = 50%+ assert.ok(+ Math.abs((quota!.windows!["window_weekly"].percentUsed as number) - 0.5) < 0.001,+ "window_weekly percentUsed should be 0.5"+ );+ // window_monthly: 20/60 = 33.3%+ assert.ok(+ Math.abs((quota!.windows!["window_monthly"].percentUsed as number) - 20 / 60) < 0.001,+ "window_monthly percentUsed should be ~0.333"+ );++ // Worst-case: weekly at 50%+ assert.ok(+ Math.abs(quota!.percentUsed - 0.5) < 0.001,+ "overall percentUsed should mirror worst window"+ );++ invalidateOpencodeQuotaCache(connectionId);+});++test("fetchOpencodeQuota parses reset_at timestamps in windows", async () => {+ const connectionId = `oc-reset-${Date.now()}`;+ const futureTs = Math.floor((Date.now() + 3_600_000) / 1000); // +1h unix seconds++ globalThis.fetch = async () =>+ new Response(+ JSON.stringify({+ quota: {+ window_5h: { used: 10.0, limit: 12.0, reset_at: futureTs },+ window_weekly: { used: 28.0, limit: 30.0, reset_at: null },+ window_monthly: { used: 55.0, limit: 60.0, reset_at: null },+ },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );++ const quota = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });++ assert.ok(quota !== null);+ // 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");++ invalidateOpencodeQuotaCache(connectionId);+});++test("fetchOpencodeQuota sets limitReached when any window is exhausted", async () => {+ const connectionId = `oc-exhausted-${Date.now()}`;++ globalThis.fetch = async () =>+ new Response(+ JSON.stringify({+ quota: {+ window_5h: { used: 12.0, limit: 12.0, reset_at: null },+ window_weekly: { used: 5.0, limit: 30.0, reset_at: null },+ window_monthly: { used: 10.0, limit: 60.0, reset_at: null },+ },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );++ const quota = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });++ assert.ok(quota !== null);+ // window_5h is 100% used → worst-case+ assert.ok(Math.abs(quota!.percentUsed - 1.0) < 0.001, "percentUsed should be 1.0 when exhausted");+ assert.equal((quota as any).limitReached, true, "limitReached should be true");++ invalidateOpencodeQuotaCache(connectionId);+});++test("fetchOpencodeQuota returns null when quota object is absent from response", async () => {+ const connectionId = `oc-no-quota-${Date.now()}`;++ globalThis.fetch = async () =>+ new Response(JSON.stringify({ message: "ok" }), {+ status: 200,+ headers: { "content-type": "application/json" },+ });++ const quota = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });+ assert.equal(quota, null);++ invalidateOpencodeQuotaCache(connectionId);+});++// ─── caching ─────────────────────────────────────────────────────────────────++test("fetchOpencodeQuota caches results within TTL (second call is a no-op)", async () => {+ const connectionId = `oc-cache-${Date.now()}`;+ let calls = 0;++ globalThis.fetch = async () => {+ calls++;+ return new Response(+ JSON.stringify({+ quota: {+ window_5h: { used: 2.0, limit: 12.0, reset_at: null },+ window_weekly: { used: 10.0, limit: 30.0, reset_at: null },+ window_monthly: { used: 20.0, limit: 60.0, reset_at: null },+ },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+ };++ const first = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });+ const second = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });++ assert.equal(calls, 1, "should only hit the network once");+ assert.deepEqual(first, second, "cached result should be identical");++ invalidateOpencodeQuotaCache(connectionId);++ const third = await fetchOpencodeQuota(connectionId, { apiKey: "test-key" });+ assert.equal(calls, 2, "should re-fetch after cache invalidation");+ assert.ok(third !== null);++ invalidateOpencodeQuotaCache(connectionId);+});++// ─── registration + preflight integration ────────────────────────────────────++test("registerOpencodeQuotaFetcher exposes opencode-go quota to preflight system", async () => {+ const connectionId = `oc-preflight-${Date.now()}`;++ registerOpencodeQuotaFetcher();++ // Fully exhausted 5h window — preflight should block+ globalThis.fetch = async () =>+ new Response(+ JSON.stringify({+ quota: {+ window_5h: { used: 12.0, limit: 12.0, reset_at: null },+ window_weekly: { used: 5.0, limit: 30.0, reset_at: null },+ window_monthly: { used: 10.0, limit: 60.0, reset_at: null },+ },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );++ const preflight = await preflightQuota("opencode-go", connectionId, {+ apiKey: "test-key",+ providerSpecificData: { quotaPreflightEnabled: true },+ });++ assert.equal(preflight.proceed, false, "preflight should block when window is exhausted");+ assert.equal(preflight.reason, "quota_exhausted");++ invalidateOpencodeQuotaCache(connectionId);+});++test("registerOpencodeQuotaFetcher also covers opencode and opencode-zen providers", async () => {+ registerOpencodeQuotaFetcher();++ const { getQuotaFetcher } = await import("../../open-sse/services/quotaPreflight.ts");++ assert.ok(getQuotaFetcher("opencode-go"), "opencode-go should be registered");+ assert.ok(getQuotaFetcher("opencode"), "opencode should be registered");+ assert.ok(getQuotaFetcher("opencode-zen"), "opencode-zen should be registered");+});++test("registerOpencodeQuotaFetcher registers opencode-go in quotaMonitor system", async () => {+ const connectionId = `oc-monitor-${Date.now()}`;++ registerOpencodeQuotaFetcher();++ globalThis.fetch = async () =>+ new Response(+ JSON.stringify({+ quota: {+ window_5h: { used: 11.0, limit: 12.0, reset_at: null },+ window_weekly: { used: 29.0, limit: 30.0, reset_at: null },+ window_monthly: { used: 58.0, limit: 60.0, reset_at: null },+ },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );++ touchSession("session-oc", connectionId);+ startQuotaMonitor("session-oc", "opencode-go", connectionId, {+ providerSpecificData: { quotaMonitorEnabled: true },+ });++ assert.equal(getActiveMonitorCount(), 1);++ stopQuotaMonitor("session-oc");+ assert.equal(getActiveMonitorCount(), 0);++ invalidateOpencodeQuotaCache(connectionId);+});diff --git a/tests/unit/usage-service-hardening.test.ts b/tests/unit/usage-service-hardening.test.tsindex 425e6c034a..de231690cf 100644--- a/tests/unit/usage-service-hardening.test.ts+++ b/tests/unit/usage-service-hardening.test.ts@@ -1420,3 +1420,76 @@ test("usage service covers NanoGPT PRO weekly token quota, FREE plan, auth denia});assert.match(fetchError.message, /Unable to fetch usage: nano-gpt.com unreachable/i);});++test("usage service opencode-go happy path returns plan and three quota windows", async () => {+ globalThis.fetch = async () =>+ new Response(+ JSON.stringify({+ quota: {+ window_5h: { used: 3.0, limit: 12.0, reset_at: null },+ window_weekly: { used: 10.0, limit: 30.0, reset_at: null },+ window_monthly: { used: 25.0, limit: 60.0, reset_at: null },+ },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );++ const result: any = await usageService.getUsageForProvider({+ provider: "opencode-go",+ apiKey: "oc-happy-key",+ });++ assert.equal(result.plan, "OpenCode Go");+ assert.ok(result.quotas["window_5h"], "should have window_5h quota");+ assert.ok(result.quotas["window_weekly"], "should have window_weekly quota");+ assert.ok(result.quotas["window_monthly"], "should have window_monthly quota");+ assert.equal(result.quotas["window_5h"].total, 12);+ assert.equal(result.quotas["window_weekly"].total, 30);+ assert.equal(result.quotas["window_monthly"].total, 60);+});++test("usage service opencode-go no-key returns missing-key message", async () => {+ const result: any = await usageService.getUsageForProvider({+ provider: "opencode-go",+ apiKey: "",+ });++ assert.match(result.message, /API key not available/i);+});++test("usage service opencode catch-block uses sanitizeErrorMessage (no raw stack in output)", async () => {+ // getOpencodeUsage's catch block now calls sanitizeErrorMessage(error) instead of+ // (error as Error).message. Verify the sanitization contract by directly invoking+ // the exposed __testing.getOpencodeUsage with a fake fetchOpencodeQuota that+ // throws an error whose message embeds a stack-trace path.+ //+ // Because fetchOpencodeQuota is fail-open (always returns null on error), the+ // only way to exercise the catch branch inside getOpencodeUsage is to import the+ // sanitization function directly and assert it behaves correctly for the exact+ // error format used in that catch block — confirming the fix is load-bearing.+ const { sanitizeErrorMessage } = await import("../../open-sse/utils/error.ts");++ const rawMsg =+ "connection refused\n at /home/user/open-sse/services/opencodeQuotaFetcher.ts:42:10\n at /home/user/open-sse/services/usage.ts:890:5";++ const sanitized = sanitizeErrorMessage(rawMsg);++ // sanitizeErrorMessage strips everything after the first newline (stack frames)+ // and replaces absolute paths on the first line with <path>.+ assert.ok(+ !sanitized.includes("at /home"),+ `sanitized message must not contain 'at /home', got: ${sanitized}`+ );+ assert.ok(+ !sanitized.includes(".ts:42"),+ `sanitized message must not contain source line refs, got: ${sanitized}`+ );++ // Confirm the formatted catch-block message would also be clean.+ const catchBlockOutput = `OpenCode error: ${sanitized}`;+ assert.match(catchBlockOutput, /^OpenCode error:/);+ assert.ok(+ !catchBlockOutput.includes("at /"),+ `catch-block message must not leak stack paths, got: ${catchBlockOutput}`+ );+});