@specode/pi-subscription-usage 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/query.ts ADDED
@@ -0,0 +1,390 @@
1
+ // Runtime-auth and origin checks adapted from @narumitw/pi-usage@0.53.0 (MIT).
2
+ import { randomBytes } from "node:crypto";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import {
5
+ errorMessage,
6
+ fingerprintResolvedAuth,
7
+ redactUsageError,
8
+ } from "./core.ts";
9
+ import { normalizeCodexUsage } from "./providers/codex.ts";
10
+ import {
11
+ normalizeGrokBilling,
12
+ normalizeGrokIdentity,
13
+ } from "./providers/grok.ts";
14
+ import { normalizeKimiUsage } from "./providers/kimi.ts";
15
+ import { normalizeOpenCodeGoUsage } from "./providers/opencode-go.ts";
16
+ import type {
17
+ ResolvedUsageAuth,
18
+ UsageProviderAdapter,
19
+ UsageReport,
20
+ } from "./types.ts";
21
+
22
+ const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
23
+ const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
24
+ const KIMI_USAGE_URL = "https://api.kimi.com/coding/v1/usages";
25
+ const GROK_USER_URL = "https://cli-chat-proxy.grok.com/v1/user";
26
+ const GROK_BILLING_URL =
27
+ "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
28
+ const MAX_SUCCESS_BODY_BYTES = 64 * 1024;
29
+ const MAX_ERROR_BODY_BYTES = 4 * 1024;
30
+
31
+ type PiModel = NonNullable<ExtensionContext["model"]>;
32
+
33
+ export const AUTH_FINGERPRINT_SALT = randomBytes(32);
34
+
35
+ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
36
+ {
37
+ id: "openai-codex",
38
+ displayName: "OpenAI Codex",
39
+ providerIds: ["openai-codex"],
40
+ semantics: {
41
+ kind: "consumer-subscription",
42
+ label: "ChatGPT subscription limits",
43
+ },
44
+ async query(auth, signal, timeoutMs) {
45
+ return normalizeCodexUsage(
46
+ await fetchProviderJson(
47
+ CODEX_USAGE_URL,
48
+ auth,
49
+ signal,
50
+ timeoutMs,
51
+ "Codex usage endpoint",
52
+ ),
53
+ Date.now(),
54
+ );
55
+ },
56
+ },
57
+ {
58
+ id: "opencode-go",
59
+ displayName: "OpenCode Go",
60
+ providerIds: ["opencode-go"],
61
+ semantics: { kind: "consumer-subscription", label: "OpenCode Go plan usage" },
62
+ async query(auth, signal, timeoutMs) {
63
+ return normalizeOpenCodeGoUsage(
64
+ await fetchProviderJson(
65
+ OPENCODE_GO_USAGE_URL,
66
+ auth,
67
+ signal,
68
+ timeoutMs,
69
+ "OpenCode Go usage endpoint",
70
+ ),
71
+ Date.now(),
72
+ );
73
+ },
74
+ },
75
+ {
76
+ id: "kimi-coding",
77
+ displayName: "Kimi Coding",
78
+ providerIds: ["kimi-coding"],
79
+ semantics: { kind: "consumer-subscription", label: "Kimi Coding plan usage" },
80
+ async query(auth, signal, timeoutMs) {
81
+ return normalizeKimiUsage(
82
+ await fetchProviderJson(
83
+ KIMI_USAGE_URL,
84
+ auth,
85
+ signal,
86
+ timeoutMs,
87
+ "Kimi usage endpoint",
88
+ ),
89
+ Date.now(),
90
+ );
91
+ },
92
+ },
93
+ {
94
+ id: "xai",
95
+ displayName: "Grok",
96
+ providerIds: ["xai", "xai-auth"],
97
+ semantics: {
98
+ kind: "consumer-subscription",
99
+ label: "SuperGrok subscription usage",
100
+ },
101
+ requiresOAuth: true,
102
+ async query(auth, signal, timeoutMs) {
103
+ const identity = await fetchProviderJson(
104
+ GROK_USER_URL,
105
+ auth,
106
+ signal,
107
+ timeoutMs,
108
+ "Grok identity endpoint",
109
+ { headers: grokHeaders() },
110
+ );
111
+ const userId = normalizeGrokIdentity(identity);
112
+ const billing = await fetchProviderJson(
113
+ GROK_BILLING_URL,
114
+ auth,
115
+ signal,
116
+ timeoutMs,
117
+ "Grok billing endpoint",
118
+ { headers: grokHeaders(userId) },
119
+ );
120
+ return normalizeGrokBilling(billing, Date.now());
121
+ },
122
+ },
123
+ ];
124
+
125
+ export function adapterForProvider(
126
+ providerId: string | undefined,
127
+ ): UsageProviderAdapter | undefined {
128
+ return SUPPORTED_ADAPTERS.find((adapter) =>
129
+ providerId ? adapter.providerIds.includes(providerId) : false,
130
+ );
131
+ }
132
+
133
+ export async function resolveUsageAuth(
134
+ ctx: ExtensionContext,
135
+ adapter: UsageProviderAdapter,
136
+ salt: Uint8Array = AUTH_FINGERPRINT_SALT,
137
+ ): Promise<ResolvedUsageAuth | undefined> {
138
+ const current = ctx.model;
139
+ if (
140
+ current &&
141
+ adapter.providerIds.includes(current.provider) &&
142
+ !hasOfficialOrigin(current.baseUrl, current.provider)
143
+ ) {
144
+ throw new Error(
145
+ `${adapter.displayName} usage cannot send a custom provider credential to an official usage endpoint.`,
146
+ );
147
+ }
148
+ const candidates = candidateModels(ctx, adapter.providerIds).filter(
149
+ (candidate) => hasOfficialOrigin(candidate.baseUrl, candidate.provider),
150
+ );
151
+ const currentModel =
152
+ current && adapter.providerIds.includes(current.provider)
153
+ ? current
154
+ : undefined;
155
+ const model =
156
+ currentModel ??
157
+ candidates.find(
158
+ (candidate) =>
159
+ !adapter.requiresOAuth || ctx.modelRegistry.isUsingOAuth(candidate),
160
+ );
161
+ if (!model) return undefined;
162
+ if (adapter.requiresOAuth && !ctx.modelRegistry.isUsingOAuth(model)) {
163
+ throw new Error(
164
+ `${adapter.displayName} usage requires Pi OAuth; API-key auth is not accepted.`,
165
+ );
166
+ }
167
+ const result = await ctx.modelRegistry.getProviderAuth(model.provider);
168
+ if (!result) return undefined;
169
+ if (
170
+ result.auth.baseUrl &&
171
+ !hasOfficialOrigin(result.auth.baseUrl, model.provider)
172
+ ) {
173
+ throw new Error(
174
+ `${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
175
+ );
176
+ }
177
+ const authorization =
178
+ headerValue(result.auth.headers, "Authorization") ??
179
+ (result.auth.apiKey ? `Bearer ${result.auth.apiKey}` : undefined);
180
+ if (!authorization) return undefined;
181
+ const headers = { Authorization: authorization };
182
+ const secrets = [
183
+ result.auth.apiKey,
184
+ headerValue(result.auth.headers, "Authorization"),
185
+ authorization,
186
+ ].filter((value): value is string => Boolean(value));
187
+ return {
188
+ actualProviderId: model.provider,
189
+ apiKey: result.auth.apiKey,
190
+ headers,
191
+ fingerprint: fingerprintResolvedAuth({ headers }, salt),
192
+ secrets,
193
+ model,
194
+ };
195
+ }
196
+
197
+ export async function queryProviderUsage(
198
+ adapter: UsageProviderAdapter,
199
+ auth: ResolvedUsageAuth,
200
+ signal: AbortSignal,
201
+ timeoutMs: number,
202
+ ): Promise<UsageReport> {
203
+ try {
204
+ return await adapter.query(auth, signal, timeoutMs);
205
+ } catch (error) {
206
+ if (error instanceof Error && error.name === "AbortError") throw error;
207
+ throw new Error(redactUsageError(errorMessage(error), auth.secrets));
208
+ }
209
+ }
210
+
211
+ export async function fetchProviderJson(
212
+ url: string,
213
+ auth: ResolvedUsageAuth,
214
+ signal: AbortSignal,
215
+ timeoutMs: number,
216
+ description: string,
217
+ request: {
218
+ method?: "GET" | "POST";
219
+ body?: Record<string, unknown>;
220
+ headers?: Record<string, string>;
221
+ } = {},
222
+ ): Promise<Record<string, unknown>> {
223
+ const controller = new AbortController();
224
+ let timedOut = false;
225
+ const abortFromCaller = () => controller.abort();
226
+ if (signal.aborted) controller.abort();
227
+ else signal.addEventListener("abort", abortFromCaller, { once: true });
228
+ const timeout = setTimeout(() => {
229
+ timedOut = true;
230
+ controller.abort();
231
+ }, timeoutMs);
232
+ try {
233
+ const headers: Record<string, string> = {
234
+ Accept: "application/json",
235
+ "User-Agent": "@specode/pi-subscription-usage/0.1.0",
236
+ ...auth.headers,
237
+ ...request.headers,
238
+ };
239
+ if (request.body) headers["Content-Type"] = "application/json";
240
+ const response = await fetch(url, {
241
+ method: request.method ?? "GET",
242
+ headers,
243
+ redirect: "error",
244
+ ...(request.body ? { body: JSON.stringify(request.body) } : {}),
245
+ signal: controller.signal,
246
+ });
247
+ const text = await readBoundedResponse(
248
+ response,
249
+ response.ok ? MAX_SUCCESS_BODY_BYTES : MAX_ERROR_BODY_BYTES,
250
+ !response.ok,
251
+ description,
252
+ );
253
+ if (!response.ok) {
254
+ throw new Error(
255
+ `${description} returned ${response.status} ${response.statusText}: ${redactUsageError(text, auth.secrets)}`,
256
+ );
257
+ }
258
+ let parsed: unknown;
259
+ try {
260
+ parsed = JSON.parse(text);
261
+ } catch (error) {
262
+ throw new Error(
263
+ `${description} returned invalid JSON: ${errorMessage(error)}`,
264
+ );
265
+ }
266
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
267
+ throw new Error(`${description} response was not an object.`);
268
+ }
269
+ return parsed as Record<string, unknown>;
270
+ } catch (error) {
271
+ if (timedOut) {
272
+ throw new Error(
273
+ `Timed out after ${Math.round(timeoutMs / 1_000)}s while fetching usage.`,
274
+ );
275
+ }
276
+ if (signal.aborted) {
277
+ throw Object.assign(new Error("Usage query aborted."), {
278
+ name: "AbortError",
279
+ });
280
+ }
281
+ throw error;
282
+ } finally {
283
+ clearTimeout(timeout);
284
+ signal.removeEventListener("abort", abortFromCaller);
285
+ }
286
+ }
287
+
288
+ async function readBoundedResponse(
289
+ response: Response,
290
+ maxBytes: number,
291
+ truncateOverflow: boolean,
292
+ description: string,
293
+ ): Promise<string> {
294
+ if (!response.body) return "";
295
+ const reader = response.body.getReader();
296
+ const chunks: Uint8Array[] = [];
297
+ let total = 0;
298
+ let truncated = false;
299
+ try {
300
+ while (true) {
301
+ const { done, value } = await reader.read();
302
+ if (done) break;
303
+ const remaining = maxBytes - total;
304
+ if (value.byteLength > remaining) {
305
+ if (remaining > 0) chunks.push(value.subarray(0, remaining));
306
+ total = maxBytes;
307
+ truncated = true;
308
+ await reader.cancel();
309
+ break;
310
+ }
311
+ chunks.push(value);
312
+ total += value.byteLength;
313
+ }
314
+ } finally {
315
+ reader.releaseLock();
316
+ }
317
+ if (truncated && !truncateOverflow) {
318
+ throw new Error(`${description} response exceeded ${maxBytes} bytes.`);
319
+ }
320
+ const body = new Uint8Array(total);
321
+ let offset = 0;
322
+ for (const chunk of chunks) {
323
+ body.set(chunk, offset);
324
+ offset += chunk.byteLength;
325
+ }
326
+ const text = new TextDecoder().decode(body);
327
+ return truncated ? `${text}…` : text;
328
+ }
329
+
330
+ function candidateModels(
331
+ ctx: ExtensionContext,
332
+ providerIds: readonly string[],
333
+ ): PiModel[] {
334
+ const candidates: PiModel[] = [];
335
+ const seen = new Set<string>();
336
+ const add = (model: PiModel | undefined) => {
337
+ if (!model || !providerIds.includes(model.provider)) return;
338
+ const key = `${model.provider}/${model.id}`;
339
+ if (seen.has(key)) return;
340
+ seen.add(key);
341
+ candidates.push(model);
342
+ };
343
+ add(ctx.model);
344
+ for (const model of ctx.modelRegistry.getAvailable()) add(model);
345
+ for (const model of ctx.modelRegistry.getAll()) add(model);
346
+ return candidates;
347
+ }
348
+
349
+ function hasOfficialOrigin(
350
+ value: string | undefined,
351
+ providerId: string,
352
+ ): boolean {
353
+ if (!value) return false;
354
+ try {
355
+ const origin = new URL(value).origin;
356
+ if (providerId === "openai-codex") return origin === "https://chatgpt.com";
357
+ if (providerId === "opencode-go") return origin === "https://opencode.ai";
358
+ if (providerId === "kimi-coding") return origin === "https://api.kimi.com";
359
+ if (providerId === "xai" || providerId === "xai-auth") {
360
+ return (
361
+ origin === "https://api.x.ai" ||
362
+ origin === "https://cli-chat-proxy.grok.com"
363
+ );
364
+ }
365
+ return false;
366
+ } catch {
367
+ return false;
368
+ }
369
+ }
370
+
371
+ function headerValue(
372
+ headers: Record<string, string | null> | undefined,
373
+ name: string,
374
+ ): string | undefined {
375
+ return (
376
+ Object.entries(headers ?? {}).find(
377
+ ([candidate]) => candidate.toLowerCase() === name.toLowerCase(),
378
+ )?.[1] ?? undefined
379
+ );
380
+ }
381
+
382
+ function grokHeaders(userId?: string): Record<string, string> {
383
+ return {
384
+ "X-XAI-Token-Auth": "xai-grok-cli",
385
+ "x-grok-client-version": "0.1.0",
386
+ "x-grok-client-mode":
387
+ process.stdin.isTTY && process.stdout.isTTY ? "interactive" : "headless",
388
+ ...(userId ? { "x-userid": userId } : {}),
389
+ };
390
+ }
package/src/status.ts ADDED
@@ -0,0 +1,213 @@
1
+ import type { UsageBucket, UsageModel, UsageReport } from "./types.ts";
2
+
3
+ export const USAGE_STATUS_EVENT = "subscription-usage/status/v1";
4
+
5
+ export type UsageStatusWindowKind =
6
+ | "hourly"
7
+ | "weekly"
8
+ | "monthly"
9
+ | "rolling"
10
+ | "quota";
11
+
12
+ export interface UsageStatusWindow {
13
+ kind: UsageStatusWindowKind;
14
+ label: string;
15
+ remainingPercent: number;
16
+ windowMinutes?: number;
17
+ resetsAt?: number;
18
+ }
19
+
20
+ export type UsageStatusEvent =
21
+ | {
22
+ v: 1;
23
+ status: "ready";
24
+ providerId: string;
25
+ capturedAt: number;
26
+ windows: UsageStatusWindow[];
27
+ }
28
+ | {
29
+ v: 1;
30
+ status: "unavailable";
31
+ };
32
+
33
+ export function unavailableUsageStatusEvent(): UsageStatusEvent {
34
+ return { v: 1, status: "unavailable" };
35
+ }
36
+
37
+ export function buildUsageStatusEvent(
38
+ report: UsageReport,
39
+ model?: UsageModel,
40
+ ): UsageStatusEvent {
41
+ const buckets =
42
+ report.providerId === "openai-codex"
43
+ ? bucketsForCodexModel(report, model)
44
+ : report.buckets;
45
+ const windows = sortUsageBuckets(buckets).flatMap((bucket) => {
46
+ const remainingPercent = usagePercentRemaining(bucket);
47
+ if (remainingPercent === undefined) return [];
48
+ return [
49
+ {
50
+ kind: usageWindowKind(bucket),
51
+ label: compactUsageWindowLabel(bucket),
52
+ remainingPercent,
53
+ ...(bucket.windowMinutes === undefined
54
+ ? {}
55
+ : { windowMinutes: bucket.windowMinutes }),
56
+ ...(bucket.resetsAt === undefined ? {} : { resetsAt: bucket.resetsAt }),
57
+ } satisfies UsageStatusWindow,
58
+ ];
59
+ });
60
+ return {
61
+ v: 1,
62
+ status: "ready",
63
+ providerId: report.providerId,
64
+ capturedAt: report.capturedAt,
65
+ windows,
66
+ };
67
+ }
68
+
69
+ /** Plain fallback for Pi's default footer. Rich rendering belongs to session-ui. */
70
+ export function formatUsageStatusline(
71
+ report: UsageReport,
72
+ model?: UsageModel,
73
+ ): string | undefined {
74
+ const event = buildUsageStatusEvent(report, model);
75
+ if (event.status !== "ready" || event.windows.length === 0) return undefined;
76
+ return event.windows
77
+ .map(
78
+ (window) =>
79
+ `${window.label} ${Math.round(window.remainingPercent).toString()}%`,
80
+ )
81
+ .join(" · ");
82
+ }
83
+
84
+ export function usageWindowLabel(bucket: UsageBucket): string {
85
+ const kind = usageWindowKind(bucket);
86
+ if (kind === "weekly") return "1w Window";
87
+ if (kind === "monthly") return "1m Window";
88
+ if (kind === "rolling") return "Rolling Window";
89
+ if (bucket.windowMinutes && bucket.windowMinutes > 0) {
90
+ if (bucket.windowMinutes % 60 === 0) {
91
+ return `${bucket.windowMinutes / 60}h Window`;
92
+ }
93
+ return `${Math.round(bucket.windowMinutes)}m Window`;
94
+ }
95
+ return "Quota";
96
+ }
97
+
98
+ export function compactUsageWindowLabel(bucket: UsageBucket): string {
99
+ const kind = usageWindowKind(bucket);
100
+ if (kind === "weekly") return "1w";
101
+ if (kind === "monthly") return "1m";
102
+ if (kind === "rolling") return "rolling";
103
+ if (bucket.windowMinutes && bucket.windowMinutes > 0) {
104
+ if (bucket.windowMinutes % 60 === 0) return `${bucket.windowMinutes / 60}h`;
105
+ return `${Math.round(bucket.windowMinutes)}m`;
106
+ }
107
+ return "quota";
108
+ }
109
+
110
+ export function usageWindowKind(bucket: UsageBucket): UsageStatusWindowKind {
111
+ const key =
112
+ `${bucket.id} ${bucket.label} ${bucket.period ?? ""}`.toLowerCase();
113
+ if (key.includes("month")) return "monthly";
114
+ if (key.includes("week")) return "weekly";
115
+ if (bucket.windowMinutes === 10_080) return "weekly";
116
+ if (
117
+ bucket.windowMinutes !== undefined &&
118
+ bucket.windowMinutes >= 28 * 24 * 60 &&
119
+ bucket.windowMinutes <= 31 * 24 * 60
120
+ ) {
121
+ return "monthly";
122
+ }
123
+ if (bucket.windowMinutes !== undefined && bucket.windowMinutes > 0) {
124
+ return "hourly";
125
+ }
126
+ if (key.includes("rolling")) return "rolling";
127
+ return "quota";
128
+ }
129
+
130
+ /** Canonical status order: hourly/rolling, weekly, monthly, then other quota. */
131
+ export function sortUsageBuckets(
132
+ buckets: readonly UsageBucket[],
133
+ ): UsageBucket[] {
134
+ return [...buckets].sort((left, right) => {
135
+ const rankComparison = usageWindowRank(left) - usageWindowRank(right);
136
+ if (rankComparison !== 0) return rankComparison;
137
+ const durationComparison =
138
+ (left.windowMinutes ?? Number.POSITIVE_INFINITY) -
139
+ (right.windowMinutes ?? Number.POSITIVE_INFINITY);
140
+ if (durationComparison !== 0) return durationComparison;
141
+ return (left.groupId ?? "").localeCompare(right.groupId ?? "");
142
+ });
143
+ }
144
+
145
+ export function usagePercentRemaining(bucket: UsageBucket): number | undefined {
146
+ if (bucket.unit === "percent" && bucket.remaining !== undefined) {
147
+ return clampPercent(bucket.remaining);
148
+ }
149
+ if (!bucket.limit || bucket.remaining === undefined) return undefined;
150
+ return clampPercent((bucket.remaining / bucket.limit) * 100);
151
+ }
152
+
153
+ function usageWindowRank(bucket: UsageBucket): number {
154
+ const kind = usageWindowKind(bucket);
155
+ if (kind === "hourly" || kind === "rolling") return 0;
156
+ if (kind === "weekly") return 1;
157
+ if (kind === "monthly") return 2;
158
+ return 3;
159
+ }
160
+
161
+ function bucketsForCodexModel(
162
+ report: UsageReport,
163
+ model?: UsageModel,
164
+ ): UsageBucket[] {
165
+ const group = selectCodexGroup(report, model);
166
+ return report.buckets.filter(
167
+ (bucket) => (bucket.groupId ?? bucket.id) === group,
168
+ );
169
+ }
170
+
171
+ function selectCodexGroup(
172
+ report: UsageReport,
173
+ model?: UsageModel,
174
+ ): string | undefined {
175
+ const groups = [
176
+ ...new Set(report.buckets.map((bucket) => bucket.groupId ?? bucket.id)),
177
+ ];
178
+ if (model?.provider === "openai-codex") {
179
+ const keys = [model.id, model.name]
180
+ .map(normalizeKey)
181
+ .filter((value): value is string => Boolean(value));
182
+ const specificGroups = groups
183
+ .filter((group) => group !== "codex")
184
+ .sort((left, right) => right.length - left.length);
185
+ for (const group of specificGroups) {
186
+ const bucket = report.buckets.find(
187
+ (candidate) => (candidate.groupId ?? candidate.id) === group,
188
+ );
189
+ const candidates = [group, bucket?.groupLabel, ...(bucket?.modelKeys ?? [])]
190
+ .map(normalizeKey)
191
+ .filter((value): value is string => Boolean(value));
192
+ if (
193
+ candidates.some((candidate) => keys.some((key) => key.includes(candidate)))
194
+ ) {
195
+ return group;
196
+ }
197
+ }
198
+ }
199
+ return groups.includes("codex") ? "codex" : groups[0];
200
+ }
201
+
202
+ function normalizeKey(value: string | undefined): string | undefined {
203
+ return (
204
+ value
205
+ ?.toLowerCase()
206
+ .replace(/[^a-z0-9]+/gu, "-")
207
+ .replace(/^-+|-+$/gu, "") || undefined
208
+ );
209
+ }
210
+
211
+ function clampPercent(value: number): number {
212
+ return Math.min(100, Math.max(0, value));
213
+ }
package/src/types.ts ADDED
@@ -0,0 +1,83 @@
1
+ export type UsageSemanticsKind = "consumer-subscription";
2
+ export type UsageUnit = "percent" | "usd" | "count";
3
+
4
+ export interface UsageModel {
5
+ provider: string;
6
+ id: string;
7
+ name?: string;
8
+ baseUrl?: string;
9
+ }
10
+
11
+ export interface UsageSemantics {
12
+ kind: UsageSemanticsKind;
13
+ label: string;
14
+ }
15
+
16
+ export interface UsageBucket {
17
+ id: string;
18
+ label: string;
19
+ groupId?: string;
20
+ groupLabel?: string;
21
+ modelKeys?: string[];
22
+ used?: number;
23
+ remaining?: number;
24
+ limit?: number;
25
+ unit: UsageUnit;
26
+ period?: string;
27
+ windowMinutes?: number;
28
+ resetsAt?: number;
29
+ }
30
+
31
+ export interface UsageMetric {
32
+ id: string;
33
+ label: string;
34
+ value: number | string;
35
+ unit?: UsageUnit;
36
+ }
37
+
38
+ export interface UsageReport {
39
+ providerId: string;
40
+ providerName: string;
41
+ capturedAt: number;
42
+ source: string;
43
+ semantics: UsageSemantics;
44
+ buckets: UsageBucket[];
45
+ metrics: UsageMetric[];
46
+ notes?: string[];
47
+ }
48
+
49
+ export interface ResolvedUsageAuth {
50
+ actualProviderId: string;
51
+ apiKey?: string;
52
+ headers: Record<string, string>;
53
+ fingerprint: string;
54
+ secrets: string[];
55
+ model: UsageModel;
56
+ }
57
+
58
+ export interface UsageProviderAdapter {
59
+ id: string;
60
+ displayName: string;
61
+ providerIds: readonly string[];
62
+ semantics: UsageSemantics;
63
+ requiresOAuth?: boolean;
64
+ query(
65
+ auth: ResolvedUsageAuth,
66
+ signal: AbortSignal,
67
+ timeoutMs: number,
68
+ ): Promise<UsageReport>;
69
+ }
70
+
71
+ export type ProviderUsageState =
72
+ | {
73
+ providerId: string;
74
+ providerName: string;
75
+ status: "ready";
76
+ report: UsageReport;
77
+ }
78
+ | {
79
+ providerId: string;
80
+ providerName: string;
81
+ status: "unsupported" | "auth-unavailable" | "query-failed";
82
+ message: string;
83
+ };