@fenlyin/pi-subscription-usage 0.0.0-stage → 2.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/status.ts ADDED
@@ -0,0 +1,291 @@
1
+ import {
2
+ DEFAULT_USAGE_DISPLAY_MODE,
3
+ formatUsagePercent,
4
+ usagePercent,
5
+ usagePercentRemaining,
6
+ usagePercentUsed,
7
+ type UsageDisplayMode,
8
+ } from "./display.ts";
9
+ import type { UsageBucket, UsageModel, UsageReport } from "./types.ts";
10
+
11
+ export { usagePercentRemaining, usagePercentUsed } from "./display.ts";
12
+
13
+ export const USAGE_STATUS_EVENT = "subscription-usage/status/v1";
14
+
15
+ export type UsageStatusWindowKind =
16
+ | "hourly"
17
+ | "weekly"
18
+ | "monthly"
19
+ | "rolling"
20
+ | "quota";
21
+
22
+ export interface UsageStatusWindow {
23
+ kind: UsageStatusWindowKind;
24
+ label: string;
25
+ remainingPercent: number;
26
+ usedPercent: number;
27
+ displayPercent: number;
28
+ windowMinutes?: number;
29
+ resetsAt?: number;
30
+ /** Countdown to `resetsAt` at publish time, such as `2h13m`; absent once the reset has passed. */
31
+ resetCountdown?: string;
32
+ }
33
+
34
+ export type UsageStatusEvent =
35
+ | {
36
+ v: 1;
37
+ status: "ready";
38
+ providerId: string;
39
+ capturedAt: number;
40
+ displayMode: UsageDisplayMode;
41
+ windows: UsageStatusWindow[];
42
+ }
43
+ | {
44
+ v: 1;
45
+ status: "unavailable";
46
+ };
47
+
48
+ export function unavailableUsageStatusEvent(): UsageStatusEvent {
49
+ return { v: 1, status: "unavailable" };
50
+ }
51
+
52
+ export function buildUsageStatusEvent(
53
+ report: UsageReport,
54
+ model?: UsageModel,
55
+ displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
56
+ nowMs: number = Date.now(),
57
+ ): UsageStatusEvent {
58
+ const buckets = bucketsForModel(report, model);
59
+ const windows = sortUsageBuckets(buckets).flatMap((bucket) => {
60
+ const remainingPercent = usagePercentRemaining(bucket);
61
+ const usedPercent = usagePercentUsed(bucket);
62
+ const displayPercent = usagePercent(bucket, displayMode);
63
+ if (
64
+ remainingPercent === undefined ||
65
+ usedPercent === undefined ||
66
+ displayPercent === undefined
67
+ ) {
68
+ return [];
69
+ }
70
+ const resetCountdown =
71
+ bucket.resetsAt === undefined
72
+ ? undefined
73
+ : formatResetCountdown(bucket.resetsAt * 1_000 - nowMs);
74
+ return [
75
+ {
76
+ kind: usageWindowKind(bucket),
77
+ label: compactUsageWindowLabel(bucket),
78
+ remainingPercent,
79
+ usedPercent,
80
+ displayPercent,
81
+ ...(bucket.windowMinutes === undefined
82
+ ? {}
83
+ : { windowMinutes: bucket.windowMinutes }),
84
+ ...(bucket.resetsAt === undefined ? {} : { resetsAt: bucket.resetsAt }),
85
+ ...(resetCountdown === undefined ? {} : { resetCountdown }),
86
+ } satisfies UsageStatusWindow,
87
+ ];
88
+ });
89
+ return {
90
+ v: 1,
91
+ status: "ready",
92
+ providerId: report.providerId,
93
+ capturedAt: report.capturedAt,
94
+ displayMode,
95
+ windows,
96
+ };
97
+ }
98
+
99
+ /**
100
+ * Footer tone for a window, chosen by how much quota is left rather than by the
101
+ * percentage the footer happens to display. Rounded first so the color always
102
+ * agrees with the number next to it.
103
+ */
104
+ export function usageStatuslineTone(
105
+ remainingPercent: number,
106
+ ): "success" | "warning" | "error" {
107
+ const left = Math.round(remainingPercent);
108
+ if (left < 20) return "error";
109
+ if (left < 50) return "warning";
110
+ return "success";
111
+ }
112
+
113
+ /**
114
+ * Optional color hooks for the footer. Pi renders whatever `setStatus()` receives,
115
+ * so a caller holding a theme can colorize each segment; without hooks the line
116
+ * stays plain for tests, RPC mode, and non-TUI consumers.
117
+ */
118
+ export type UsageStatuslineStyle = {
119
+ /** Wraps a window label such as `5h`. */
120
+ label?: (text: string) => string;
121
+ /** Wraps the displayed percentage; `remainingPercent` is always what is left. */
122
+ percent?: (text: string, remainingPercent: number) => string;
123
+ /** Wraps `↻ 2h13m` as one unit. */
124
+ countdown?: (text: string) => string;
125
+ /** Wraps the ` · ` separator between windows. */
126
+ separator?: (text: string) => string;
127
+ };
128
+
129
+ /** Plain fallback for Pi's default footer. Rich rendering belongs to session-ui. */
130
+ export function formatUsageStatusline(
131
+ report: UsageReport,
132
+ model?: UsageModel,
133
+ displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
134
+ nowMs: number = Date.now(),
135
+ style?: UsageStatuslineStyle,
136
+ ): string | undefined {
137
+ const event = buildUsageStatusEvent(report, model, displayMode, nowMs);
138
+ if (event.status !== "ready" || event.windows.length === 0) return undefined;
139
+ const windows = event.windows.map((window) => {
140
+ const label = style?.label?.(window.label) ?? window.label;
141
+ const percentText = `${formatUsagePercent(window.displayPercent)}%`;
142
+ const percent = style?.percent
143
+ ? style.percent(percentText, window.remainingPercent)
144
+ : percentText;
145
+ const head = `${label} ${percent}`;
146
+ if (!window.resetCountdown) return head;
147
+ const countdown = `↻ ${window.resetCountdown}`;
148
+ return `${head} ${style?.countdown?.(countdown) ?? countdown}`;
149
+ });
150
+ if (windows.length === 1) return windows[0];
151
+ return windows.join(style?.separator?.(" · ") ?? " · ");
152
+ }
153
+
154
+ /** Compact two-unit countdown such as `3d4h`, `2h13m`, or `<1m`; past resets yield nothing. */
155
+ export function formatResetCountdown(remainingMs: number): string | undefined {
156
+ if (!Number.isFinite(remainingMs) || remainingMs <= 0) return undefined;
157
+ const totalMinutes = Math.floor(remainingMs / 60_000);
158
+ if (totalMinutes < 1) return "<1m";
159
+ const days = Math.floor(totalMinutes / 1_440);
160
+ const hours = Math.floor((totalMinutes % 1_440) / 60);
161
+ const minutes = totalMinutes % 60;
162
+ if (days > 0) return hours > 0 ? `${days}d${hours}h` : `${days}d`;
163
+ if (hours > 0) return minutes > 0 ? `${hours}h${minutes}m` : `${hours}h`;
164
+ return `${minutes}m`;
165
+ }
166
+
167
+ export function usageWindowLabel(bucket: UsageBucket): string {
168
+ const kind = usageWindowKind(bucket);
169
+ if (kind === "weekly") return "1w Window";
170
+ if (kind === "monthly") return "1m Window";
171
+ if (kind === "rolling") return "Rolling Window";
172
+ if (bucket.windowMinutes && bucket.windowMinutes > 0) {
173
+ if (bucket.windowMinutes % 60 === 0) {
174
+ return `${bucket.windowMinutes / 60}h Window`;
175
+ }
176
+ return `${Math.round(bucket.windowMinutes)}m Window`;
177
+ }
178
+ return "Quota";
179
+ }
180
+
181
+ export function compactUsageWindowLabel(bucket: UsageBucket): string {
182
+ const kind = usageWindowKind(bucket);
183
+ if (kind === "weekly") return "1w";
184
+ if (kind === "monthly") return "1m";
185
+ if (kind === "rolling") return "rolling";
186
+ if (bucket.windowMinutes && bucket.windowMinutes > 0) {
187
+ if (bucket.windowMinutes % 60 === 0) return `${bucket.windowMinutes / 60}h`;
188
+ return `${Math.round(bucket.windowMinutes)}m`;
189
+ }
190
+ return "quota";
191
+ }
192
+
193
+ export function usageWindowKind(bucket: UsageBucket): UsageStatusWindowKind {
194
+ const key =
195
+ `${bucket.id} ${bucket.label} ${bucket.period ?? ""}`.toLowerCase();
196
+ if (key.includes("month")) return "monthly";
197
+ if (key.includes("week")) return "weekly";
198
+ if (bucket.windowMinutes === 10_080) return "weekly";
199
+ if (
200
+ bucket.windowMinutes !== undefined &&
201
+ bucket.windowMinutes >= 28 * 24 * 60 &&
202
+ bucket.windowMinutes <= 31 * 24 * 60
203
+ ) {
204
+ return "monthly";
205
+ }
206
+ if (bucket.windowMinutes !== undefined && bucket.windowMinutes > 0) {
207
+ return "hourly";
208
+ }
209
+ if (key.includes("rolling")) return "rolling";
210
+ return "quota";
211
+ }
212
+
213
+ /** Canonical status order: hourly/rolling, weekly, monthly, then other quota. */
214
+ export function sortUsageBuckets(
215
+ buckets: readonly UsageBucket[],
216
+ ): UsageBucket[] {
217
+ return [...buckets].sort((left, right) => {
218
+ const rankComparison = usageWindowRank(left) - usageWindowRank(right);
219
+ if (rankComparison !== 0) return rankComparison;
220
+ const durationComparison =
221
+ (left.windowMinutes ?? Number.POSITIVE_INFINITY) -
222
+ (right.windowMinutes ?? Number.POSITIVE_INFINITY);
223
+ if (durationComparison !== 0) return durationComparison;
224
+ return (left.groupId ?? "").localeCompare(right.groupId ?? "");
225
+ });
226
+ }
227
+
228
+ function usageWindowRank(bucket: UsageBucket): number {
229
+ const kind = usageWindowKind(bucket);
230
+ if (kind === "hourly" || kind === "rolling") return 0;
231
+ if (kind === "weekly") return 1;
232
+ if (kind === "monthly") return 2;
233
+ return 3;
234
+ }
235
+
236
+ function bucketsForModel(
237
+ report: UsageReport,
238
+ model?: UsageModel,
239
+ ): UsageBucket[] {
240
+ const hasGroups = report.buckets.some((bucket) => bucket.groupId);
241
+ const hasModelGroups = report.buckets.some(
242
+ (bucket) => bucket.modelKeys && bucket.modelKeys.length > 0,
243
+ );
244
+ if (!hasGroups || (!report.defaultGroupId && !hasModelGroups)) {
245
+ return report.buckets;
246
+ }
247
+ const group = !hasModelGroups && report.defaultGroupId
248
+ ? report.defaultGroupId
249
+ : selectUsageGroup(report, model);
250
+ return report.buckets.filter(
251
+ (bucket) => (bucket.groupId ?? bucket.id) === group,
252
+ );
253
+ }
254
+
255
+ function selectUsageGroup(
256
+ report: UsageReport,
257
+ model?: UsageModel,
258
+ ): string | undefined {
259
+ const groups = [
260
+ ...new Set(report.buckets.map((bucket) => bucket.groupId ?? bucket.id)),
261
+ ];
262
+ const keys = [model?.id, model?.name]
263
+ .map(normalizeKey)
264
+ .filter((value): value is string => Boolean(value));
265
+ const specificGroups = groups
266
+ .filter((group) => group !== report.defaultGroupId)
267
+ .sort((left, right) => right.length - left.length);
268
+ for (const group of specificGroups) {
269
+ const bucket = report.buckets.find(
270
+ (candidate) => (candidate.groupId ?? candidate.id) === group,
271
+ );
272
+ const candidates = [group, bucket?.groupLabel, ...(bucket?.modelKeys ?? [])]
273
+ .map(normalizeKey)
274
+ .filter((value): value is string => Boolean(value));
275
+ if (
276
+ candidates.some((candidate) => keys.some((key) => key.includes(candidate)))
277
+ ) {
278
+ return group;
279
+ }
280
+ }
281
+ return groups.find((group) => group === report.defaultGroupId) ?? groups[0];
282
+ }
283
+
284
+ function normalizeKey(value: string | undefined): string | undefined {
285
+ return (
286
+ value
287
+ ?.toLowerCase()
288
+ .replace(/[^a-z0-9]+/gu, "-")
289
+ .replace(/^-+|-+$/gu, "") || undefined
290
+ );
291
+ }
package/src/types.ts ADDED
@@ -0,0 +1,90 @@
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
+ defaultGroupId?: string;
46
+ metrics: UsageMetric[];
47
+ notes?: string[];
48
+ }
49
+
50
+ export interface ResolvedUsageAuth {
51
+ actualProviderId: string;
52
+ /** Active OpenAI OAuth registration, matched against the ChatGPT app list. */
53
+ openaiClientId?: string;
54
+ /** Original usage identity, retained when reset auth adds account headers. */
55
+ usageFingerprint?: string;
56
+ apiKey?: string;
57
+ headers: Record<string, string>;
58
+ fingerprint: string;
59
+ secrets: string[];
60
+ model: UsageModel;
61
+ }
62
+
63
+ export interface UsageProviderAdapter {
64
+ id: string;
65
+ displayName: string;
66
+ providerIds: readonly string[];
67
+ officialOrigins: readonly string[];
68
+ semantics: UsageSemantics;
69
+ requiresOAuth?: boolean;
70
+ query(
71
+ auth: ResolvedUsageAuth,
72
+ signal: AbortSignal,
73
+ timeoutMs: number,
74
+ ): Promise<UsageReport>;
75
+ }
76
+
77
+ export type ProviderUsageState =
78
+ | {
79
+ providerId: string;
80
+ providerName: string;
81
+ status: "ready";
82
+ report: UsageReport;
83
+ }
84
+ | {
85
+ providerId: string;
86
+ providerName: string;
87
+ /** `pending`: an observed provider has not reported usage yet. */
88
+ status: "unsupported" | "auth-unavailable" | "query-failed" | "pending";
89
+ message: string;
90
+ };