@clothespin/pi-pippi 0.0.0-stage → 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/usage.ts ADDED
@@ -0,0 +1,959 @@
1
+ /**
2
+ * Provider allowance and balance, for the pet's "usage" row.
3
+ *
4
+ * The data belongs to another extension. This file speaks the process-local
5
+ * `pi.events` protocol documented in `usage-v1.md` — `usage:query:v1` for a
6
+ * report, `usage:changed:v1` for an invalidation hint — and deliberately imports
7
+ * nothing from the extension that answers: a session without it must behave
8
+ * exactly as it did before this row existed, which means no row. The channel
9
+ * names are extension-neutral on purpose, so this says "is there a usage
10
+ * service?" and never "are you the usage extension?".
11
+ *
12
+ * Two shapes reach the device, because the two ways of buying model time differ
13
+ * in kind and not just in units (see UsageInfo in protocol.ts):
14
+ *
15
+ * subscription an allowance with a ceiling and a window, drawn as a bar that
16
+ * is full straight after a reset and empties as it is spent;
17
+ * prepaid money, drawn as what is left and what has gone.
18
+ *
19
+ * Which is which comes from the report's `semantics.kind`, set by whoever reads
20
+ * the provider — an account's billing model is not something to infer from the
21
+ * shape of a number. But the data gets the final say on what can be drawn: a
22
+ * bar needs a denominator, and a report that only knows a balance cannot draw
23
+ * one however its semantics are labelled.
24
+ */
25
+
26
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
27
+
28
+ import {
29
+ MAX_MONEY_MINOR,
30
+ MAX_USAGE_METERS,
31
+ MAX_USAGE_TAG_BYTES,
32
+ type UsageInfo,
33
+ type UsageMeter,
34
+ } from "./protocol.ts";
35
+
36
+ const QUERY_CHANNEL = "usage:query:v1";
37
+ const CHANGED_CHANNEL = "usage:changed:v1";
38
+
39
+ /** The protocol gives a service 15s from accepting a request to settling it. */
40
+ const REFRESH_DEADLINE_MS = 15_000;
41
+ /**
42
+ * A cache-only query promises no network at all, so an answer that takes longer
43
+ * than a few seconds is a broken service rather than a slow provider.
44
+ */
45
+ const CACHE_DEADLINE_MS = 5_000;
46
+
47
+ /**
48
+ * Why a report is not coming. Mirrors the protocol's reasons plus the two
49
+ * outcomes the consumer invents locally (`no-service`, `protocol-error`).
50
+ */
51
+ export type UsageSkipReason =
52
+ | "no-service"
53
+ | "protocol-error"
54
+ | "not-ready"
55
+ | "no-model"
56
+ | "unsupported"
57
+ | "auth-unavailable"
58
+ | "selection-required"
59
+ | "cache-miss"
60
+ | "query-failed"
61
+ | "cancelled"
62
+ | "timeout"
63
+ | "stale-context";
64
+
65
+ export type UsageQueryResult = { ok: true; report: UsageReport } | { ok: false; reason: UsageSkipReason };
66
+
67
+ // ─────────────────────────── the report, as declared locally ───────────────────────────
68
+ // Structural, not imported: the protocol says a consumer declares these types
69
+ // itself, and a field added by a newer service must be ignored rather than
70
+ // break this file. `unknown` at the boundary, validated before use — the event
71
+ // bus is not a trust boundary, since every extension in the process shares it.
72
+
73
+ interface UsageBucket {
74
+ id: string;
75
+ label: string;
76
+ groupId?: string;
77
+ groupLabel?: string;
78
+ used?: number;
79
+ remaining?: number;
80
+ limit?: number;
81
+ unit: string;
82
+ period?: string;
83
+ windowMinutes?: number;
84
+ resetsAt?: number;
85
+ }
86
+
87
+ interface UsageMetric {
88
+ id: string;
89
+ label: string;
90
+ value: number | string;
91
+ unit?: string;
92
+ currency?: string;
93
+ }
94
+
95
+ export interface UsageReport {
96
+ providerId: string;
97
+ providerName: string;
98
+ capturedAt: number;
99
+ source: string;
100
+ semantics: { kind: string; label: string };
101
+ accountLabel?: string;
102
+ buckets: UsageBucket[];
103
+ metrics: UsageMetric[];
104
+ }
105
+
106
+ // ─────────────────────────────── normalisation ───────────────────────────────
107
+
108
+ /**
109
+ * The money units are a convention, not a measurement: a report's amounts are in
110
+ * major units (12.5 means $12.50) and the wire carries integer minor units,
111
+ * because the device has no reason to own floating point. A currency with zero
112
+ * decimal places therefore reads "1000.00" rather than "1000", which is a
113
+ * cosmetic price of keeping the firmware out of currency tables.
114
+ *
115
+ * The ceiling is the firmware's uint32 field, shared with the clamp in protocol.ts.
116
+ */
117
+ function minorUnits(amount: number): number {
118
+ return Math.min(MAX_MONEY_MINOR, Math.round(amount * 100));
119
+ }
120
+
121
+ function moneyUnit(unit: string | undefined): boolean {
122
+ return unit === "usd" || unit === "currency";
123
+ }
124
+
125
+ // ─────────────────────── money ids and metrics ───────────────────────
126
+ //
127
+ // Spelled out rather than matched by substring because the same style of id also
128
+ // names the opposite thing: `booster-monthly-limit` is a ceiling and `key-limit` is
129
+ // a spending cap, neither of which is a balance you can spend from. They are
130
+ // preference-ordered because a report can carry several and the panel has one row.
131
+
132
+ const BALANCE_IDS = [
133
+ "credit-balance",
134
+ "prepaid-balance",
135
+ "booster-balance",
136
+ "purchased-credits",
137
+ "free-credits",
138
+ "credits",
139
+ ];
140
+
141
+ const SPEND_IDS = ["lifetime-spend", "usage-total", "period-cost", "booster-monthly-used"];
142
+
143
+ /**
144
+ * The first of `ids` that holds a usable amount.
145
+ *
146
+ * A unit that says the number is not money means it is not money whatever the id was
147
+ * spelled as: a token-count `credits` metric is a quantity of tokens, and drawing it
148
+ * as a balance would be inventing a price for tokens on someone's behalf.
149
+ */
150
+ function metricValue(
151
+ report: UsageReport,
152
+ ids: string[],
153
+ ): { value: number; currency?: string } | undefined {
154
+ for (const id of ids) {
155
+ const metric = report.metrics.find((m) => m.id === id);
156
+ if (!metric || typeof metric.value !== "number" || !Number.isFinite(metric.value) || metric.value < 0) continue;
157
+ if (metric.unit === "count" || metric.unit === "percent") continue;
158
+ return { value: metric.value, currency: metric.currency };
159
+ }
160
+ return undefined;
161
+ }
162
+
163
+ /** A bucket carries no currency of its own; the report's metrics do. */
164
+ function currencyOf(bucket: UsageBucket): string | undefined {
165
+ return bucket.unit === "usd" ? "USD" : undefined;
166
+ }
167
+
168
+
169
+ /**
170
+ * One row per counter the provider reports, tightest first.
171
+ *
172
+ * A Claude subscription has a five-hour window, a seven-day window, and a second
173
+ * seven-day window scoped to one model family; a gateway has a monthly credit
174
+ * balance alongside a session spend. Reducing those to a single number would hide
175
+ * exactly the one that is about to stop the next request, which is the only reason
176
+ * to glance at a desk pet instead of the terminal.
177
+ *
178
+ * `semantics.kind` is read and not obeyed, on purpose: it states how an account is
179
+ * sold, while the buckets state what can honestly be drawn. A subscription whose
180
+ * provider reports nothing but money gets money rows; a key that happens to publish
181
+ * a percentage window gets a bar.
182
+ */
183
+ export function normaliseReport(
184
+ report: UsageReport,
185
+ lowAt?: () => number | undefined,
186
+ ): UsageInfo | undefined {
187
+ const meters = [...ceilingMeters(report), ...walletMeters(report)];
188
+ if (meters.length === 0) return undefined;
189
+ // Bars before money, and the emptiest bar first, so a panel with room for two
190
+ // shows the two most likely to be the reason the next request fails.
191
+ meters.sort((a, b) => (a.pct ?? Number.MAX_SAFE_INTEGER) - (b.pct ?? Number.MAX_SAFE_INTEGER));
192
+ const rows = labelUniquely(meters).slice(0, MAX_USAGE_METERS);
193
+ // The alarm threshold is stamped on here rather than taken from the report: it is
194
+ // this consumer's opinion about the desk, not the provider's about the account.
195
+ // Read at the moment of normalising, so changing it needs nothing reconfigured.
196
+ const low = lowAt?.();
197
+ return low === undefined ? { meters: rows } : { meters: rows, low };
198
+ }
199
+
200
+ /**
201
+ * A percentage of what is left, in the only range the bar can draw. Over-quota is
202
+ * empty rather than negative: a provider that reports 140% used has not run out of
203
+ * allowance in a way a bar can show past its right edge, and the number a person
204
+ * needs from the panel is "none", not "-40".
205
+ *//**
206
+ * Whether two readings would draw the same rows. Field by field rather than by
207
+ * serialisation, because these are four small numbers per row and an object that
208
+ * differs only in key order is the same reading.
209
+ */
210
+ function sameUsage(a: UsageInfo | undefined, b: UsageInfo | undefined): boolean {
211
+ if (a === b) return true;
212
+ if (!a || !b || a.low !== b.low || a.meters.length !== b.meters.length) return false;
213
+ return a.meters.every((meter, i) => {
214
+ const other = b.meters[i];
215
+ return (
216
+ meter.tag === other.tag &&
217
+ meter.pct === other.pct &&
218
+ meter.left === other.left &&
219
+ meter.used === other.used &&
220
+ meter.cur === other.cur
221
+ );
222
+ });
223
+ }
224
+
225
+ /**
226
+ * A stand-in report, shaped exactly like the `ready` payload of `usage:query:v1`.
227
+ *
228
+ * Two situations this exists for are situations the code cannot reach on its own:
229
+ * a model served by a local backend has no subscription and no balance to draw
230
+ * down, and the two counters worth laying out side by side -- a five hour window
231
+ * inside a weekly one -- take five hours and a week of real use to produce. So the
232
+ * bridge can be told to answer its own question, and the report it gets back has
233
+ * to be a report: it goes through `normaliseReport` like any other, which is the
234
+ * point. The tags, the order, the rounding and the clamps it exercises are the
235
+ * ones that would have to be right for a real provider, because they are the same
236
+ * code. What it cannot show is whether a provider actually reports these numbers.
237
+ *
238
+ * `5h=83` a window with 83% left, tagged from its own id
239
+ * `7d\*=21` a model-scoped window; the `*` is the scope marker a real
240
+ * id carries, so it is accepted here and reaches the panel
241
+ * `$bal=12.50` a wallet with $12.50 left, in major units like the report's
242
+ *
243
+ * A value that is not a number is a typo in a setting nobody else will ever look
244
+ * at, so the whole spec is rejected rather than quietly drawing the parts that
245
+ * parsed.
246
+ */
247
+ export function usageReportSpec(spec: string, capturedAt = Date.now()): UsageReport | undefined {
248
+ const buckets: UsageBucket[] = [];
249
+ for (const part of spec.split(/[,;]+/)) {
250
+ const match = /^\s*(\$?[^=\s]+)\s*=\s*(\S*)\s*$/.exec(part);
251
+ if (!match) return undefined;
252
+ const money = match[1].startsWith("$");
253
+ const id = money ? match[1].slice(1) : match[1];
254
+ // An explicit numeric literal, because `Number("")` is zero and `5h=` would
255
+ // otherwise be drawn as an empty bar rather than rejected as the typo it is.
256
+ const text = match[2].replace(/[$,]/g, "");
257
+ if (!id || !/^\d+(?:\.\d+)?$/.test(text)) return undefined;
258
+ const value = Number(text);
259
+ if (!Number.isFinite(value)) return undefined;
260
+ buckets.push(
261
+ money
262
+ ? { id, label: id, unit: "usd", remaining: value }
263
+ : // A bucket is a window because it has a ceiling, and the normaliser reads
264
+ // a percentage window as "how much is left". Stating it as limit 100 keeps
265
+ // this a report rather than a set of conclusions about it.
266
+ { id, label: id, unit: "percent", limit: 100, remaining: value },
267
+ );
268
+ }
269
+ if (buckets.length === 0) return undefined;
270
+ return {
271
+ providerId: "spec",
272
+ providerName: "command line",
273
+ capturedAt,
274
+ source: "PI_PIPPI_USAGE_SPEC",
275
+ semantics: { kind: "consumer-subscription", label: "specified" },
276
+ buckets,
277
+ metrics: [],
278
+ };
279
+ }
280
+
281
+ function pctLeft(pct: number): number {
282
+ return Math.max(0, Math.min(100, Math.round(pct)));
283
+ }
284
+
285
+ /** Meters that have a ceiling, and so can be drawn as a bar that drains. */
286
+ function ceilingMeters(report: UsageReport): UsageMeter[] {
287
+ const out: UsageMeter[] = [];
288
+ for (const bucket of report.buckets) {
289
+ const pct = bucketPct(bucket);
290
+ if (pct !== undefined) out.push({ tag: windowTag(bucket), pct: pctLeft(pct) });
291
+ }
292
+ for (const group of metricGroups(report)) {
293
+ if (group.limit === undefined || group.limit <= 0) continue;
294
+ const pct =
295
+ group.remaining !== undefined
296
+ ? (group.remaining / group.limit) * 100
297
+ : group.used !== undefined
298
+ ? ((group.limit - group.used) / group.limit) * 100
299
+ : undefined;
300
+ if (pct !== undefined) out.push({ tag: groupTag(group), pct: pctLeft(pct) });
301
+ }
302
+ return out;
303
+ }
304
+
305
+ /**
306
+ * Money with no ceiling: what is left of a wallet, and what has gone out of it.
307
+ *
308
+ * Either half may be missing on its own, and that is a real state rather than a
309
+ * partial failure — an API key with no spending cap reports a spend and nothing
310
+ * else. A bucket is a wallet only when it has no ceiling, because the same bucket
311
+ * with a ceiling is a window, and drawing it twice would be reporting one number as
312
+ * two facts.
313
+ */
314
+ function walletMeters(report: UsageReport): UsageMeter[] {
315
+ const bucket = report.buckets.find(
316
+ (b) =>
317
+ moneyUnit(b.unit) &&
318
+ !(typeof b.limit === "number" && b.limit > 0) &&
319
+ ((typeof b.remaining === "number" && b.remaining >= 0) || (typeof b.used === "number" && b.used >= 0)),
320
+ );
321
+ const balance = bucket
322
+ ? { value: bucket.remaining, currency: currencyOf(bucket) }
323
+ : metricValue(report, BALANCE_IDS);
324
+ const spend =
325
+ (!bucket && metricValue(report, SPEND_IDS)) ||
326
+ (bucket && typeof bucket.used === "number" && bucket.used >= 0 ? { value: bucket.used } : undefined) ||
327
+ metricValue(report, ["usage-monthly", "usage-weekly", "usage-daily"]);
328
+
329
+ if (balance?.value === undefined && spend?.value === undefined) return [];
330
+ // A wallet that is only a spend is labelled for what it is, because "bal 0.00"
331
+ // under a key that never had a balance would read as an exhausted account.
332
+ const tag = balance?.value !== undefined ? "bal" : "spend";
333
+ const meter: UsageMeter = { tag };
334
+ if (balance?.value !== undefined) meter.left = minorUnits(balance.value);
335
+ if (spend?.value !== undefined) meter.used = minorUnits(spend.value);
336
+ const currency = balance?.currency ?? spend?.currency;
337
+ if (currency) meter.cur = currency;
338
+ return [meter];
339
+ }
340
+
341
+ /** Percentage left, for a bucket that states a ceiling; undefined for a wallet. */
342
+ function bucketPct(bucket: UsageBucket): number | undefined {
343
+ if (bucket.unit === "percent") {
344
+ // A percent bucket states usage against a ceiling of 100, so `used` is the only
345
+ // figure in it. `remaining` is honoured too, for a provider that reports the
346
+ // other half instead.
347
+ if (typeof bucket.remaining === "number") return bucket.remaining;
348
+ if (typeof bucket.used === "number") return 100 - bucket.used;
349
+ return undefined;
350
+ }
351
+ if (!moneyUnit(bucket.unit)) return undefined;
352
+ // The protocol is explicit that an absent limit is unknown and not unlimited, so
353
+ // a bare spend figure says nothing about how much room is left.
354
+ if (!Number.isFinite(bucket.limit ?? Number.NaN) || (bucket.limit ?? 0) <= 0) return undefined;
355
+ const limit = bucket.limit as number;
356
+ if (typeof bucket.remaining === "number") return (bucket.remaining / limit) * 100;
357
+ if (typeof bucket.used === "number") return ((limit - bucket.used) / limit) * 100;
358
+ return undefined;
359
+ }
360
+
361
+ interface MetricGroup {
362
+ key: string;
363
+ label?: string;
364
+ limit?: number;
365
+ remaining?: number;
366
+ used?: number;
367
+ }
368
+
369
+ /**
370
+ * Quota published as separate numbers instead of a bucket — `<thing>-limit` plus
371
+ * `<thing>-used` and/or `<thing>-remaining`, the shape Anthropic uses for its
372
+ * extra-usage credits. Grouped by the id in front of the suffix rather than matched
373
+ * exactly, because providers name these after their own APIs and a fixed list would
374
+ be a change here for every new one.
375
+ */
376
+ function metricGroups(report: UsageReport): MetricGroup[] {
377
+ const groups = new Map<string, MetricGroup>();
378
+ for (const metric of report.metrics) {
379
+ if (typeof metric.value !== "number" || !Number.isFinite(metric.value) || metric.value < 0) continue;
380
+ const suffix = metric.id.endsWith("-limit")
381
+ ? "limit"
382
+ : metric.id.endsWith("-used")
383
+ ? "used"
384
+ : metric.id.endsWith("-remaining")
385
+ ? "remaining"
386
+ : undefined;
387
+ if (!suffix) continue;
388
+ const key = metric.id.slice(0, -suffix.length - 1);
389
+ const group = groups.get(key) ?? { key };
390
+ group[suffix] = metric.value;
391
+ group.label ??= metric.label;
392
+ groups.set(key, group);
393
+ }
394
+ return [...groups.values()];
395
+ }
396
+
397
+ const WINDOW_WORDS: Array<[RegExp, number]> = [
398
+ [/session/i, 300],
399
+ [/hour/i, 60],
400
+ [/day/i, 1440],
401
+ [/week/i, 10080],
402
+ [/month/i, 43200],
403
+ ];
404
+
405
+ /**
406
+ * A tag short enough to sit beside a ten-cell bar: "5h", "7d", "30d", and "7d*" for
407
+ * a window scoped to one model family rather than the whole account.
408
+ *
409
+ * Derived from the window's length rather than the provider's wording, because the
410
+ * wording is English prose ("7-day week (scoped)") and the length is what the
411
+ * protocol puts in `windowMinutes` for exactly this purpose. When neither a length
412
+ * nor a recognisable period is present, a reset time that lands near a known window
413
+ * is used, and failing that the bucket's own id, shortened.
414
+ */
415
+ function windowTag(bucket: UsageBucket): string {
416
+ const scoped = /scoped/.test(`${bucket.id} ${bucket.groupId ?? ""} ${bucket.groupLabel ?? ""}`);
417
+ const minutes =
418
+ bucket.windowMinutes ??
419
+ minutesFromWords(bucket.period) ??
420
+ minutesFromWords(bucket.label) ??
421
+ minutesFromReset(bucket);
422
+ const base = minutes === undefined ? shortId(bucket.id) : humanWindow(minutes);
423
+ const tag = scoped ? `${base}*` : base;
424
+ return tag.slice(0, MAX_USAGE_TAG_BYTES);
425
+ }
426
+
427
+ function humanWindow(minutes: number): string {
428
+ const round = (value: number) => String(Math.max(1, Math.round(value)));
429
+ if (minutes < 60) return `${round(minutes)}m`;
430
+ if (minutes < 1440) return `${round(minutes / 60)}h`;
431
+ // Days up to a month, and no weeks unit at all: the windows in the wild are sold
432
+ // as "7-day week", and `7d` is what reads off a desk across the room.
433
+ if (minutes < 43200) return `${round(minutes / 1440)}d`;
434
+ return `${round(minutes / 43200)}mo`;
435
+ }
436
+
437
+ function minutesFromWords(words: string | undefined): number | undefined {
438
+ if (!words) return undefined;
439
+ const explicit = words.match(/(\d+(?:\.\d+)?)\s*([hdwm]|hour|day|week|month)s?\b/i);
440
+ if (explicit) {
441
+ const value = Number(explicit[1]);
442
+ const unit = explicit[2].toLowerCase();
443
+ const per = unit.startsWith("h") ? 60 : unit === "d" ? 1440 : unit === "w" ? 10080 : unit === "m" ? 43200 : 1;
444
+ return value * per;
445
+ }
446
+ for (const [pattern, minutes] of WINDOW_WORDS) if (pattern.test(words)) return minutes;
447
+ return undefined;
448
+ }
449
+
450
+ /**
451
+ * A reset time is a weak signal, so it is only trusted when it is close to a window
452
+ * someone would actually have built: an hour from now is an hour window, and four
453
+ * days from now is nobody's window and stays unlabelled.
454
+ */
455
+ function minutesFromReset(bucket: UsageBucket): number | undefined {
456
+ if (typeof bucket.resetsAt !== "number" || !Number.isFinite(bucket.resetsAt)) return undefined;
457
+ const ahead = bucket.resetsAt - Date.now();
458
+ if (ahead <= 0) return undefined;
459
+ const minutes = ahead / 60000;
460
+ for (const known of [60, 300, 1440, 10080, 43200]) {
461
+ if (Math.abs(minutes - known) / known < 0.15) return known;
462
+ }
463
+ return undefined;
464
+ }
465
+
466
+ function groupTag(group: MetricGroup): string {
467
+ const fromLabel = minutesFromWords(group.label);
468
+ if (fromLabel !== undefined) return humanWindow(fromLabel);
469
+ const fromKey = minutesFromWords(group.key.replace(/[-_]/g, " "));
470
+ if (fromKey !== undefined) return fromKey;
471
+ // "cap" rather than the id: a quota with no period in its name is still a ceiling,
472
+ // and the id of a provider's internal counter is not information at 6 pixels tall.
473
+ return shortId(group.key) ?? "cap";
474
+ }
475
+
476
+ /** Two meters cannot be drawn under the same label, however they got there. */
477
+ function labelUniquely(meters: UsageMeter[]): UsageMeter[] {
478
+ const seen = new Map<string, number>();
479
+ for (const meter of meters) {
480
+ const base = meter.tag;
481
+ const times = seen.get(base) ?? 0;
482
+ seen.set(base, times + 1);
483
+ if (times > 0) {
484
+ const suffix = String(times + 1);
485
+ meter.tag = `${base.slice(0, Math.max(1, MAX_USAGE_TAG_BYTES - suffix.length))}${suffix}`;
486
+ }
487
+ }
488
+ return meters;
489
+ }
490
+
491
+ function shortId(id: string): string {
492
+ const cleaned = id.replace(/[^A-Za-z0-9]/g, "").toLowerCase();
493
+ return cleaned.length > 0 ? cleaned.slice(0, MAX_USAGE_TAG_BYTES) : "cap";
494
+ }
495
+
496
+ function isRecord(value: unknown): value is Record<string, unknown> {
497
+ return typeof value === "object" && value !== null && !Array.isArray(value);
498
+ }
499
+
500
+ function num(value: unknown): number | undefined {
501
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
502
+ }
503
+
504
+ /**
505
+ * Structural validation of a query result. Anything unexpected about the shape
506
+ * is a protocol error, and a protocol error is not worth a row: the device shows
507
+ * no usage rather than a number assembled from a report whose meaning changed.
508
+ */
509
+ export function parseQueryResult(raw: unknown): UsageQueryResult {
510
+ if (!isRecord(raw)) return { ok: false, reason: "protocol-error" };
511
+ if (raw.status === "unavailable") {
512
+ return { ok: false, reason: knownReason(raw.reason) };
513
+ }
514
+ if (raw.status !== "ready") return { ok: false, reason: "protocol-error" };
515
+ if (typeof raw.providerId !== "string") return { ok: false, reason: "protocol-error" };
516
+ if (num(raw.expiresAt) === undefined) return { ok: false, reason: "protocol-error" };
517
+
518
+ const report = raw.report;
519
+ if (!isRecord(report)) return { ok: false, reason: "protocol-error" };
520
+ if (report.providerId !== raw.providerId) return { ok: false, reason: "protocol-error" };
521
+ if (!isRecord(report.semantics) || typeof report.semantics.kind !== "string") {
522
+ return { ok: false, reason: "protocol-error" };
523
+ }
524
+ if (!Array.isArray(report.buckets) || !Array.isArray(report.metrics)) {
525
+ return { ok: false, reason: "protocol-error" };
526
+ }
527
+ const buckets: UsageBucket[] = [];
528
+ for (const bucket of report.buckets) {
529
+ if (!isRecord(bucket) || typeof bucket.id !== "string" || typeof bucket.unit !== "string") continue;
530
+ buckets.push({
531
+ id: bucket.id,
532
+ label: typeof bucket.label === "string" ? bucket.label : bucket.id,
533
+ unit: bucket.unit,
534
+ used: num(bucket.used),
535
+ remaining: num(bucket.remaining),
536
+ limit: num(bucket.limit),
537
+ period: typeof bucket.period === "string" ? bucket.period : undefined,
538
+ windowMinutes: num(bucket.windowMinutes),
539
+ // The API publishes reset times in milliseconds; the internal field is
540
+ // seconds. Only the documented millisecond form is understood here, and a
541
+ // second-denominated value would be a fifth of the way to 1971 — so a
542
+ // plausible-looking number is checked for, not assumed.
543
+ resetsAt: num(bucket.resetsAt),
544
+ });
545
+ }
546
+ const metrics: UsageMetric[] = [];
547
+ for (const metric of report.metrics) {
548
+ if (!isRecord(metric) || typeof metric.id !== "string") continue;
549
+ if (typeof metric.value !== "number" && typeof metric.value !== "string") continue;
550
+ metrics.push({
551
+ id: metric.id,
552
+ label: typeof metric.label === "string" ? metric.label : metric.id,
553
+ value: metric.value,
554
+ unit: typeof metric.unit === "string" ? metric.unit : undefined,
555
+ currency:
556
+ typeof metric.currency === "string" && /^[A-Z]{3}$/.test(metric.currency) ? metric.currency : undefined,
557
+ });
558
+ }
559
+ return {
560
+ ok: true,
561
+ report: {
562
+ providerId: raw.providerId,
563
+ providerName: typeof report.providerName === "string" ? report.providerName : raw.providerId,
564
+ capturedAt: num(report.capturedAt) ?? 0,
565
+ source: typeof report.source === "string" ? report.source : "",
566
+ semantics: { kind: report.semantics.kind, label: report.semantics.label ?? "" },
567
+ accountLabel: typeof report.accountLabel === "string" ? report.accountLabel : undefined,
568
+ buckets,
569
+ metrics,
570
+ },
571
+ };
572
+ }
573
+
574
+ const KNOWN_REASONS = new Set<UsageSkipReason>([
575
+ "not-ready",
576
+ "no-model",
577
+ "unsupported",
578
+ "auth-unavailable",
579
+ "selection-required",
580
+ "cache-miss",
581
+ "query-failed",
582
+ "cancelled",
583
+ "timeout",
584
+ "stale-context",
585
+ ]);
586
+
587
+ function knownReason(value: unknown): UsageSkipReason {
588
+ return typeof value === "string" && KNOWN_REASONS.has(value as UsageSkipReason)
589
+ ? (value as UsageSkipReason)
590
+ : "protocol-error";
591
+ }
592
+
593
+ // ─────────────────────────────── the service ───────────────────────────────
594
+
595
+ export interface UsageServiceOptions {
596
+ /** How often to ask a provider, in milliseconds. 0 turns the row off. */
597
+ intervalMs: number;
598
+ /** The session to read the model from; undefined until session_start. */
599
+ context: () => ExtensionContext | undefined;
600
+ /**
601
+ * Whether anyone could be looking. A provider request on a timer for a pet
602
+ * that is not connected is traffic for no one, so this gates every query.
603
+ */
604
+ wanted: () => boolean;
605
+ /**
606
+ * The percentage below which a bar means "about to run out" and the device blinks
607
+ * it. A function rather than a number so it is read whenever a report lands, and
608
+ * optional because absent is the default the device already assumes.
609
+ */
610
+ usageLow?: () => number | undefined;
611
+ /**
612
+ * A provider that always answers this instead of being asked. See
613
+ * `usageReportSpec` for what it is for and what it cannot show; note that it
614
+ * bypasses the event bus entirely, so nothing about the query -- its deadline,
615
+ * its failure handling, the shape of a real answer -- is exercised by it.
616
+ */
617
+ report?: () => UsageReport | undefined;
618
+ /** A report was accepted or the row cleared; the bridge pushes a snapshot. */
619
+ onChange: () => void;
620
+ log: (message: string) => void;
621
+ }
622
+
623
+ /**
624
+ * Asks the usage service on a timer and holds the last accepted row.
625
+ *
626
+ * Cadence is the whole design. A refresh is a real request to a provider, and
627
+ * quota windows move on the order of minutes while the pet redraws ten times a
628
+ * second, so polling in step with the screen would be absurd. Five minutes is the
629
+ * default for want of a better number: shorter than a session's attention span,
630
+ * longer than most quota windows take to change enough to matter.
631
+ *
632
+ * Notifications are handled the way the protocol insists they be handled: a
633
+ * `changed` hint earns a cache-only query and never a refresh, because a consumer
634
+ * that refreshed on every hint would be the second half of a loop.
635
+ */
636
+ export class UsageService {
637
+ private readonly events: Pick<EventBusLike, "emit" | "on">;
638
+ private readonly opts: UsageServiceOptions;
639
+ private info: UsageInfo | undefined;
640
+ private providerId: string | undefined;
641
+ private failures = 0;
642
+ private inFlight: AbortController | undefined;
643
+ private hintPending = false;
644
+ private timer: ReturnType<typeof setTimeout> | undefined;
645
+ private unsubscribe: (() => void) | undefined;
646
+ private running = false;
647
+ private generation = 0;
648
+ /** A provider that says it has no report for this model stays quiet until the model changes. */
649
+ private dormantFor: string | undefined;
650
+ private readonly now: () => number;
651
+
652
+ // Plain fields rather than constructor parameter properties: pi runs this file
653
+ // through Node's type-stripping loader, which rejects the shorthand outright.
654
+ constructor(events: Pick<EventBusLike, "emit" | "on">, opts: UsageServiceOptions) {
655
+ this.events = events;
656
+ this.opts = opts;
657
+ }
658
+
659
+ get current(): UsageInfo | undefined {
660
+ return this.info;
661
+ }
662
+
663
+ /** What the rows are showing, for /pippi status. */
664
+ describe(): string {
665
+ const info = this.info;
666
+ if (!info || info.meters.length === 0) return "no usage report";
667
+ const money = (value: number | undefined, cur?: string) =>
668
+ value === undefined ? "?" : `${(value / 100).toFixed(2)}${cur ? ` ${cur}` : ""}`;
669
+ const parts = info.meters.map((meter) => {
670
+ if (meter.pct !== undefined) return `${meter.tag} ${meter.pct}% left`;
671
+ const halves = [
672
+ meter.left !== undefined ? `${money(meter.left, meter.cur)} left` : undefined,
673
+ meter.used !== undefined ? `${money(meter.used, meter.cur)} used` : undefined,
674
+ ].filter(Boolean);
675
+ return `${meter.tag} ${halves.join(", ") || "?"}`;
676
+ });
677
+ return `${this.providerId ?? "?"}: ${parts.join(" · ")}`;
678
+ }
679
+
680
+ start(): void {
681
+ if (this.running || this.opts.intervalMs <= 0) return;
682
+ this.running = true;
683
+ // Subscribe before the first query: a notification published between the two
684
+ // would otherwise be lost, and the protocol offers no replay.
685
+ this.unsubscribe = this.events.on(CHANGED_CHANNEL, (data) => this.onChanged(data));
686
+ this.schedule(0);
687
+ }
688
+
689
+ async stop(): Promise<void> {
690
+ this.running = false;
691
+ this.unsubscribe?.();
692
+ this.unsubscribe = undefined;
693
+ if (this.timer) clearTimeout(this.timer);
694
+ this.timer = undefined;
695
+ this.inFlight?.abort();
696
+ this.inFlight = undefined;
697
+ this.info = undefined;
698
+ this.generation++;
699
+ }
700
+
701
+ /** Call when the selected model changes: a provider that declined may accept now. */
702
+ modelChanged(): void {
703
+ if (this.dormantFor === undefined) return;
704
+ this.dormantFor = undefined;
705
+ this.failures = 0;
706
+ if (this.running) this.schedule(0);
707
+ }
708
+
709
+ private schedule(delayMs: number): void {
710
+ if (!this.running || this.timer) return;
711
+ this.timer = setTimeout(() => {
712
+ this.timer = undefined;
713
+ void this.poll();
714
+ }, delayMs);
715
+ this.timer.unref?.();
716
+ }
717
+
718
+ /**
719
+ * Normalise a report, remember it, and tell the bridge to push a snapshot -- but
720
+ * only when the panel would show something different. A row that froze at
721
+ * yesterday's value would be worse than no row, so a report that normalises to
722
+ * nothing clears what was there instead of leaving it up.
723
+ *
724
+ * Shared by the provider's own answer and the stand-in, which is the reason it is
725
+ * a method: one path through the clamps, so the stand-in cannot pass a shape the
726
+ * real thing would have failed.
727
+ */
728
+ private publish(report: UsageReport): void {
729
+ const info = normaliseReport(report, this.opts.usageLow);
730
+ this.failures = 0;
731
+ this.dormantFor = undefined;
732
+ this.providerId = report.providerId;
733
+ // Only a change is worth a snapshot. On the scheduled path this is a five
734
+ // minute cadence against a panel that redraws ten times a second, so it matters
735
+ // little; on the specified path, where the same report is handed back every
736
+ // poll, marking the display dirty each time would be the whole behaviour.
737
+ if (sameUsage(this.info, info)) return;
738
+ this.info = info;
739
+ this.opts.onChange();
740
+ }
741
+
742
+ /**
743
+ * One refresh on the timer. It is a refresh rather than a cache read because a
744
+ * cache read is documented to answer `cache-miss` for every supported provider
745
+ * today: asking for one would be a poll that can never return anything. The
746
+ * service keeps its own request limits and failure backoff, so the cadence here
747
+ * is a courtesy on top of theirs.
748
+ */
749
+ private async poll(): Promise<void> {
750
+ if (!this.running || this.inFlight) return;
751
+ const forced = this.opts.report?.();
752
+ if (forced) {
753
+ this.providerId = forced.providerId;
754
+ this.publish(forced);
755
+ this.schedule(this.opts.intervalMs);
756
+ return;
757
+ }
758
+ const ctx = this.opts.context();
759
+ if (!ctx || !this.opts.wanted()) {
760
+ // Nobody to show it to. Re-check on the normal cadence rather than spin.
761
+ this.schedule(this.opts.intervalMs);
762
+ return;
763
+ }
764
+ const modelKey = modelIdentity(ctx);
765
+ if (this.dormantFor === modelKey) {
766
+ this.schedule(this.opts.intervalMs);
767
+ return;
768
+ }
769
+ const generation = this.generation;
770
+ const controller = new AbortController();
771
+ this.inFlight = controller;
772
+ const result = await queryUsage(this.events, ctx, {
773
+ refresh: true,
774
+ signal: controller.signal,
775
+ });
776
+ // Session, model, or stop happened while the provider was thinking.
777
+ if (generation !== this.generation || this.opts.context() !== ctx || modelIdentity(ctx) !== modelKey) return;
778
+ if (this.inFlight === controller) this.inFlight = undefined;
779
+
780
+ if (result.ok) {
781
+ this.publish(result.report);
782
+ this.schedule(this.opts.intervalMs);
783
+ return;
784
+ }
785
+
786
+ // A provider with nothing to report is not an error to retry: it is the
787
+ // answer, and the same model will keep giving it. Model change wakes up.
788
+ if (result.reason === "unsupported" || result.reason === "no-model") {
789
+ this.dormantFor = modelKey;
790
+ this.clearIfShown();
791
+ this.schedule(this.opts.intervalMs);
792
+ return;
793
+ }
794
+ // No service at all means the extension is not installed. Say so once and
795
+ // stop: this is not a condition that resolves itself mid-session.
796
+ if (result.reason === "no-service") {
797
+ this.running = false;
798
+ if (this.timer) clearTimeout(this.timer);
799
+ this.timer = undefined;
800
+ this.clearIfShown();
801
+ this.opts.log("no usage service in this session; the usage row stays off");
802
+ return;
803
+ }
804
+ this.failures++;
805
+ // Three misses and the row is not trustworthy any more, so it goes: a quota
806
+ // bar frozen at yesterday's value is worse than no bar.
807
+ if (this.failures >= 3) this.clearIfShown();
808
+ this.schedule(this.opts.intervalMs);
809
+ }
810
+
811
+ private clearIfShown(): void {
812
+ if (this.info) {
813
+ this.info = undefined;
814
+ this.opts.onChange();
815
+ }
816
+ }
817
+
818
+ private onChanged(data: unknown): void {
819
+ if (!this.running || !isRecord(data)) return;
820
+ const ctx = this.opts.context();
821
+ if (!ctx) return;
822
+ // Filter by session, as required: another window's provider changing must
823
+ // not disturb this row.
824
+ if (typeof data.sessionId === "string" && data.sessionId !== sessionId(ctx)) return;
825
+ if (data.reason !== "updated") return; // `invalidated` and `query-failed` earn nothing.
826
+ // Cache-only. Today every supported provider answers this with a miss, and
827
+ // that is fine — the next scheduled refresh is what actually updates the row.
828
+ // Kept separate from the scheduled request's own in-flight marker: the two
829
+ // have nothing to say to each other, and conflating them would let a hint
830
+ // suppress a refresh or the other way round.
831
+ if (this.inFlight || this.hintPending) return;
832
+ this.hintPending = true;
833
+ const controller = new AbortController();
834
+ void queryUsage(this.events, ctx, { refresh: false, signal: controller.signal }).then(
835
+ (result) => {
836
+ this.hintPending = false;
837
+ if (!result.ok || !this.running) return;
838
+ const info = normaliseReport(result.report, this.opts.usageLow);
839
+ if (info) {
840
+ this.info = info;
841
+ this.providerId = result.report.providerId;
842
+ this.opts.onChange();
843
+ }
844
+ },
845
+ () => {
846
+ this.hintPending = false;
847
+ },
848
+ );
849
+ }
850
+ }
851
+
852
+ interface EventBusLike {
853
+ emit(channel: string, data: unknown): void;
854
+ on(channel: string, handler: (data: unknown) => void): () => void;
855
+ }
856
+
857
+ // ─────────────────────────────── the transport ───────────────────────────────
858
+
859
+ /**
860
+ * One `usage:query:v1` request, following the protocol's offer rules exactly:
861
+ * `emit()` returns void, so the service hands back a promise synchronously
862
+ * through `respond()` and the first offer during that dispatch is the only one
863
+ * that counts. A late or duplicate offer is observed (so a rejection cannot
864
+ * become an unhandled one) and then discarded.
865
+ */
866
+ export function queryUsage(
867
+ events: Pick<EventBusLike, "emit">,
868
+ ctx: ExtensionContext,
869
+ options: { refresh: boolean; signal: AbortSignal; providerId?: string },
870
+ ): Promise<UsageQueryResult> {
871
+ if (options.signal.aborted) return Promise.resolve({ ok: false, reason: "cancelled" });
872
+ const session = ctx.sessionManager;
873
+ const sessionIdValue = sessionId(ctx);
874
+ const model = modelIdentity(ctx);
875
+
876
+ return new Promise((resolve) => {
877
+ const controller = new AbortController();
878
+ let open = true;
879
+ let offered = false;
880
+ let done = false;
881
+ let settled = false;
882
+ const deadline = setTimeout(
883
+ () => finish({ ok: false, reason: "timeout" }),
884
+ options.refresh ? REFRESH_DEADLINE_MS : CACHE_DEADLINE_MS,
885
+ );
886
+ const finish = (result: UsageQueryResult) => {
887
+ if (settled) return;
888
+ settled = true;
889
+ done = true;
890
+ open = false;
891
+ clearTimeout(deadline);
892
+ options.signal.removeEventListener("abort", cancel);
893
+ controller.abort();
894
+ resolve(result);
895
+ };
896
+ const cancel = () => finish({ ok: false, reason: "cancelled" });
897
+ options.signal.addEventListener("abort", cancel, { once: true });
898
+
899
+ try {
900
+ events.emit(QUERY_CHANNEL, {
901
+ session,
902
+ sessionId: sessionIdValue,
903
+ refresh: options.refresh,
904
+ ...(options.providerId ? { providerId: options.providerId } : {}),
905
+ signal: controller.signal,
906
+ respond(result: unknown) {
907
+ const accepted = open && !offered && !done;
908
+ if (accepted) offered = true;
909
+ void Promise.resolve(result).then(
910
+ (value) => {
911
+ if (!accepted || done) return;
912
+ // Revalidate the session and model: a report for the provider that
913
+ // was selected three seconds ago is not this session's report.
914
+ if (ctx.sessionManager !== session || sessionId(ctx) !== sessionIdValue) {
915
+ finish({ ok: false, reason: "stale-context" });
916
+ return;
917
+ }
918
+ if (modelIdentity(ctx) !== model) {
919
+ finish({ ok: false, reason: "stale-context" });
920
+ return;
921
+ }
922
+ finish(parseQueryResult(value));
923
+ },
924
+ () => {
925
+ if (accepted && !done) finish({ ok: false, reason: "protocol-error" });
926
+ },
927
+ );
928
+ return accepted;
929
+ },
930
+ });
931
+ } catch {
932
+ finish({ ok: false, reason: "protocol-error" });
933
+ return;
934
+ }
935
+ // Emit returned and nobody answered: there is no usage service, which is the
936
+ // common case and not a failure worth retrying.
937
+ open = false;
938
+ if (!offered) finish({ ok: false, reason: "no-service" });
939
+ });
940
+ }
941
+
942
+ function sessionId(ctx: ExtensionContext): string {
943
+ try {
944
+ return String(ctx.sessionManager.getSessionId());
945
+ } catch {
946
+ return "";
947
+ }
948
+ }
949
+
950
+ /**
951
+ * The provider and model as a stability key. Deliberately not the whole model
952
+ * object: two snapshots of the same selection must compare equal, and a provider
953
+ * that reports nothing for `qwen-72b` should stay asleep while that stays chosen.
954
+ */
955
+ function modelIdentity(ctx: ExtensionContext): string {
956
+ const model = ctx.model as { provider?: unknown; id?: unknown } | undefined | null;
957
+ if (!model || typeof model !== "object") return "";
958
+ return `${String(model.provider ?? "")}/${String(model.id ?? "")}`;
959
+ }