/** * Claude usage on the shared subscription core (design 5.3, Claude track * C2a): the adapter's usage members (`fetchUsage`, `decodeQuota`) and the * projection of one core connection's quota row onto the legacy * `ClaudeSubscriptionUsage` response. * * - `fetchSubscriptionCoreClaudeUsage` is the legacy `/api/oauth/usage` read * (`requestClaudeUsage`) through the core's request custody: a ten-second * deadline, a bounded body and `redirect: "error"`. A credential without * the `user:profile` OAuth scope (every setup token) is never sent: it is * `scope_required` with no network call. A 401 is `reconnect`, the 403 * naming the `user:profile` scope requirement is `scope_required`, and any * other failure is `unavailable` (never an implied zero quota). * - `decodeSubscriptionCoreClaudeUsage` decodes an `available` reading * through `decodeSubscriptionCoreClaudeQuota`, with every Claude model the * caller's catalog lists (`modelIds`), so a model-family window becomes a * cooldown of each listed model of the family. * - `projectSubscriptionCoreClaudeUsage` maps a stored core quota back to the * legacy window shape, with the connection's row `version` as the * credential version (the account listing's `version`). `scope_required` * and `reconnect` are response values derived from the connection, never * stored: `reconnect` while the connection needs a new sign-in, * `scope_required` when the adapter-owned `provider_state.oauthScopes` * (written by the connect writers; `[]` for a setup token, absent when * unknown) lacks `user:profile`. * * Usage reads present Claude Code's CLI surface (its account-API user * agent): Claude reports limit reset grants only to that surface. The * read asks for the reset status (`cedar_ember=1`); while that status says * the account is at a limit, a second read asks for the at-the-limit * program (`at_wall=1`), as Claude Code does. Both skip spend reporting. */ import { CLAUDE_CLI_SURFACE_USER_AGENT, parseClaudeUsageResponse, parseClaudeWallReset, type ClaudeUsageObservation, } from "@opengeni/config"; import { ClaudeExtraUsage, ClaudeLimitResets, ClaudeServiceState, ClaudeSurfaceUsageWindow, ClaudeUsageLimit, ClaudeUsageWindowId, ClaudeWallReset, type ClaudeSubscriptionUsage, type ClaudeUsageWindow, } from "@opengeni/contracts"; import { readResponseJsonBounded } from "@opengeni/network"; import { quotaCapacity, type QuotaWindow, type SubscriptionCoreConnectionRead, type SubscriptionQuota, type SubscriptionQuotaBlock, } from "@opengeni/subscriptions"; import { decodeSubscriptionCoreClaudeQuota, SUBSCRIPTION_CORE_CLAUDE_CLAIMABLE_WINDOW_IDS, SUBSCRIPTION_CORE_CLAUDE_WINDOW_ALIASES, type SubscriptionCoreClaudeCredential, } from "./subscription-core-claude-adapter"; import { claudeSubscriptionUpstreamModelId } from "@opengeni/contracts/claude-subscription-model-ids"; import { decodeSubscriptionQuota } from "./subscription-core-repository"; /** The Claude usage endpoint (the legacy `requestClaudeUsage` URL). */ export const SUBSCRIPTION_CORE_CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage"; /** The usage read with the limit reset status (Claude Code's ordinary reset check). */ export const SUBSCRIPTION_CORE_CLAUDE_RESET_STATUS_URL = `${SUBSCRIPTION_CORE_CLAUDE_USAGE_URL}?cedar_ember=1&skip_spend=1`; /** The usage read at a limit, which also reports the at-the-limit program. */ export const SUBSCRIPTION_CORE_CLAUDE_AT_LIMIT_URL = `${SUBSCRIPTION_CORE_CLAUDE_USAGE_URL}?at_wall=1&skip_spend=1`; /** The OAuth scope the usage endpoint requires. */ export const SUBSCRIPTION_CORE_CLAUDE_USAGE_SCOPE = "user:profile"; const USAGE_DEADLINE_MS = 10_000; const USAGE_BODY_LIMIT_BYTES = 64 * 1024; /** The headers of an account-API read: the bearer and Claude Code's CLI surface. */ export function subscriptionCoreClaudeAccountHeaders(token: string): Record { return { authorization: `Bearer ${token}`, "content-type": "application/json", "cache-control": "no-cache", "user-agent": CLAUDE_CLI_SURFACE_USER_AGENT, }; } /** One usage read: the legacy refresh outcome and, when available, its observation. */ export type SubscriptionCoreClaudeUsageReading = { status: "available" | "unavailable" | "scope_required" | "reconnect"; observation: ClaudeUsageObservation | null; /** When the read was requested (a refusal stored after it stands). */ checkedAt: string; /** * Why an `unavailable` read failed, for the operator log: Claude's HTTP * status, the kind of transport error (never its message), or a response * that carried no reading. */ failure?: SubscriptionCoreClaudeUsageFailure; }; /** Why one usage read failed. Holds no token, header or response text. */ export type SubscriptionCoreClaudeUsageFailure = | { kind: "http_status"; status: number } | { kind: "fetch_error"; error: string } | { kind: "no_reading" }; /** The kind of a thrown transport error: its name and system code, never its message. */ export function subscriptionCoreClaudeUsageErrorKind(error: unknown): string { if (!(error instanceof Error)) return typeof error; const cause = (error as { cause?: unknown }).cause; const code = (error as { code?: unknown }).code ?? (cause && typeof cause === "object" ? (cause as { code?: unknown }).code : undefined); return typeof code === "string" && /^[A-Za-z0-9_]{1,64}$/.test(code) ? `${error.name}:${code}` : error.name; } /** The adapter's `fetchUsage`: one usage read with the connection's current bearer. */ export async function fetchSubscriptionCoreClaudeUsage( read: SubscriptionCoreConnectionRead, ): Promise { const { credential } = await read.getToken(); const checkedAt = new Date().toISOString(); // Setup tokens never carry the scope: no request is sent. if (!credential.oauth?.scopes.includes(SUBSCRIPTION_CORE_CLAUDE_USAGE_SCOPE)) return { status: "scope_required", observation: null, checkedAt }; let status: SubscriptionCoreClaudeUsageReading["status"] = "unavailable"; let observation: ClaudeUsageObservation | null = null; let failure: SubscriptionCoreClaudeUsageFailure | undefined; try { const signal = AbortSignal.timeout(USAGE_DEADLINE_MS); const response = await read.fetch(SUBSCRIPTION_CORE_CLAUDE_RESET_STATUS_URL, { headers: subscriptionCoreClaudeAccountHeaders(credential.token), redirect: "error", signal, }); if (response.ok || response.status === 403) { const body = await readResponseJsonBounded( response, USAGE_BODY_LIMIT_BYTES, "Claude usage", { signal }, ); if (response.ok) { observation = parseClaudeUsageResponse(body, new Date(checkedAt)); status = observation ? "available" : "unavailable"; if (!observation) failure = { kind: "no_reading" }; if (observation?.details?.limitResets?.atLimit === true) observation = await withAtLimitProgram(read, credential.token, observation, checkedAt); } else { const error = body && typeof body === "object" && "error" in body ? body.error : null; const message = error && typeof error === "object" && "message" in error ? error.message : null; status = typeof message === "string" && message.includes("scope requirement") && message.includes(SUBSCRIPTION_CORE_CLAUDE_USAGE_SCOPE) ? "scope_required" : "unavailable"; if (status === "unavailable") failure = { kind: "http_status", status: response.status }; } } else { status = response.status === 401 ? "reconnect" : "unavailable"; if (status === "unavailable") failure = { kind: "http_status", status: response.status }; await response.body?.cancel().catch(() => undefined); } } catch (error) { // Keep the stored observation; never imply an unavailable quota is zero. status = "unavailable"; observation = null; failure = { kind: "fetch_error", error: subscriptionCoreClaudeUsageErrorKind(error) }; } return { status, observation, checkedAt, ...(failure ? { failure } : {}) }; } /** * The at-the-limit program from a second read, added to an at-limit * observation. Its failure leaves the observation as it was: the program * is information, never a condition of the usage reading. */ async function withAtLimitProgram( read: SubscriptionCoreConnectionRead, token: string, observation: ClaudeUsageObservation, checkedAt: string, ): Promise { try { const signal = AbortSignal.timeout(USAGE_DEADLINE_MS); const response = await read.fetch(SUBSCRIPTION_CORE_CLAUDE_AT_LIMIT_URL, { headers: subscriptionCoreClaudeAccountHeaders(token), redirect: "error", signal, }); if (!response.ok) { await response.body?.cancel().catch(() => undefined); return observation; } const body = await readResponseJsonBounded( response, USAGE_BODY_LIMIT_BYTES, "Claude usage", { signal }, ); const program = body && typeof body === "object" && !Array.isArray(body) ? parseClaudeWallReset((body as Record).juniper_tide, new Date(checkedAt)) : undefined; return program === undefined ? observation : { ...observation, details: { ...observation.details, wallReset: program } }; } catch { return observation; } } function isUsageReading(value: unknown): value is SubscriptionCoreClaudeUsageReading { return ( value !== null && typeof value === "object" && "status" in value && "observation" in value && typeof (value as { status: unknown }).status === "string" ); } /** The upstream Claude model ids among product model ids (other providers' ids are dropped). */ export function subscriptionCoreClaudeUpstreamModelIds( productModelIds: readonly string[], ): string[] { const upstream = new Set(); for (const modelId of productModelIds) { const id = claudeSubscriptionUpstreamModelId(modelId); if (id !== null) upstream.add(id); } return [...upstream].sort(); } /** * A reading stamped at `observedAt`, the instant the core received it (never * earlier than the request). Claude answers with the account's usage as of * its response, so a reading must not count as older than a response-header * reading of a turn that arrived while it was in flight: stamped at the * request, every such header write made the merge keep the stored quota and * drop the reading. The reading's `checkedAt` stays the request time, which * is what decides whether a refusal stored meanwhile stands. */ function observedWhenReceived( observation: ClaudeUsageObservation, observedAt: number, ): ClaudeUsageObservation { const requested = Date.parse(observation.observedAt); if (!Number.isFinite(observedAt) || !(observedAt > requested)) return observation; const at = new Date(observedAt).toISOString(); return { ...observation, observedAt: at, windows: observation.windows.map((window) => window.observedAt === observation.observedAt ? { ...window, observedAt: at } : window, ), }; } /** * The adapter's `decodeQuota`: an available reading in the shared quota * model, observed when the core received it (`input.observedAt`), else null. */ export function decodeSubscriptionCoreClaudeUsage(input: { response: unknown; observedAt: number; refreshGeneration: number; modelIds?: readonly string[]; }): SubscriptionQuota | null { if (!isUsageReading(input.response)) return null; const { status, observation } = input.response; if (status !== "available" || !observation) return null; return { ...decodeSubscriptionCoreClaudeQuota({ observation: observedWhenReceived(observation, input.observedAt), refreshGeneration: input.refreshGeneration, upstreamModelIds: subscriptionCoreClaudeUpstreamModelIds(input.modelIds ?? []), }), revision: 0, }; } /** The account windows that decide whether a Claude connection may serve. */ const ACCOUNT_WINDOW_IDS = ["five_hour", "seven_day"] as const; function reportsBelowLimit(reading: SubscriptionCoreClaudeUsageReading, id: string): boolean { // The usage endpoint reports the Fable limit as `seven_day_fable`; a // refusal names it `seven_day_overage_included`. const ids = [id, SUBSCRIPTION_CORE_CLAUDE_WINDOW_ALIASES[id]]; const window = reading.observation?.windows.find((candidate) => ids.includes(candidate.id)); return window !== undefined && window.usedPercent !== null && window.usedPercent < 100; } /** * The adapter's `usageReadConfirmsAvailability`: an available reading in * which each account window (five hours, seven days) is either reported with * a percentage below the limit or answered with an explicit `null` (the plan * has no such limit now: a verified Ultra plan has no five-hour window), and * at least one is reported below the limit. A window that is omitted, or * reported without a percentage, says nothing about the limit that refused * the connection, so the reading ends nothing. An explicit `null` only lets * the other window's reading count: it never ends a block that claims the * null window (`subscriptionCoreClaudeUsageEndsClaimedBlock`). */ export function subscriptionCoreClaudeUsageConfirmsAvailability(response: unknown): boolean { if (!isUsageReading(response) || response.status !== "available") return false; const noLimit = new Set(response.observation?.noLimitWindows ?? []); const reported = ACCOUNT_WINDOW_IDS.filter((id) => reportsBelowLimit(response, id)); return ( reported.length > 0 && ACCOUNT_WINDOW_IDS.every( (id) => reported.includes(id) || (noLimit.has(id) && !response.observation?.windows.some((window) => window.id === id)), ) ); } /** * The adapter's `usageReadEndsClaimedBlock`: with a reading that confirms * availability, a stored block (a model cooldown, or the quota exhaustion * deadline) has ended when its claim names only plan windows this build * recognizes, was observed before the reading was requested (a refusal * that arrived while it was in flight stands), and the reading reports * every claimed window with a percentage below the limit. Everything else * ends nothing (fail closed): a block without a claim (no or an * unrecognized representative claim, or a refusal without usage headers), * a claimed window the reading omits or answers as `null` (no such limit * now never clears a limit that refused), and a reading that does not * confirm availability. A plan without a family limit still recovers from * an account-window claim: only the claimed windows are required. */ export function subscriptionCoreClaudeUsageEndsClaimedBlock( response: unknown, ): (block: SubscriptionQuotaBlock) => boolean { if (!subscriptionCoreClaudeUsageConfirmsAvailability(response)) return () => false; const reading = response as SubscriptionCoreClaudeUsageReading; const requestedAt = Date.parse(reading.checkedAt); if (!Number.isFinite(requestedAt)) return () => false; return ({ claim }) => claim !== null && claim.windowIds.length > 0 && claim.observedAt < requestedAt && claim.windowIds.every( (id) => SUBSCRIPTION_CORE_CLAUDE_CLAIMABLE_WINDOW_IDS.has(id) && reportsBelowLimit(reading, id), ); } /** The fields of a core connection row the usage projection reads. */ export type SubscriptionCoreClaudeUsageRow = { status: string; provider_state: Record | null; quota: unknown; quota_revision: number | string | null; quota_observed_refresh_generation: number | string | null; quota_updated_at: Date | string | null; /** * The connection's row version (the account listing's `version`): the * shared connection reads select it; a personal row gets it from the * owner-only version reader. Required: the projection throws without it. */ version?: number | string; }; /** A live refresh outcome to report instead of the one derived from the row. */ export type SubscriptionCoreClaudeUsageRefresh = { status: ClaudeSubscriptionUsage["refreshStatus"]; checkedAt: string | null; }; /** * Whether the connection's credential lacks the usage scope, from the * adapter-owned `provider_state.oauthScopes` (absent or malformed: unknown, * so not reported). */ export function subscriptionCoreClaudeUsageScopeMissing( providerState: Record | null, ): boolean { const scopes = providerState?.oauthScopes; return ( Array.isArray(scopes) && scopes.every((scope) => typeof scope === "string") && !scopes.includes(SUBSCRIPTION_CORE_CLAUDE_USAGE_SCOPE) ); } /** A connection row without a usable row version (never reported as 0 or null). */ export class SubscriptionCoreClaudeUsageVersionMissing extends Error { constructor() { super("Claude usage needs the connection's row version"); } } /** The row version a usage response reports; throws when the row has none. */ export function subscriptionCoreClaudeUsageVersion(row: { version?: number | string }): number { const version = row.version === undefined ? Number.NaN : Number(row.version); if (!Number.isSafeInteger(version) || version < 1) throw new SubscriptionCoreClaudeUsageVersionMissing(); return version; } // The upstream model families of the family windows (the adapter's decoder). const FAMILY_PREFIXES: Partial> = { seven_day_opus: "claude-opus-", seven_day_sonnet: "claude-sonnet-", seven_day_fable: "claude-fable-", seven_day_overage_included: "claude-fable-", }; /** * The legacy status of one stored window: * * - a window the core holds as exhausted is `rejected`, whatever reading it * came from (a partial reading may have kept it from an earlier one); * - after a usage-endpoint reading every other window is null, as legacy * usage-endpoint windows were; * - after a response-header reading `ok` and `warning` map back to * `allowed` and `allowed_warning`; the decoder stores family and overage * windows as `unknown` (they never block the connection), so their * header `rejected` is derived: a family window while a model of its * family is cooling down, the overage window while the connection itself * is exhausted (an overage that covered the plan would have kept it * serving). Anything else is null. */ function windowStatus( window: QuotaWindow, quota: SubscriptionQuota, now: number, ): ClaudeUsageWindow["status"] { if (window.status === "exhausted") return "rejected"; if (quota.source === "usage_endpoint") return null; if (window.status === "ok") return "allowed"; if (window.status === "warning") return "allowed_warning"; const running = window.resetsAt === null || window.resetsAt > now; const family = FAMILY_PREFIXES[window.id as ClaudeUsageWindow["id"]]; if (family !== undefined) return running && Object.entries(quota.modelCooldowns).some( ([modelId, until]) => until > now && subscriptionCoreClaudeUpstreamModelIds([modelId]).some((upstream) => upstream.startsWith(family), ), ) ? "rejected" : null; if (window.id === "overage") return running && quotaCapacity(quota, now).kind === "exhausted" ? "rejected" : null; return null; } function iso(value: number | null): string | null { if (value === null || !Number.isFinite(value)) return null; const date = new Date(value); return Number.isNaN(date.getTime()) ? null : date.toISOString(); } /** * The stored provider details as usage response fields. Each part is * checked against its contract and dropped when it does not match (a * newer build may have stored a shape this one does not know). */ export function subscriptionCoreClaudeUsageDetails( quota: SubscriptionQuota | null, ): Pick< ClaudeSubscriptionUsage, "limitResets" | "wallReset" | "limits" | "extraUsage" | "surfaceWindows" | "serviceState" > { const details = quota?.providerDetails ?? {}; const part = ( key: string, schema: { safeParse(value: unknown): { success: boolean; data?: T } }, ) => { const stored = details[key]; if (!stored) return undefined; const parsed = schema.safeParse(stored.value); return parsed.success ? (parsed.data as T) : undefined; }; const limitResets = part("limitResets", ClaudeLimitResets.nullable()); const wallReset = part("wallReset", ClaudeWallReset.nullable()); const limits = part("limits", ClaudeUsageLimit.array().max(16)); const extraUsage = part("extraUsage", ClaudeExtraUsage.nullable()); const surfaceWindows = part("surfaceWindows", ClaudeSurfaceUsageWindow.array().max(3)); const serviceState = part("serviceState", ClaudeServiceState.nullable()); return { ...(limitResets !== undefined ? { limitResets } : {}), ...(wallReset !== undefined ? { wallReset } : {}), ...(limits !== undefined ? { limits } : {}), ...(extraUsage !== undefined ? { extraUsage } : {}), ...(surfaceWindows !== undefined ? { surfaceWindows } : {}), ...(serviceState !== undefined ? { serviceState } : {}), }; } /** * One core connection's stored quota as the legacy usage response. * * - `credentialVersion` is the connection's row version (the account * listing's `version`; it moves on reconnect and rename, never on a token * refresh). A row without one throws: a connected account never reports 0 * or null. * - Windows keep the legacy ids, percentages and ISO resets; every stored * window stays visible whatever credential generation observed it (as * legacy kept them across token refreshes). Statuses: see `windowStatus`. * The shared quota keeps no per-window time or source, so each window * carries the newest observation's. * - The refresh status is `reconnect` while the connection needs a new * sign-in; else `refresh` when given (a live read decides by the * credential it decoded); else `scope_required` when * `provider_state.oauthScopes` lacks the usage scope, `available` when the * newest stored observation is a usage-endpoint reading and `not_checked` * otherwise. * - `options.now` (epoch milliseconds, default `Date.now()`) is the instant * window statuses are judged at; a refresh passes its own clock. */ export function projectSubscriptionCoreClaudeUsage( row: SubscriptionCoreClaudeUsageRow, refresh?: SubscriptionCoreClaudeUsageRefresh, options: { now?: number } = {}, ): ClaudeSubscriptionUsage { const credentialVersion = subscriptionCoreClaudeUsageVersion(row); const now = options.now ?? Date.now(); const quota = decodeSubscriptionQuota(row); const observedAt = iso(quota?.observedAt ?? null); const source = quota === null || quota.source === null || observedAt === null ? null : quota.source === "usage_endpoint" ? ("provider" as const) : ("response_headers" as const); const seen = new Set(); const windows: ClaudeUsageWindow[] = []; const stored = observedAt === null ? null : quota; for (const window of stored?.windows ?? []) { const id = ClaudeUsageWindowId.safeParse(window.id); if (!id.success || seen.has(id.data)) continue; seen.add(id.data); windows.push({ id: id.data, usedPercent: window.usedPercent !== null && Number.isFinite(window.usedPercent) && window.usedPercent >= 0 ? window.usedPercent : null, resetsAt: iso(window.resetsAt), status: windowStatus(window, stored!, now), observedAt: observedAt!, ...(source ? { source } : {}), }); } const derived: SubscriptionCoreClaudeUsageRefresh = row.status === "needs_relogin" ? { status: "reconnect", checkedAt: refresh?.checkedAt ?? null } : (refresh ?? (subscriptionCoreClaudeUsageScopeMissing(row.provider_state) ? { status: "scope_required", checkedAt: null } : source === "provider" ? { status: "available", checkedAt: observedAt } : { status: "not_checked", checkedAt: null })); return { // Every row a usage route can read is connected: the readers return no // disconnected connection. connected: true, credentialVersion, windows, observedAt: windows.length > 0 || source !== null ? observedAt : null, source, refreshStatus: derived.status, refreshCheckedAt: derived.checkedAt, ...subscriptionCoreClaudeUsageDetails(stored), }; }