@deathbeam/pi-usage 0.0.7 → 0.0.8

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.
Files changed (3) hide show
  1. package/index.ts +28 -17
  2. package/package.json +1 -1
  3. package/src/usage.ts +70 -60
package/index.ts CHANGED
@@ -32,6 +32,7 @@ type Column = {
32
32
  };
33
33
  type BodyRow = GroupRow & { parent?: string };
34
34
  type Frame = { filters: UsageFilter[]; group: number; cursor: number; top: number };
35
+ type SparkBar = { label: string; char: string };
35
36
 
36
37
  const GROUPS = ["day", "provider", "model", "project"] as const satisfies readonly GroupMode[];
37
38
  const GROUP_LABELS: Record<GroupMode, string> = {
@@ -88,7 +89,9 @@ function hitPct(stats: Stats): string {
88
89
  }
89
90
 
90
91
  function layout(width: number, allColumns: Column[]): { nameWidth: number; columns: Column[] } {
91
- const used = (cols: Column[]) => cols.reduce((sum, c) => sum + c.width + 1, 0);
92
+ function used(cols: Column[]): number {
93
+ return cols.reduce((sum, c) => sum + c.width + 1, 0);
94
+ }
92
95
  let columns = allColumns;
93
96
  for (const label of ["Share", "Hit%", "Cache", "Out", "In", "Reqs", "Δ"]) {
94
97
  if (width - used(columns) >= MIN_NAME_WIDTH) break;
@@ -97,7 +100,9 @@ function layout(width: number, allColumns: Column[]): { nameWidth: number; colum
97
100
  return { nameWidth: Math.max(4, width - used(columns)), columns };
98
101
  }
99
102
 
100
- const padWidth = (s: string, w: number): string => s + " ".repeat(Math.max(0, w - visibleWidth(s)));
103
+ function padWidth(s: string, w: number): string {
104
+ return s + " ".repeat(Math.max(0, w - visibleWidth(s)));
105
+ }
101
106
 
102
107
  function displayName(mode: GroupMode, name: string): string {
103
108
  if (mode === "day") return `${name} ${new Date(`${name}T00:00`).toLocaleDateString("en-US", { weekday: "short" })}`;
@@ -122,8 +127,6 @@ function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCos
122
127
  .trimEnd();
123
128
  }
124
129
 
125
- type SparkBar = { label: string; char: string };
126
-
127
130
  function sparkline(daily: DailyCost[], width: number): { first: string; last: string; bars: SparkBar[] } | undefined {
128
131
  const recent = daily.slice(-Math.max(1, width - 12));
129
132
  if (recent.length === 0) return undefined;
@@ -182,9 +185,13 @@ export default function (pi: ExtensionAPI) {
182
185
  let viewHeight = 1; // set on first render; 1 keeps page keys sane before it
183
186
  let body: BodyRow[] = [];
184
187
  const stack: Frame[] = [];
185
- const filters = () => stack.flatMap((frame) => frame.filters);
186
- const dayFilter = () => filters().findLast((f) => f.mode === "day");
187
- const derive = (source: UsageRecord[]) => {
188
+ function filters() {
189
+ return stack.flatMap((frame) => frame.filters);
190
+ }
191
+ function dayFilter() {
192
+ return filters().findLast((f) => f.mode === "day");
193
+ }
194
+ function derive(source: UsageRecord[]) {
188
195
  const active = filters();
189
196
  const records = source.filter((record) =>
190
197
  active.every((f) => f.mode === "day" || matchesFilter(record, f)),
@@ -195,24 +202,27 @@ export default function (pi: ExtensionAPI) {
195
202
  const summary = summarize(records, window.since, window.until);
196
203
  const body = flatten(buildRows(records, window.since, mode, window.until), mode);
197
204
  return { mode, summary, body, compare: day ? undefined : comparison(records) };
198
- };
205
+ }
199
206
  const getView = cacheView(() => derive(state.records!));
200
207
  let allDays: DailyCost[] | undefined;
201
- const allDaily = () => (allDays ??= dailyTotals(state.records!));
208
+ function allDaily() {
209
+ return (allDays ??= dailyTotals(state.records!));
210
+ }
202
211
  render = () => tui.requestRender();
203
212
  void loaded.then(render);
204
- const colorDelta = (delta: number | undefined): string => {
213
+ function colorDelta(delta: number | undefined): string {
205
214
  if (delta === undefined) return "-";
206
215
  if (delta === 0) return "0%";
207
216
  const text = Number.isFinite(delta)
208
217
  ? `${delta > 0 ? "▲" : "▼"}${Math.round(Math.abs(delta))}%`
209
218
  : "▲new";
210
219
  return theme.fg(delta > 0 ? "error" : "success", text);
211
- };
220
+ }
212
221
  const deltaColumn: Column = { label: "Δ", width: 9, cell: (_s, _r, _t, row) => colorDelta(row?.delta) };
213
- const title = (width: number): string => {
214
- const tab = (label: string, active: boolean) =>
215
- active ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `);
222
+ function title(width: number): string {
223
+ function tab(label: string, active: boolean): string {
224
+ return active ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `);
225
+ }
216
226
  const left =
217
227
  theme.fg("accent", theme.bold("Usage")) +
218
228
  filters()
@@ -233,12 +243,13 @@ export default function (pi: ExtensionAPI) {
233
243
  right,
234
244
  width,
235
245
  );
236
- };
237
- const footer = (width: number): string =>
238
- truncateToWidth(
246
+ }
247
+ function footer(width: number): string {
248
+ return truncateToWidth(
239
249
  theme.fg("dim", "enter open · esc back · tab/←→ group · [ ] day · q close · ↑↓ scroll"),
240
250
  width,
241
251
  );
252
+ }
242
253
  return {
243
254
  render(width: number) {
244
255
  const rows = tui.terminal.rows;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-usage",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "description": "Minimal extension for token usage and cost per provider, model and project.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/usage.ts CHANGED
@@ -29,6 +29,35 @@ export type Stats = {
29
29
  cacheWrite: number;
30
30
  };
31
31
 
32
+ type CacheEntry = { size: number; mtimeMs: number; records: UsageRecord[] };
33
+ type Cache = { version: number; files: Record<string, CacheEntry> };
34
+
35
+ export type GroupMode = "day" | "provider" | "model" | "project";
36
+ export type UsageFilter = { mode: GroupMode; key: string };
37
+
38
+ export type GroupRow = {
39
+ key: string;
40
+ name: string;
41
+ stats: Stats;
42
+ requests: number;
43
+ delta?: number;
44
+ /** Nested model rows; only produced by provider grouping. */
45
+ children?: GroupRow[];
46
+ };
47
+
48
+ export type Summary = {
49
+ stats: Stats;
50
+ requests: number;
51
+ /** Distinct session ids (files) seen in the window. */
52
+ sessions: number;
53
+ };
54
+
55
+ export type DailyCost = { label: string; cost: number };
56
+
57
+ type Tally = { stats: Stats; requests: number; models?: Map<string, Tally>; providers?: Set<string> };
58
+
59
+ const CACHE_VERSION = 1;
60
+
32
61
  function emptyStats(): Stats {
33
62
  return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
34
63
  }
@@ -37,6 +66,31 @@ function num(value: unknown): number {
37
66
  return typeof value === "number" && Number.isFinite(value) ? value : 0;
38
67
  }
39
68
 
69
+ function addStats(stats: Stats, record: UsageRecord): void {
70
+ stats.cost += record.cost;
71
+ stats.input += record.input;
72
+ stats.output += record.output;
73
+ stats.cacheRead += record.cacheRead;
74
+ stats.cacheWrite += record.cacheWrite;
75
+ }
76
+
77
+ function recordKey(record: UsageRecord, mode: GroupMode): string {
78
+ return mode === "day" ? dayKey(record.ts) : mode === "project" ? record.cwd : record[mode];
79
+ }
80
+
81
+ function tokens(s: Stats): number {
82
+ return s.input + s.output + s.cacheRead + s.cacheWrite;
83
+ }
84
+
85
+ /** Cost descending, then total tokens (so free models still rank by usage). */
86
+ function byCost(a: GroupRow, b: GroupRow): number {
87
+ return b.stats.cost - a.stats.cost || tokens(b.stats) - tokens(a.stats);
88
+ }
89
+
90
+ function newTally(): Tally {
91
+ return { stats: emptyStats(), requests: 0 };
92
+ }
93
+
40
94
  async function sessionFiles(dir: string, out: string[]): Promise<void> {
41
95
  let entries;
42
96
  try {
@@ -51,11 +105,6 @@ async function sessionFiles(dir: string, out: string[]): Promise<void> {
51
105
  }
52
106
  }
53
107
 
54
- type CacheEntry = { size: number; mtimeMs: number; records: UsageRecord[] };
55
- type Cache = { version: number; files: Record<string, CacheEntry> };
56
-
57
- const CACHE_VERSION = 1;
58
-
59
108
  async function readCache(file: string): Promise<Record<string, CacheEntry>> {
60
109
  try {
61
110
  const cache = JSON.parse(await readFile(file, "utf8")) as Cache;
@@ -178,17 +227,6 @@ export async function collectUsage(
178
227
  return records;
179
228
  }
180
229
 
181
- function addStats(stats: Stats, record: UsageRecord): void {
182
- stats.cost += record.cost;
183
- stats.input += record.input;
184
- stats.output += record.output;
185
- stats.cacheRead += record.cacheRead;
186
- stats.cacheWrite += record.cacheWrite;
187
- }
188
-
189
- export type GroupMode = "day" | "provider" | "model" | "project";
190
- export type UsageFilter = { mode: GroupMode; key: string };
191
-
192
230
  export function cacheView<T>(derive: () => T) {
193
231
  let cached: { key: string; value: T } | undefined;
194
232
  return (mode: GroupMode, filters: UsageFilter[], now = Date.now()): T => {
@@ -220,10 +258,10 @@ export function dayWindow(key: string, offset = 0): { since: number; until: numb
220
258
  // UTC ordinals count local calendar days without DST changing their length.
221
259
  export function windowDays(since: number, until: number): number {
222
260
  if (since >= until) return 0;
223
- const ordinal = (ts: number) => {
261
+ function ordinal(ts: number): number {
224
262
  const d = new Date(ts);
225
263
  return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) / 86_400_000;
226
- };
264
+ }
227
265
  return ordinal(until - 1) - ordinal(since) + 1;
228
266
  }
229
267
 
@@ -231,10 +269,6 @@ export function percentChange(current: number, previous: number): number {
231
269
  return previous === 0 ? (current === 0 ? 0 : Infinity) : ((current - previous) / previous) * 100;
232
270
  }
233
271
 
234
- function recordKey(record: UsageRecord, mode: GroupMode): string {
235
- return mode === "day" ? dayKey(record.ts) : mode === "project" ? record.cwd : record[mode];
236
- }
237
-
238
272
  export function matchesFilter(record: UsageRecord, filter: UsageFilter): boolean {
239
273
  return recordKey(record, filter.mode) === filter.key;
240
274
  }
@@ -280,25 +314,6 @@ export function comparison(records: UsageRecord[], now = Date.now()) {
280
314
  };
281
315
  }
282
316
 
283
- export type GroupRow = {
284
- key: string;
285
- name: string;
286
- stats: Stats;
287
- requests: number;
288
- delta?: number;
289
- /** Nested model rows; only produced by provider grouping. */
290
- children?: GroupRow[];
291
- };
292
-
293
- const tokens = (s: Stats): number => s.input + s.output + s.cacheRead + s.cacheWrite;
294
-
295
- /** Cost descending, then total tokens (so free models still rank by usage). */
296
- const byCost = (a: GroupRow, b: GroupRow): number => b.stats.cost - a.stats.cost || tokens(b.stats) - tokens(a.stats);
297
-
298
- type Tally = { stats: Stats; requests: number; models?: Map<string, Tally>; providers?: Set<string> };
299
-
300
- const newTally = (): Tally => ({ stats: emptyStats(), requests: 0 });
301
-
302
317
  export function buildRows(
303
318
  records: UsageRecord[],
304
319
  sinceMs = 0,
@@ -344,23 +359,18 @@ export function buildRows(
344
359
  rows[i]!.delta = percentChange(rows[i]!.stats.cost, rows[i + 1]!.stats.cost);
345
360
  return rows;
346
361
  }
347
- const toRow = ([name, group]: [string, Tally]): GroupRow => ({
348
- key: name,
349
- name: mode === "model" && group.providers!.size > 1 ? `${name} (${group.providers!.size})` : name,
350
- stats: group.stats,
351
- requests: group.requests,
352
- children: group.models && [...group.models].map(toRow).sort(byCost),
353
- });
362
+ function toRow([name, group]: [string, Tally]): GroupRow {
363
+ return {
364
+ key: name,
365
+ name: mode === "model" && group.providers!.size > 1 ? `${name} (${group.providers!.size})` : name,
366
+ stats: group.stats,
367
+ requests: group.requests,
368
+ children: group.models && [...group.models].map(toRow).sort(byCost),
369
+ };
370
+ }
354
371
  return [...groups].map(toRow).sort(byCost);
355
372
  }
356
373
 
357
- export type Summary = {
358
- stats: Stats;
359
- requests: number;
360
- /** Distinct session ids (files) seen in the window. */
361
- sessions: number;
362
- };
363
-
364
374
  /** Totals for the summary block: one pass over [sinceMs, untilMs). */
365
375
  export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinity): Summary {
366
376
  const stats = emptyStats();
@@ -375,9 +385,9 @@ export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinit
375
385
  return { stats, requests, sessions: sessions.size };
376
386
  }
377
387
 
378
- export type DailyCost = { label: string; cost: number };
379
-
380
- export const seriesKey = (key: string, parent?: string): string => JSON.stringify([key, parent ?? null]);
388
+ export function seriesKey(key: string, parent?: string): string {
389
+ return JSON.stringify([key, parent ?? null]);
390
+ }
381
391
 
382
392
  export function buildDailySeries(
383
393
  records: UsageRecord[],
@@ -396,11 +406,11 @@ export function buildDailySeries(
396
406
  cursor = dayWindow(key).until;
397
407
  }
398
408
  const costs = new Map<string, Map<number, number>>();
399
- const add = (key: string, index: number, cost: number) => {
409
+ function add(key: string, index: number, cost: number): void {
400
410
  let values = costs.get(key);
401
411
  if (!values) costs.set(key, (values = new Map()));
402
412
  values.set(index, (values.get(index) ?? 0) + cost);
403
- };
413
+ }
404
414
  for (const record of records) {
405
415
  if (record.ts < since || record.ts >= until) continue;
406
416
  const index = positions.get(dayKey(record.ts));