/** * OAuth-backed subscription usage: the Anthropic and ChatGPT Codex collectors, * a normalized per-provider cache, and the per-model block decision built on it. * * The built-in adapters were ported from the nredd/pi-subagents fork * (`src/subscription-usage.ts`). Additional adapters can register in-process. * * Fetching is deliberately conservative: successful reads are cached for five * minutes, `fresh` reads within a minute share one response, and a failed read * backs the provider off (1m, 2m, 5m, then 15m) so a throttled endpoint is not * hammered. Known resets use monotonic-projected deadlines for admission; the * cached provider timestamps stay intact. Credentials go only to the registered adapter. */ import { addAbortListener } from "node:events"; import type { ExtensionContext } from "@earendil-works/pi-coding-agent"; import { normalizeReading } from "./collector-reading.ts"; import { type CollectorReading, type CollectorRegistration, isBuiltinCollector, isCollectorId, registrationFor, transferredTo, } from "./collectors.ts"; import type { ProviderConfig } from "./config.ts"; export { parseAnthropic, parseAntigravity, parseCodex } from "./builtin-collectors.ts"; import { type ModelRef, refKey } from "./model-ref.ts"; import { anchorElapsed, anchorReset, type ResetDeadline } from "./reset-deadline.ts"; export { COLLECTED_PROVIDERS } from "./collectors.ts"; /** How long a successful read is served from cache to plain `get` calls. */ const CACHE_TTL_MS = 5 * 60_000; /** Minimum spacing between user-initiated (`force`) refreshes per provider. */ const MANUAL_REFRESH_INTERVAL_MS = 60_000; /** A `fresh` read reuses a snapshot retrieved this recently, so concurrent confirmations share one read. */ const FRESH_REUSE_WINDOW_MS = 60_000; const REQUEST_TIMEOUT_MS = 10_000; /** Maximum decoded HTTP response bytes retained by a quota read. */ const MAX_USAGE_RESPONSE_BYTES = 256 * 1024; /** Monotonic-over-wall slack (slew, rounding) tolerated before a wall rollback is assumed. */ const WALL_SKEW_TOLERANCE_MS = 200; /** Failure backoff steps; the last entry is the cap. Reset on the next success. */ const FAILURE_BACKOFF_MS = [60_000, 2 * 60_000, 5 * 60_000, 15 * 60_000] as const; /** * Latest reset an external collector may report, from the read's start. A later reset is * implausible evidence and becomes unknown, which blocks only while the reading is fresh. */ const MAX_EXTERNAL_RESET_MS = 31 * 24 * 60 * 60_000; /** Clock-skew tolerance added to an Antigravity window's reported span when bounding resets. */ const ANTIGRAVITY_RESET_SKEW_MS = 5 * 60_000; /** Upper bound on a server-supplied `Retry-After`, so a bogus header cannot park a provider for days. */ const RETRY_AFTER_CEILING_MS = 60 * 60_000; /** `available`: fresh data. `stale`: old data kept after an expiry or failed refresh. */ export type UsageStatus = "available" | "stale" | "unavailable" | "error"; export interface Quantity { unit: "requests" | "tokens" | "usd" | "credits"; used?: number; limit?: number; remaining?: number; } type CollectedSpanSource = "reported" | "assumed"; export type UsageSpanSource = CollectedSpanSource | "inferred"; /** One normalized quota window with a truthful percentage. Legacy collectors default to collected spans. */ export interface UsageWindow { /** Provider-native window name, e.g. `five_hour`, `seven_day_opus`, `5h`. */ name: string; /** 0-100; values over 100 are clamped so over-limit still blocks. */ usedPercent: number; /** Epoch milliseconds, when known. */ resetAt?: number; /** Full quota-window duration in milliseconds, when known. */ durationMs?: number; /** * Provenance of `name` and `durationMs`, for display only (never read by scoring or admission). * `reported`: the provider stated the span (Anthropic's fixed windows, Codex `limit_window_seconds`). * `assumed`: guessed from position because the provider stated none. Absent on older snapshots. * `inferred`: derived from indirect evidence, e.g. a failure hint. */ spanSource?: SpanSource; /** `provider` windows gate every model; `model` windows gate only matching `families`. */ scope: "provider" | "model"; /** Family tokens a `model`-scoped window applies to, e.g. `["opus"]`. See `modelMatchesFamily`. */ families?: string[]; /** Absent on legacy windows. */ kind?: "rolling" | "calendar"; /** For calendar windows only; `at` is local HH:mm in `timeZone`. */ resetRule?: { at: string; timeZone: string; every: "day" | "week" }; /** Display and evidence only; never read by scoring. */ quantity?: Quantity; /** Absent means reported. */ basis?: "reported" | "observed" | "inferred"; } /** A bucket without a truthful percentage. An absent limit is unknown. */ export type UsageMeter = Omit, "usedPercent"> & { quantity: Quantity }; /** Display only; a balance never bypasses a quota window. */ export interface CreditPool { name: string; unit: "usd" | "credits"; role: "overage" | "prepaid"; balance?: number; unlimited?: boolean; appliesAfter?: string[]; } /** * Snapshot-side symbol: the elapsed freshness budget of a service reading. It rides on the snapshot, so * another loaded copy of this module observes the same budget. Contrast `COLLECTOR_FRESHNESS`, which a * block decision carries. */ export const READING_FRESHNESS = Symbol.for("pi-subscription-router.reading-freshness"); /** Normalized quota state for one provider at one point in time. */ export interface UsageSnapshot { [READING_FRESHNESS]?: ResetDeadline; provider: string; status: UsageStatus; windows: UsageWindow[]; meters?: UsageMeter[]; pools?: CreditPool[]; access?: "subscription" | "metered"; /** Paid credits. Only `unlimited` affects decisions; a balance never bypasses a window. */ credits?: { available: boolean; unlimited: boolean; balance?: string }; retrievedAt: number; expiresAt: number; message?: string; } /** The part of `ExtensionContext` usage reads. Unlike the ctx itself, it stays valid after its session is disposed. */ export type RegistryContext = Pick; /** Side-effecting dependencies, injectable for tests. */ export interface UsageTransport { fetch(input: string, init: RequestInit): Promise; now(): number; /** Monotonic milliseconds, independent of `now`. Defaults to `performance.now`. */ monotonicNow?(): number; getAccessToken(ctx: RegistryContext, provider: string): Promise; } /** Lifetime of the collector registration that produced a decision. */ export const COLLECTOR_EVIDENCE = Symbol.for("pi-subscription-router.collector-evidence"); /** * The wall-time adapter for standalone, timestamp-only snapshots: available and not past `expiresAt`. * Wall steps move it, so it is the fallback of `isFreshReading`, never a second verdict. */ export function wallFresh(snapshot: UsageSnapshot, now: number): boolean { return snapshot.status === "available" && snapshot.expiresAt > now; } /** * The single freshness verdict. A service reading carries its elapsed budget, which crosses module copies * with the snapshot; only timestamp-only snapshots fall back to `wallFresh`. Not pure: observing the budget * latches it (it only shrinks), so capture the verdict once at a caller boundary and pass that boolean to scorers. */ export function isFreshReading(snapshot: UsageSnapshot, now: number): boolean { const budget = snapshot[READING_FRESHNESS]; return budget ? snapshot.status === "available" && budget(now) > now : wallFresh(snapshot, now); } /** Projects a known collector reset into the current wall clock for confirmed blocks. */ export const COLLECTOR_RESET = Symbol.for("pi-subscription-router.collector-reset"); /** * Decision-side symbol: the `READING_FRESHNESS` budget of the snapshot a no-reset block came from, so the * block can be rechecked at commit, independent of the backoff it would start. */ export const COLLECTOR_FRESHNESS = Symbol.for("pi-subscription-router.collector-freshness"); /** Whether a model must not be dispatched on included quota right now, and why. */ export interface UsageDecision { [COLLECTOR_EVIDENCE]?: AbortSignal; [COLLECTOR_RESET]?: ResetDeadline; [COLLECTOR_FRESHNESS]?: ResetDeadline; block: boolean; message?: string; window?: string; resetAt?: number; /** Scope of the exhausted window: which models the block also covers. */ scope?: "provider" | "model"; families?: string[]; } /** * True when `family` appears in `modelId` as a whole token: bounded on each side * by the string edge or one of `-./:`, case-insensitive. `opus` matches * `claude-opus-4-1` and `us.anthropic.claude-opus-4-1-v1:0`, not `claude-magnopus`. */ export function modelMatchesFamily(modelId: string, family: string): boolean { const escaped = family.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); return new RegExp(`(?:^|[-./:])${escaped}(?:$|[-./:])`, "i").test(modelId); } function errorSnapshot(provider: string, status: "error" | "unavailable", now: number, message: string): UsageSnapshot { return { provider, status, windows: [], retrievedAt: now, expiresAt: now, message }; } /** * Set on an `unavailable` snapshot whose provider has no usage source at all: no collector, or a * credential its collector cannot read (an API key). Only then may confirmation infer from the * failure. A missing credential or a collector retired mid-read is a failed read instead. * Non-enumerable, so snapshot equality and serialization are unchanged. */ export const NO_USAGE_SOURCE = Symbol.for("pi-subscription-router.no-usage-source"); function unmeasured(provider: string, now: number, message: string): UsageSnapshot { return Object.defineProperty(errorSnapshot(provider, "unavailable", now, message), NO_USAGE_SOURCE, { value: true }); } /** `cached` with its last-known windows, marked stale and expired as of `now`. */ function staleSnapshot(cached: UsageSnapshot, now: number, message: string | undefined): UsageSnapshot { return { ...cached, status: "stale", expiresAt: now, message }; } function isoMinute(epochMs: number): string { return `${new Date(epochMs).toISOString().slice(0, 16)}Z`; } /** `Retry-After` as milliseconds from `now`: delta-seconds or an HTTP-date. */ function retryAfterMs(header: string | null, now: number): number | undefined { if (!header) return undefined; const trimmed = header.trim(); const ms = /^\d+$/.test(trimmed) ? Number(trimmed) * 1000 : Date.parse(trimmed) - now; return Number.isFinite(ms) ? ms : undefined; } interface FetchOutcome { snapshot: UsageSnapshot; /** True when a network read was attempted and failed; drives the backoff. */ failed: boolean; retryAfterMs?: number; } /** Options for `UsageService.get`. */ export interface UsageGetOptions { /** User-initiated; limited to once per minute per provider. */ force?: boolean; /** Bypass the TTL, but reuse a read from the last minute. */ fresh?: boolean; /** * Epoch ms. Reuse a cached or in-flight read only if it started at or after * this, e.g. the failure a confirmation is about. Concurrent confirmations of * the same failure still share one request. */ notBefore?: number; /** Detaches only this caller; a shared in-flight read continues. */ signal?: AbortSignal; } /** Initiation-ordered reads retain local evidence without publishing superseded results. */ interface UsageRead { /** Causal initiation sequence: immune to wall steps, unlike `startedAt`. */ order: number; startedAt: number; /** Monotonic reading at initiation, to detect a wall step since. */ startedMono: number; read: Promise; snapshot?: UsageSnapshot; newer?: UsageRead; } /** * Whether a read begun at wall `startedAt`, `elapsedMs` of monotonic time ago, can have followed a failure * stamped `notBefore`. The wall stamps agree only if the wall clock advanced at least as far as the monotonic * one since the read; a rollback in between makes the stamps incomparable, so the read is not credited. */ function followsFailure(startedAt: number, elapsedMs: number, notBefore: number, now: number): boolean { return startedAt >= notBefore && now - startedAt >= elapsedMs - WALL_SKEW_TOLERANCE_MS; } /** Resolve adapter IDs without changing the provider whose credentials are read. */ export function collectorIdFor(provider: string, providers: Readonly>): string { return providers[provider]?.collector?.id ?? provider; } /** One provider's grant to the registration it resolved. `reconfigured` marks a config-driven unbind. */ interface CollectorBinding { registration: CollectorRegistration; binding: CollectorRegistration; unbind: AbortController; reconfigured: boolean; } /** Subscription quota state for OAuth-backed consumer plans. */ export class UsageService { private readonly collectors = new Map(); private providers: Readonly> = {}; /** Aliased providers whose authorized registration retired. Only `configureCollectors` re-authorizes. */ private readonly revoked = new Set(); private readonly evidence = new WeakMap(); // Stale snapshots retain the same normalized window objects and their original reset budgets. private readonly resets = new WeakMap(); private readonly readOrder = new WeakMap(); private nextReadOrder = 0; private readonly monotonicNow = () => this.transport.monotonicNow?.() ?? performance.now(); private readonly cache = new Map(); private readonly listeners = new Set<() => void>(); private readonly generations = new Map(); private readonly lastManualRefreshAt = new Map(); private readonly inFlight = new Map(); private readonly backoff = new Map(); constructor( private readonly transport: UsageTransport = { fetch, now: () => Date.now(), getAccessToken: (ctx, provider) => ctx.modelRegistry.getApiKeyForProvider(provider), }, ) {} /** * Apply provider declarations before serving reads for this config. A configured alias is a * credential grant to the registration that owns its ID at first resolution; each call * re-authorizes aliases whose granted registration has since retired. */ configureCollectors(providers: Readonly> = {}): void { // Swap atomically before any abort callback runs: a retirement those callbacks cause // (e.g. a reentrant replacement) postdates this config and must stay revoked. this.providers = providers; this.revoked.clear(); const stale: CollectorBinding[] = []; for (const [provider, entry] of this.collectors) { if (entry.registration === registrationFor(collectorIdFor(provider, providers))) continue; entry.reconfigured = true; this.collectors.delete(provider); stale.push(entry); } for (const { unbind } of stale) unbind.abort(); } /** * Current usage for `provider`: cached while younger than five minutes, else a * network read (see `UsageGetOptions` for `fresh` and `force`). During failure * backoff nothing touches the network: the last snapshot comes back `stale`, * or an `error` snapshot when there is none. Never rejects. */ async get(ctx: RegistryContext, provider: string, options: UsageGetOptions = {}): Promise { const now = this.transport.now(); if (options.signal?.aborted) return errorSnapshot(provider, "error", now, "Usage request was cancelled."); const collector = this.currentCollector(provider); if (!collector) return unmeasured(provider, now, "No subscription usage collector exists for this provider."); const generation = this.generations.get(provider) ?? 0; const cached = this.cache.get(provider); const force = options.force === true; if (!force && cached?.status === "available") { const remaining = (cached[READING_FRESHNESS] as ResetDeadline)(now) - now; const reusable = options.notBefore === undefined || followsFailure(cached.retrievedAt, CACHE_TTL_MS - remaining, options.notBefore, now); if (reusable && remaining > (options.fresh ? CACHE_TTL_MS - FRESH_REUSE_WINDOW_MS : 0)) return cached; } const backoff = this.backoff.get(provider); if (backoff && backoff.until > now) { const until = new Date(backoff.until).toISOString(); return this.withStale(cached, provider, now, `Backing off after a failed usage request until ${until}.`); } if (force) { if (now - (this.lastManualRefreshAt.get(provider) ?? 0) < MANUAL_REFRESH_INTERVAL_MS) { return this.withStale(cached, provider, now, "Manual refresh is limited to once per minute."); } this.lastManualRefreshAt.set(provider, now); } const refresh = this.refresh(ctx, provider, collector, now, options.notBefore); const failed = () => errorSnapshot(provider, "error", now, "Usage request failed."); const snapshot = await waitForCaller(refresh.read, options.signal, failed, () => { // The one outer deadline owns fallback selection. Inner waits must not // race it with separate timers or extend it for each newer owner. let fallback: UsageSnapshot | undefined; const consider = (candidate: UsageSnapshot | undefined) => { if ( candidate && isFreshReading(candidate, this.transport.now()) && candidate.retrievedAt >= Math.max(refresh.startedAt, options.notBefore ?? refresh.startedAt) && (this.readOrder.get(candidate) as number) >= refresh.order && (!fallback || (this.readOrder.get(candidate) as number) > (this.readOrder.get(fallback) as number)) ) fallback = candidate; }; for (let entry: UsageRead | undefined = refresh; entry; entry = entry.newer) consider(entry.snapshot); consider(this.cache.get(provider)); return fallback; }); if (!options.signal?.aborted && collector.signal.aborted) { return errorSnapshot(provider, "unavailable", now, "Usage collector changed during the read."); } if (generation !== (this.generations.get(provider) ?? 0) && !options.signal?.aborted) { const current = this.peek(provider); return current?.status === "available" && current.retrievedAt >= (options.notBefore ?? 0) ? current : errorSnapshot( provider, "error", this.transport.now(), "Usage evidence preceded a verified reset; confirmation requires a new read.", ); } if (!snapshot) { return errorSnapshot( provider, "error", now, options.signal?.aborted ? "Usage request was cancelled." : "Usage request timed out.", ); } return this.observed(snapshot); } /** * Applies the freshness verdict to a reading about to leave `get`: an `available` reading whose * budget expired is downgraded to `stale` (data kept), so `get` never returns it as available. */ private observed(snapshot: UsageSnapshot): UsageSnapshot { if (snapshot.status !== "available") return snapshot; const now = this.transport.now(); return isFreshReading(snapshot, now) ? snapshot : this.stale(snapshot, now, "Usage read outlived its freshness before it was returned."); } /** Discard only this provider's cached evidence and prior read ownership after verified server mutation. */ invalidate(provider: string): void { this.generations.set(provider, (this.generations.get(provider) ?? 0) + 1); const changed = this.cache.delete(provider); this.inFlight.delete(provider); this.backoff.delete(provider); if (changed) this.notify(); } /** Subscribe to changes in cached readings. */ subscribe(listener: () => void): () => void { this.listeners.add(listener); return () => void this.listeners.delete(listener); } /** Read the current cache without refreshing credentials or making requests. */ cachedSnapshots(): UsageSnapshot[] { return [...this.cache.values()]; } /** Display metadata from the binding that produced this exact cached reading. */ displayForSnapshot(snapshot: UsageSnapshot) { return this.evidence.get(snapshot)?.collector.display; } private notify(): void { for (const listener of this.listeners) listener(); } /** Cached snapshot without any network read; expired data is reported `stale`. */ peek(provider: string): UsageSnapshot | undefined { this.currentCollector(provider); const cached = this.cache.get(provider); if (!cached) return undefined; const now = this.transport.now(); return (cached[READING_FRESHNESS] as ResetDeadline)(now) > now ? cached : this.withStale(cached, provider, now, "Cached usage data is stale."); } /** Observe cached reset budgets even when a confirmed mark takes precedence. */ observeResets(provider: string): void { const cached = this.cache.get(provider); if (!cached) return; const now = this.transport.now(); cached[READING_FRESHNESS]?.(now); for (const window of cached.windows) this.resets.get(window)?.(now); } /** * Whether `model` is blocked on included quota, from cached data only. Blocks * when a matching window is exhausted in fresh data, or in stale data whose * known reset is still ahead (staleness cannot refill a window early). Stale * data with an unknown or past reset, missing data, and failed reads fail open. * An unlimited plan never blocks; a credit balance never bypasses a window. */ decisionFor(model: ModelRef, snapshot = this.peek(model.provider)): UsageDecision { if (!snapshot || (snapshot.status !== "available" && snapshot.status !== "stale")) return { block: false }; const registration = this.evidence.get(snapshot); if (registration?.signal.aborted || snapshot.credits?.unlimited === true) return { block: false }; const now = this.transport.now(); const freshUntil = snapshot[READING_FRESHNESS]?.(now) ?? Infinity; // Record forward steps for every reset before choosing the first blocker. const projected = snapshot.windows.map((window) => { const deadline = this.resets.get(window); return { window, deadline, resetAt: deadline?.(now) ?? window.resetAt }; }); for (const { window, deadline, resetAt } of projected) { if ( !(window.usedPercent >= 100) || (window.scope !== "provider" && !window.families?.some((family) => modelMatchesFamily(model.id, family))) ) continue; if (resetAt === undefined ? snapshot.status !== "available" || freshUntil <= now : resetAt <= now) continue; const reset = resetAt === undefined ? "an unknown time" : new Date(resetAt).toISOString(); const decision: UsageDecision = { block: true, window: window.name, resetAt, scope: window.scope, families: window.families, message: `${refKey(model)}: ${window.name} is exhausted and resets ${reset}.`, }; if (registration) Object.defineProperty(decision, COLLECTOR_EVIDENCE, { value: registration.signal }); if (deadline) Object.defineProperty(decision, COLLECTOR_RESET, { value: deadline }); if (resetAt === undefined && snapshot[READING_FRESHNESS]) Object.defineProperty(decision, COLLECTOR_FRESHNESS, { value: snapshot[READING_FRESHNESS] }); return decision; } return { block: false }; } /** Human-readable one-liner for UI and tool output. */ format(snapshot: UsageSnapshot | undefined): string { if (!snapshot) return "usage unavailable (not checked)"; if (snapshot.status !== "available") return `usage ${snapshot.status}: ${snapshot.message ?? "not available"}`; return snapshot.windows .map((window) => { const reset = window.resetAt ? `, resets ${new Date(window.resetAt).toLocaleTimeString()}` : ""; return `${window.name} ${Math.round(window.usedPercent)}% used${reset}`; }) .join("; "); } /** * System-prompt rendering with coarse 25% buckets and UTC minute resets only for * exhausted windows, so the text (and the prompt-cache prefix) stays stable * across ordinary turns. Stale snapshots keep their last-known windows. */ formatForPrompt(snapshot: UsageSnapshot | undefined): string { if (!snapshot) return "usage unavailable"; if (snapshot.windows.length === 0) return `usage ${snapshot.status}`; return snapshot.windows .map((window) => { const used = window.usedPercent; const bucket = used >= 100 ? window.resetAt ? `exhausted until ${isoMinute(window.resetAt)}` : "exhausted, reset unknown" : used < 25 ? "<25%" : used < 50 ? "25-50%" : used < 75 ? "50-75%" : "75-100%"; return `${window.name} ${bucket}`; }) .join("; "); } private withStale(cached: UsageSnapshot | undefined, provider: string, now: number, message: string): UsageSnapshot { return cached ? this.stale(cached, now, message) : errorSnapshot(provider, "error", now, message); } private stale(cached: UsageSnapshot, now: number, message: string | undefined): UsageSnapshot { const stale = staleSnapshot(cached, now, message); this.evidence.set(stale, this.evidence.get(cached)); Object.defineProperty(stale, READING_FRESHNESS, { value: cached[READING_FRESHNESS] }); return stale; } private currentCollector(provider: string): CollectorRegistration | undefined { // Checked again here: the provider, not the collector ID, selects the credential. if (!isCollectorId(provider)) return undefined; const current = this.collectors.get(provider); if (current) return current.binding; if (this.revoked.has(provider)) return undefined; const id = collectorIdFor(provider, this.providers); const registration = registrationFor(id); return registration && this.bind(provider, id, registration); } /** Grant `provider`'s credential to `registration` until it retires or config changes. */ private bind(provider: string, id: string, registration: CollectorRegistration): CollectorRegistration { const unbind = new AbortController(); const binding = { collector: registration.collector, signal: AbortSignal.any([registration.signal, unbind.signal]), }; const entry: CollectorBinding = { registration, binding, unbind, reconfigured: false }; this.collectors.set(provider, entry); addAbortListener(binding.signal, () => { this.invalidate(provider); this.lastManualRefreshAt.delete(provider); if (this.collectors.get(provider) === entry) this.collectors.delete(provider); // The alias granted credentials to this registration, not to a later owner of its ID, unless // the owner replaced it through its handle. A config-driven unbind is not a retirement. if (id === provider || entry.reconfigured) return; const successor = transferredTo(registration); if (successor) this.bind(provider, id, successor); else this.revoked.add(provider); }); return binding; } private refresh( ctx: RegistryContext, provider: string, registration: CollectorRegistration, now: number, notBefore?: number, ): UsageRead { const existing = this.inFlight.get(provider); if ( existing && (notBefore === undefined || followsFailure(existing.startedAt, this.monotonicNow() - existing.startedMono, notBefore, now)) ) return existing; const retired = () => errorSnapshot(provider, "unavailable", now, "Usage collector changed during the read."); const order = ++this.nextReadOrder; const startedMono = this.monotonicNow(); const refresh = this.fetchSnapshot(ctx, provider, registration, now) .then(async (outcome) => { if (registration.signal.aborted) return retired(); this.evidence.set(outcome.snapshot, registration); this.readOrder.set(outcome.snapshot, order); entry.snapshot = outcome.snapshot; // A post-failure read may supersede a slow warm-up. Only the newest // initiated read owns cache/backoff writes, regardless of completion order. if (this.inFlight.get(provider)?.read !== refresh) { // Follow only later owners, never older reads: the dependency graph // is acyclic. The caller's total wait is bounded across supersessions. const newer = this.inFlight.get(provider); const latest = newer ? await newer.read : this.cache.get(provider); const freshEnough = (snapshot: UsageSnapshot | undefined): snapshot is UsageSnapshot => snapshot !== undefined && isFreshReading(snapshot, this.transport.now()) && (this.readOrder.get(snapshot) as number) >= order && snapshot.retrievedAt >= Math.max(now, notBefore ?? now); if (freshEnough(latest)) return latest; // This caller can use its exact live result, but must not overwrite // the newer owner's cache or clear the newer failure's backoff. if (freshEnough(outcome.snapshot)) return outcome.snapshot; if (latest) return latest; return errorSnapshot( provider, "error", this.transport.now(), "Usage request was superseded by a newer read.", ); } if (outcome.snapshot.status === "available" && !isFreshReading(outcome.snapshot, this.transport.now())) { // The fetch resolved after the reading's elapsed budget: keep the data, never as available. const expired = this.stale( outcome.snapshot, this.transport.now(), "Usage read completed after its freshness expired.", ); this.cache.set(provider, expired); this.notify(); return expired; } if (outcome.snapshot.status === "available") { this.cache.set(provider, outcome.snapshot); this.notify(); this.backoff.delete(provider); } else if (outcome.failed) { this.recordFailure(provider, outcome.retryAfterMs); } const cached = this.cache.get(provider); if (outcome.snapshot.status !== "available" && cached) { const stale = this.stale(cached, this.transport.now(), outcome.snapshot.message); this.cache.set(provider, stale); this.notify(); return stale; } return outcome.snapshot; }) .finally(() => { if (this.inFlight.get(provider)?.read === refresh) this.inFlight.delete(provider); }); const entry: UsageRead = { order, startedAt: now, startedMono, read: refresh }; if (existing) existing.newer = entry; this.inFlight.set(provider, entry); return entry; } private recordFailure(provider: string, retryAfter: number | undefined): void { const failures = (this.backoff.get(provider)?.failures ?? 0) + 1; // The ladder ascends, so its largest reached step is the step for this failure count. const step = Math.max(...FAILURE_BACKOFF_MS.slice(0, failures)); const delay = Math.min(Math.max(step, retryAfter ?? 0), RETRY_AFTER_CEILING_MS); this.backoff.set(provider, { failures, until: this.transport.now() + delay }); } private async fetchSnapshot( ctx: RegistryContext, provider: string, { collector, signal: lifetime }: CollectorRegistration, now: number, ): Promise { const monotonicAtRead = this.monotonicNow(); const unfetched = (status: "error" | "unavailable", message: string): FetchOutcome => ({ snapshot: errorSnapshot(provider, status, now, message), failed: false, }); let token: string | undefined; const lookupTimedOut = Symbol("credential lookup timeout"); let lookupTimer: ReturnType | undefined; try { // Core owns refresh/persistence. Bound only our wait; its API has no // cancellation parameter, so a late owner result is ignored, not aborted. const result = await Promise.race([ this.transport.getAccessToken(ctx, provider), new Promise((resolve) => { lookupTimer = setTimeout(() => resolve(lookupTimedOut), REQUEST_TIMEOUT_MS); }), ]); if (result === lookupTimedOut) { return { ...unfetched("error", "OAuth credential lookup timed out."), failed: true }; } token = result; } catch { return unfetched("error", "OAuth credential lookup failed."); } finally { clearTimeout(lookupTimer); } if (!token) return unfetched("unavailable", "No OAuth credential is available for this provider."); const failure = (message: string, retryAfter?: number): FetchOutcome => ({ snapshot: errorSnapshot(provider, "error", now, message), failed: true, retryAfterMs: retryAfter, }); const controller = new AbortController(); const signal = AbortSignal.any([controller.signal, lifetime]); let timedOut = false; const timeout = setTimeout(() => { timedOut = true; controller.abort(); }, REQUEST_TIMEOUT_MS); try { signal.throwIfAborted(); if (collector.acceptsCredential?.(token) === false) { return { snapshot: unmeasured(provider, now, "This credential has no subscription usage window (e.g. an API key)."), failed: false, }; } signal.throwIfAborted(); let parsed: CollectorReading | undefined; if (collector.kind === "http") { const { url, ...init } = collector.request(token); const response = await this.transport.fetch(url, { ...init, signal }); if (!response.ok) { // The byte cap and deadline stop here; never wait for the source to stop. void response.body?.cancel().catch(() => {}); return failure( `Usage request failed (${response.status}).`, retryAfterMs(response.headers.get("retry-after"), this.transport.now()), ); } // Real fetch rejects on abort. Keep the legacy late-response behavior for // injected transports that resolve despite abort, but still bound the body. const payload = await readUsageJson(response, timedOut ? lifetime : signal); lifetime.throwIfAborted(); parsed = collector.parse(payload); } else { // Custom reads get the same deadline even if the adapter ignores abort. const read = collector.read({ token, signal, now: () => this.transport.now() }); parsed = await untilAborted(read, signal); } const latestReset = !isBuiltinCollector(collector) ? () => now + MAX_EXTERNAL_RESET_MS : collector.provider === "antigravity" ? (durationMs: number | undefined) => now + Number(durationMs) + ANTIGRAVITY_RESET_SKEW_MS : () => Infinity; const reading = normalizeReading(parsed, latestReset); if (!reading) return failure("Usage response had an unsupported shape."); for (const window of reading.windows) { if (window.resetAt !== undefined) { this.resets.set(window, anchorReset(window.resetAt, now, monotonicAtRead, this.monotonicNow)); } } const snapshot: UsageSnapshot = { provider, status: "available", retrievedAt: now, expiresAt: now + CACHE_TTL_MS, ...reading, }; Object.defineProperty(snapshot, READING_FRESHNESS, { value: anchorElapsed(CACHE_TTL_MS, monotonicAtRead, this.monotonicNow), }); return { snapshot, failed: false }; } catch (error) { if (isAbortError(error)) return failure(timedOut ? "Usage request timed out." : "Usage request was cancelled."); return failure("Usage request failed."); } finally { clearTimeout(timeout); } } } async function readUsageJson(response: Response, signal: AbortSignal): Promise { const reader = response.body?.getReader(); if (!reader) throw new Error("Missing usage response body."); const decoder = new TextDecoder(); let bytes = 0; let json = ""; try { for (;;) { const { done, value } = await untilAborted(reader.read(), signal); if (done) break; bytes += value.byteLength; if (bytes > MAX_USAGE_RESPONSE_BYTES) throw new Error("Usage response exceeded its byte limit."); json += decoder.decode(value, { stream: true }); } } catch (error) { // Cancellation can itself hang or reject; never wait for the source to stop. void reader.cancel().catch(() => {}); throw error; } finally { reader.releaseLock(); } return JSON.parse(json + decoder.decode()); } /** Total: a throwable's `name` getter or prototype trap cannot escape sanitization. */ function isAbortError(error: unknown): boolean { try { return error instanceof Error && error.name === "AbortError"; } catch { return false; } } /** Bound awaited work even when an adapter ignores the signal. */ async function untilAborted(work: Promise, signal: AbortSignal): Promise { let listener: Disposable | undefined; const cancelled = new Promise((_, reject) => { listener = addAbortListener(signal, () => reject(signal.reason)); }); try { return await Promise.race([cancelled, work]); } finally { listener?.[Symbol.dispose](); } } /** Prefer the completed read; at the total deadline use live evidence, never on abort. A rejected read fails now. */ function waitForCaller( refresh: Promise, signal: AbortSignal | undefined, onRejected: () => UsageSnapshot, onTimeout: () => UsageSnapshot | undefined, ): Promise { // The credential lookup runs synchronously inside `refresh` and may abort the signal // before the listener below exists; an `abort` listener added afterwards never fires. if (signal?.aborted) return Promise.resolve(undefined); return new Promise((resolve) => { let settled = false; const finish = (snapshot?: UsageSnapshot) => { if (settled) return; settled = true; clearTimeout(timer); signal?.removeEventListener("abort", abort); resolve(snapshot); }; const abort = () => finish(); // One credential lookup plus one fetch, regardless of supersession count. Re-check // the signal: a foreign listener can stop the `abort` event before ours runs. const timer = setTimeout(() => finish(signal?.aborted ? undefined : onTimeout()), 2 * REQUEST_TIMEOUT_MS); signal?.addEventListener("abort", abort, { once: true }); void refresh.then(finish, () => finish(onRejected())); }); }