import type { AllowanceSource, AllowanceWindow, ProviderDefinition, SourceFailure, SourceObservation, SourceResult, } from "../meter.js"; export const OPENCODE_GO_PROVIDER_ID = "opencode-go"; // pi-lens-ignore: hardcoded-url const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage"; export interface OpenCodeGoProviderOptions { readonly resolveAuth: () => Promise< { readonly auth: { readonly apiKey?: string } } | undefined >; readonly fetch?: typeof globalThis.fetch; } export function createOpenCodeGoProvider( options: OpenCodeGoProviderOptions, ): ProviderDefinition { return { support: "live", id: OPENCODE_GO_PROVIDER_ID, displayName: "OpenCode Go", evidence: "first-party-source", source: createOpenCodeGoSource(options), }; } function createOpenCodeGoSource( options: OpenCodeGoProviderOptions, ): AllowanceSource { const fetchImplementation = options.fetch ?? globalThis.fetch; return { async read(signal): Promise { let resolvedAuth: | { readonly auth: { readonly apiKey?: string } } | undefined; try { resolvedAuth = await options.resolveAuth(); } catch { return failure("network"); } const apiKey = resolvedAuth?.auth.apiKey; if (!apiKey || !isSafeHeaderValue(apiKey)) { return failure("not-configured"); } let response: Response; try { response = await fetchImplementation(OPENCODE_GO_USAGE_URL, { method: "GET", headers: { Accept: "application/json", Authorization: `Bearer ${apiKey}`, }, signal, }); } catch { return failure(signal.aborted ? "timeout" : "network"); } if (response.status === 401 || response.status === 403) { return failure("unauthorized"); } // The reviewed route defines no rate-limit or retry protocol, so // any status other than 200 (including 429) is an unexpected // network failure with no retry hint. if (response.status !== 200) return failure("network"); let payload: unknown; try { payload = await response.json(); } catch { return failure("invalid-response"); } const observation = decodeObservation(payload); return observation ? { kind: "success", observation } : failure("invalid-response"); }, }; } function decodeObservation(payload: unknown): SourceObservation | undefined { if (!isRecord(payload)) return undefined; if (Object.keys(payload).length !== 1) return undefined; const usage = payload.usage; if (!isRecord(usage)) return undefined; if (Object.keys(usage).length !== 3) return undefined; const rolling = decodeWindow("rolling", "5 hour", 300, usage.rolling); const weekly = decodeWindow("weekly", "Weekly", 10_080, usage.weekly); const monthly = decodeWindow("monthly", "Monthly", undefined, usage.monthly); if (!rolling || !weekly || !monthly) return undefined; return { windows: [rolling, weekly, monthly] }; } function decodeWindow( id: string, label: string, windowMinutes: number | undefined, value: unknown, ): AllowanceWindow | undefined { if (!isRecord(value)) return undefined; if (Object.keys(value).length !== 3) return undefined; const status = value.status; if (status !== "ok" && status !== "rate-limited") return undefined; const usedPercent = parseUsedPercent(value.percent); const resetsAt = parseRfc3339(value.resetsAt); if (usedPercent === undefined || resetsAt === undefined) return undefined; return windowMinutes === undefined ? { id, label, usedPercent, resetsAt } : { id, label, usedPercent, windowMinutes, resetsAt }; } function parseUsedPercent(value: unknown): number | undefined { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 100 ? value : undefined; } const RFC3339_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(Z|[+-]\d{2}:\d{2})$/; function parseRfc3339(value: unknown): Date | undefined { if (typeof value !== "string") return undefined; const match = RFC3339_TIMESTAMP.exec(value); if (!match) return undefined; const [, year, month, day, hour, minute, second, offset] = match; if (!year || !month || !day || !hour || !minute || !second || !offset) { return undefined; } const monthNumber = Number(month); const dayNumber = Number(day); if ( monthNumber < 1 || monthNumber > 12 || dayNumber < 1 || Number(hour) > 23 || Number(minute) > 59 || Number(second) > 59 ) { return undefined; } if (offset !== "Z") { if (Number(offset.slice(1, 3)) > 23 || Number(offset.slice(4, 6)) > 59) { return undefined; } } const daysInMonth = new Date(Date.UTC(Number(year), monthNumber, 0)) .getUTCDate(); if (dayNumber > daysInMonth) return undefined; const timestamp = Date.parse(value); return Number.isNaN(timestamp) ? undefined : new Date(timestamp); } function isSafeHeaderValue(value: string): boolean { return value.length > 0 && /^[\x21-\x7e]+$/.test(value); } function failure(reason: SourceFailure["reason"]): SourceResult { return { kind: "failure", failure: { reason } }; } function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); }