@deathbeam/pi-usage 0.0.13 → 0.0.14

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/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Use the `/usage` command for a fullscreen dashboard of token usage and cost. It opens on a Summary and has per-day, per-provider, per-model and per-project views.
4
4
 
5
+ The Summary covers totals, trends with a month projection, the delegate share of the cost, activity and the top models, providers, projects and sessions.
6
+
5
7
  ## Installation
6
8
 
7
9
  ```sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-usage",
3
- "version": "0.0.13",
3
+ "version": "0.0.14",
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/summary.ts CHANGED
@@ -29,16 +29,31 @@ export type Heatmap = { header: string; rows: (HeatCell | undefined)[][] };
29
29
 
30
30
  export type Trends = {
31
31
  today: number;
32
- /** Per-day spend so far this week and this month, with the change against the previous one. */
32
+ /** Totals and per-day spend so far this week and this month, against the previous ones. */
33
33
  week: number;
34
+ weekTotal: number;
34
35
  weekDelta: number;
35
36
  month: number;
37
+ monthTotal: number;
36
38
  monthDelta: number;
39
+ lastMonthTotal: number;
40
+ /** This month's per-day average spread over every day of the month. */
41
+ projection: number;
37
42
  };
38
43
 
39
- export type TopLists = { models: GroupRow[]; projects: GroupRow[]; sessions: GroupRow[] };
44
+ export type TopLists = {
45
+ models: GroupRow[];
46
+ providers: GroupRow[];
47
+ projects: GroupRow[];
48
+ sessions: GroupRow[];
49
+ };
50
+
51
+ /** Delegate child sessions and their share of the total cost, as a fraction. */
52
+ export type Delegates = { cost: number; share: number };
40
53
 
41
54
  type Cell = { label: string; value: string };
55
+ type GridColumn = { label: number; width: number };
56
+ type TrendRow = { label: string; total: string; perDay?: string; delta?: string; suffix?: string; accent?: boolean };
42
57
  type List = { title: string; mode?: GroupMode; rows: GroupRow[] };
43
58
  type Section = { title: string; maxColumns: number; cells: (width: number) => Cell[] };
44
59
 
@@ -56,6 +71,7 @@ export type SummaryModel = {
56
71
  /** Absent when a single day is in context: there is nothing to compare it with. */
57
72
  trends?: Trends;
58
73
  top: TopLists;
74
+ delegates: Delegates;
59
75
  };
60
76
 
61
77
  const WEEKDAYS = ["Mon", "", "Wed", "", "Fri", "", ""];
@@ -69,12 +85,16 @@ const HEAT_LEVELS = [
69
85
  ] as const;
70
86
  const INDENT = " ";
71
87
  const COLUMN_GAP = 3;
88
+ /** pi-delegate children persist their own sessions under this id prefix. */
89
+ const DELEGATE_PREFIX = "delegate-";
72
90
  /** Narrowest a section may get before it is stacked instead of placed beside another. */
73
91
  const MIN_SECTION_WIDTH = 44;
74
92
  /** Longest a name column grows; a longer list would push the bar too far from the name. */
75
93
  const MAX_NAME_WIDTH = 30;
76
94
  /** Space the bar and the cost take in a top list row. */
77
95
  const LIST_OVERHEAD = 24;
96
+ /** Two lists share a row while each keeps its names readable. */
97
+ const LISTS_PER_ROW = 2;
78
98
 
79
99
  function emptyStats(): Stats {
80
100
  return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
@@ -82,12 +102,18 @@ function emptyStats(): Stats {
82
102
 
83
103
  function trends(records: UsageRecord[], now: number): Trends {
84
104
  const compare = comparison(records, now);
105
+ const date = new Date(now);
106
+ const monthDays = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
85
107
  return {
86
108
  today: compare.today,
87
109
  week: compare.week,
110
+ weekTotal: compare.weekTotal,
88
111
  weekDelta: percentChange(compare.week, compare.lastWeek),
89
112
  month: compare.month,
113
+ monthTotal: compare.monthTotal,
90
114
  monthDelta: percentChange(compare.month, compare.lastMonth),
115
+ lastMonthTotal: compare.lastMonthTotal,
116
+ projection: compare.month * monthDays,
91
117
  };
92
118
  }
93
119
 
@@ -106,28 +132,35 @@ function cellText(cell: Cell, theme: Theme, labelWidth = visibleWidth(cell.label
106
132
  return theme.fg("muted", padWidth(cell.label, labelWidth)) + " " + cell.value;
107
133
  }
108
134
 
109
- /** One label/value column per entry, sized to its widest cell plus the gap. */
110
- function columnWidths(cells: Cell[], count: number, theme: Theme): number[] {
135
+ /** Widest label and widest padded value per column, plus the gap; labels pad so values line up. */
136
+ function gridColumns(cells: Cell[], count: number, theme: Theme): GridColumn[] {
137
+ const labels = Array.from({ length: count }, () => 0);
138
+ for (const [index, cell] of cells.entries()) {
139
+ const column = index % count;
140
+ labels[column] = Math.max(labels[column]!, visibleWidth(cell.label));
141
+ }
111
142
  const widths = Array.from({ length: count }, () => 0);
112
143
  for (const [index, cell] of cells.entries()) {
113
144
  const column = index % count;
114
- widths[column] = Math.max(widths[column]!, visibleWidth(cellText(cell, theme)) + COLUMN_GAP);
145
+ widths[column] = Math.max(widths[column]!, visibleWidth(cellText(cell, theme, labels[column]!)) + COLUMN_GAP);
115
146
  }
116
- return widths;
147
+ return labels.map((label, column) => ({ label, width: widths[column]! }));
117
148
  }
118
149
 
119
150
  /** Label/value pairs in as many aligned columns as `maxColumns` and the width allow. */
120
151
  function grid(cells: Cell[], width: number, maxColumns: number, theme: Theme): string[] {
121
152
  for (let count = Math.min(cells.length, maxColumns); count > 0; count--) {
122
- const widths = columnWidths(cells, count, theme);
123
- const used = widths.reduce((sum, column) => sum + column, 0) - COLUMN_GAP;
153
+ const columns = gridColumns(cells, count, theme);
154
+ const used = columns.reduce((sum, column) => sum + column.width, 0) - COLUMN_GAP;
124
155
  if (count > 1 && used > width) continue;
125
156
  const rows: string[] = [];
126
157
  for (let start = 0; start < cells.length; start += count) {
127
158
  rows.push(
128
159
  cells
129
160
  .slice(start, start + count)
130
- .map((cell, column) => padWidth(cellText(cell, theme), widths[column]!))
161
+ .map((cell, column) =>
162
+ padWidth(cellText(cell, theme, columns[column]!.label), columns[column]!.width),
163
+ )
131
164
  .join("")
132
165
  .trimEnd(),
133
166
  );
@@ -186,6 +219,17 @@ function activity(daily: DailyCost[], width: number, theme: Theme): string[] {
186
219
  return rows;
187
220
  }
188
221
 
222
+ /** Delegate children cost against the whole set; the id prefix is the only marker of a delegate session. */
223
+ function delegateSplit(records: UsageRecord[]): Delegates {
224
+ let cost = 0;
225
+ let total = 0;
226
+ for (const record of records) {
227
+ total += record.cost;
228
+ if (record.sessionId.startsWith(DELEGATE_PREFIX)) cost += record.cost;
229
+ }
230
+ return { cost, share: total > 0 ? cost / total : 0 };
231
+ }
232
+
189
233
  /** Cost, volume and token cells; one group per column so the three start side by side. */
190
234
  function kpiGroups(model: SummaryModel, theme: Theme): Cell[][] {
191
235
  const { stats } = model;
@@ -194,6 +238,13 @@ function kpiGroups(model: SummaryModel, theme: Theme): Cell[][] {
194
238
  { label: "Total", value: cellValue(formatCost(stats.cost), true, theme) },
195
239
  { label: "Per day", value: cellValue(formatCost(model.perDay), false, theme) },
196
240
  { label: "Per session", value: cellValue(formatCost(model.perSession), false, theme) },
241
+ {
242
+ label: "Delegates",
243
+ value:
244
+ cellValue(formatCost(model.delegates.cost), false, theme) +
245
+ " " +
246
+ theme.fg("muted", `${Math.round(100 * model.delegates.share)}%`),
247
+ },
197
248
  ],
198
249
  [
199
250
  { label: "Reqs", value: cellValue(formatTokens(model.requests), false, theme) },
@@ -234,23 +285,54 @@ function kpiBlock(groups: Cell[][], width: number, theme: Theme): string[] {
234
285
  );
235
286
  }
236
287
 
237
- function trendCells(model: SummaryModel, width: number, theme: Theme): Cell[] {
288
+ /** Total, then per day, then the change against the previous period. */
289
+ function trendRows(model: SummaryModel, theme: Theme): TrendRow[] {
238
290
  const trends = model.trends!;
239
- /** Bold average, colored delta, muted comparison; only the suffix is dropped when space runs out. */
240
- function trend(label: string, average: number, delta: number, suffix: string): Cell {
241
- const avg = `${formatCost(average)}/day`;
242
- const change = deltaText(delta, theme);
243
- // grid() skips its width test for a single column, so an oversized value would be cut mid-word.
244
- const fits = visibleWidth(`${label} ${avg} ${change} ${suffix}`) <= width;
245
- return { label, value: `${theme.bold(avg)} ${change}${fits ? theme.fg("muted", ` ${suffix}`) : ""}` };
246
- }
247
291
  return [
248
- { label: "Today", value: cellValue(formatCost(trends.today), true, theme) },
249
- trend("This week", trends.week, trends.weekDelta, "vs last week"),
250
- trend("This month", trends.month, trends.monthDelta, "vs last month"),
292
+ { label: "Today", total: formatCost(trends.today), accent: true },
293
+ {
294
+ label: "This week",
295
+ total: formatCost(trends.weekTotal),
296
+ perDay: `${formatCost(trends.week)}/day`,
297
+ delta: deltaText(trends.weekDelta, theme),
298
+ suffix: "vs last week",
299
+ },
300
+ {
301
+ label: "This month",
302
+ total: formatCost(trends.monthTotal),
303
+ perDay: `${formatCost(trends.month)}/day`,
304
+ delta: deltaText(trends.monthDelta, theme),
305
+ suffix: "vs last month",
306
+ },
307
+ {
308
+ label: "Projected",
309
+ total: formatCost(trends.projection),
310
+ suffix: `vs ${formatCost(trends.lastMonthTotal)} last month`,
311
+ },
251
312
  ];
252
313
  }
253
314
 
315
+ /** The per-day columns go before the total is dropped, and the wording goes last: the total always stays. */
316
+ function trendCells(model: SummaryModel, width: number, theme: Theme): Cell[] {
317
+ const rows = trendRows(model, theme);
318
+ const labelWidth = Math.max(...rows.map((row) => visibleWidth(row.label)));
319
+ const totalWidth = Math.max(...rows.map((row) => visibleWidth(row.total)));
320
+ const perDayWidth = Math.max(...rows.map((row) => visibleWidth(row.perDay ?? "")));
321
+ const deltaWidth = Math.max(...rows.map((row) => visibleWidth(row.delta ?? "")));
322
+ // One decision for the whole block: a column shown on some rows only would break the alignment.
323
+ const detailed = labelWidth + 2 + totalWidth + 2 + perDayWidth + 2 + deltaWidth <= width;
324
+ return rows.map((row) => {
325
+ const total = padWidth(cellValue(row.total, row.accent === true, theme), totalWidth);
326
+ const perDay = detailed && row.perDay !== undefined ? " " + padWidth(theme.bold(row.perDay), perDayWidth) : "";
327
+ const delta = detailed && row.delta !== undefined ? " " + row.delta : "";
328
+ const value = total + perDay + delta;
329
+ const suffix = row.suffix === undefined ? "" : ` ${row.suffix}`;
330
+ // grid() skips its width test for a single column, so an oversized row would be cut mid-word.
331
+ const fits = labelWidth + 2 + visibleWidth(value) + visibleWidth(suffix) <= width;
332
+ return { label: row.label, value: value + (fits ? theme.fg("muted", suffix) : "") };
333
+ });
334
+ }
335
+
254
336
  function days(count: number): string {
255
337
  return `${count} ${count === 1 ? "day" : "days"}`;
256
338
  }
@@ -296,15 +378,24 @@ function sideBySide(blocks: string[][], widths: number[]): string[] {
296
378
  return lines;
297
379
  }
298
380
 
299
- function listRow(lists: List[], totalCost: number, width: number, theme: Theme): string[] {
300
- const widths = rowWidths(width, lists.length);
381
+ /** One row of lists at the given column widths, so the pairs line up down the rows. */
382
+ function listRow(lists: List[], widths: number[], totalCost: number, theme: Theme): string[] {
301
383
  return sideBySide(
302
384
  lists.map((list, column) => listBlock(list, totalCost, widths[column]!, theme)),
303
385
  widths,
304
386
  );
305
387
  }
306
388
 
307
- /** Trends and streaks share a row while each keeps a readable width. */
389
+ /** A section's heading and its cell grid, rendered into `width`. */
390
+ function sectionBlock(section: Section, width: number, theme: Theme): string[] {
391
+ const bodyWidth = Math.max(1, width - INDENT.length);
392
+ return [
393
+ heading(theme, section.title),
394
+ ...indent(grid(section.cells(bodyWidth), bodyWidth, section.maxColumns, theme)),
395
+ ];
396
+ }
397
+
398
+ /** Trends and streaks share a row while each keeps its content width instead of an even share. */
308
399
  function sections(items: Section[], width: number, theme: Theme): string[] {
309
400
  const count = Math.max(
310
401
  1,
@@ -314,17 +405,19 @@ function sections(items: Section[], width: number, theme: Theme): string[] {
314
405
  for (let start = 0; start < items.length; start += count) {
315
406
  if (lines.length > 0) lines.push("");
316
407
  const row = items.slice(start, start + count);
317
- const widths = rowWidths(width, row.length);
408
+ // Render at the full width first: a section that needs less keeps its wording and sits next to its
409
+ // neighbour instead of being squeezed into half the terminal.
410
+ const natural = row.map((section) => sectionBlock(section, width, theme));
411
+ const widths = natural.map((block) => Math.max(...block.map((line) => visibleWidth(line))));
412
+ if (widths.reduce((sum, column) => sum + column, 0) + COLUMN_GAP * (row.length - 1) <= width) {
413
+ lines.push(...sideBySide(natural, widths));
414
+ continue;
415
+ }
416
+ const share = rowWidths(width, row.length);
318
417
  lines.push(
319
418
  ...sideBySide(
320
- row.map((section, column) => {
321
- const bodyWidth = Math.max(1, widths[column]! - INDENT.length);
322
- return [
323
- heading(theme, section.title),
324
- ...indent(grid(section.cells(bodyWidth), bodyWidth, section.maxColumns, theme)),
325
- ];
326
- }),
327
- widths,
419
+ row.map((section, column) => sectionBlock(section, share[column]!, theme)),
420
+ share,
328
421
  ),
329
422
  );
330
423
  }
@@ -476,9 +569,11 @@ export function summaryModel(
476
569
  trends: withTrends ? trends(records, now) : undefined,
477
570
  top: {
478
571
  models: topGroups(records, 0, Infinity, "model"),
572
+ providers: topGroups(records, 0, Infinity, "provider"),
479
573
  projects: topGroups(records, 0, Infinity, "project"),
480
574
  sessions: topSessions(records, 0, Infinity),
481
575
  },
576
+ delegates: delegateSplit(records),
482
577
  };
483
578
  }
484
579
 
@@ -495,27 +590,24 @@ export function summaryLines(model: SummaryModel, width: number, theme: Theme):
495
590
  const lists = (
496
591
  [
497
592
  { title: "Models", mode: "model", rows: model.top.models },
593
+ { title: "Providers", mode: "provider", rows: model.top.providers },
498
594
  { title: "Projects", mode: "project", rows: model.top.projects },
595
+ { title: "Sessions", rows: model.top.sessions },
499
596
  ] satisfies List[]
500
597
  ).filter((list) => list.rows.length > 0);
501
- let listColumn = width;
502
- if (lists.length > 0) {
503
- // Names are the point of a list, so two blocks share a row only while both keep them readable.
504
- const needed = lists.reduce((sum, list) => sum + listWidth(list, width), 0) + COLUMN_GAP * (lists.length - 1);
505
- if (needed <= width) {
506
- listColumn = rowWidths(width, lists.length)[0]!;
507
- lines.push("", ...listRow(lists, model.stats.cost, width, theme));
508
- } else {
509
- for (const list of lists) lines.push("", ...listBlock(list, model.stats.cost, width, theme));
510
- }
511
- }
512
- const sessions: List = { title: "Sessions", rows: model.top.sessions };
513
- if (sessions.rows.length > 0) {
514
- // Session names carry the date and the id, so the block outgrows its column rather than cut them.
515
- lines.push(
516
- "",
517
- ...listBlock(sessions, model.stats.cost, Math.max(listColumn, listWidth(sessions, width)), theme),
518
- );
598
+ // A list column is as wide as the widest list that lands in it, so the pairs line up down the rows and
599
+ // stop at their content instead of hugging the right edge of a wide terminal.
600
+ const listColumns = Array.from({ length: LISTS_PER_ROW }, (_, column) =>
601
+ Math.max(
602
+ 0,
603
+ ...lists.filter((_, index) => index % LISTS_PER_ROW === column).map((list) => listWidth(list, width)),
604
+ ),
605
+ );
606
+ const paired = lists.length > 1 && listColumns.reduce((sum, column) => sum + column, 0) + COLUMN_GAP <= width;
607
+ for (let start = 0; start < lists.length; start += paired ? LISTS_PER_ROW : 1) {
608
+ const row = lists.slice(start, start + (paired ? LISTS_PER_ROW : 1));
609
+ const widths = row.map((_, column) => (paired ? listColumns[column]! : width));
610
+ lines.push("", ...listRow(row, widths, model.stats.cost, theme));
519
611
  }
520
612
  return lines;
521
613
  }
package/src/usage.ts CHANGED
@@ -366,9 +366,12 @@ export function comparison(records: UsageRecord[], now = Date.now()) {
366
366
  return {
367
367
  today: todayCost,
368
368
  week: weekCost / windowDays(weekStart, until),
369
+ weekTotal: weekCost,
369
370
  lastWeek: lastWeekCost / 7,
370
371
  month: monthCost / windowDays(monthStart, until),
372
+ monthTotal: monthCost,
371
373
  lastMonth: lastMonthCost / windowDays(lastMonth, monthStart),
374
+ lastMonthTotal: lastMonthCost,
372
375
  };
373
376
  }
374
377