@deathbeam/pi-usage 0.0.5 → 0.0.6

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 (4) hide show
  1. package/README.md +1 -1
  2. package/index.ts +36 -22
  3. package/package.json +1 -1
  4. package/usage.ts +17 -30
package/README.md CHANGED
@@ -15,7 +15,7 @@ Use the `/usage` command for a fullscreen dashboard of token usage and costs.
15
15
  | Page Up / Page Down | Move by a page |
16
16
  | `g` / `G` | Move to the first / last row |
17
17
 
18
- Day rows include days without usage. Δ compares cost with the previous day. The sparkline shows the selected row over all history and is hidden when a day is open.
18
+ Day rows include days without usage. Δ compares cost with the previous day. The sparkline always shows total cost per day across all history; the day in context is highlighted.
19
19
 
20
20
  The summary compares the daily spend so far this week and month with last week and month. Weeks start on Monday in local time. `▲new` means the previous period had no spend.
21
21
 
package/index.ts CHANGED
@@ -6,17 +6,15 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
6
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
7
  import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
8
8
  import {
9
- bucketCosts,
10
- buildDailySeries,
11
9
  buildRows,
12
10
  cacheView,
13
11
  collectUsage,
14
12
  comparison,
13
+ dailyTotals,
15
14
  dayKey,
16
15
  dayWindow,
17
16
  matchesFilter,
18
17
  percentChange,
19
- seriesKey,
20
18
  summarize,
21
19
  usageWindow,
22
20
  type DailyCost,
@@ -124,17 +122,20 @@ function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCos
124
122
  .trimEnd();
125
123
  }
126
124
 
127
- function sparkline(daily: DailyCost[], width: number): { first: string; bars: string; last: string } | undefined {
128
- if (daily.length <= 1) return undefined;
129
- const first = daily[0]!.label;
130
- const last = daily[daily.length - 1]!.label;
131
- const bars = bucketCosts(daily, Math.ceil(daily.length / Math.max(1, width - 12)));
125
+ type SparkBar = { label: string; char: string };
126
+
127
+ function sparkline(daily: DailyCost[], width: number): { first: string; last: string; bars: SparkBar[] } | undefined {
128
+ const recent = daily.slice(-Math.max(1, width - 12));
129
+ if (recent.length === 0) return undefined;
132
130
  let max = 0;
133
- for (const bar of bars) if (bar.cost > max) max = bar.cost;
131
+ for (const day of recent) if (day.cost > max) max = day.cost;
134
132
  return {
135
- first,
136
- bars: bars.map((d) => (d.cost <= 0 ? " " : SPARK_BARS[Math.max(1, Math.round((7 * d.cost) / max))])).join(""),
137
- last,
133
+ first: recent[0]!.label,
134
+ last: recent[recent.length - 1]!.label,
135
+ bars: recent.map(({ label, cost }) => ({
136
+ label,
137
+ char: cost <= 0 ? " " : SPARK_BARS[Math.max(1, Math.round((7 * cost) / max))]!,
138
+ })),
138
139
  };
139
140
  }
140
141
 
@@ -189,10 +190,11 @@ export default function (pi: ExtensionAPI) {
189
190
  const mode = GROUPS[group]!;
190
191
  const summary = summarize(records, window.since, window.until);
191
192
  const body = flatten(buildRows(records, window.since, mode, window.until), mode);
192
- const series = day ? undefined : buildDailySeries(records, window.since, window.until, mode);
193
- return { mode, summary, body, series, compare: day ? undefined : comparison(records) };
193
+ return { mode, summary, body, compare: day ? undefined : comparison(records) };
194
194
  };
195
195
  const getView = cacheView(() => derive(state.records!));
196
+ let allDays: DailyCost[] | undefined;
197
+ const allDaily = () => (allDays ??= dailyTotals(state.records!));
196
198
  render = () => tui.requestRender();
197
199
  void loaded.then(render);
198
200
  const colorDelta = (delta: number | undefined): string => {
@@ -251,7 +253,7 @@ export default function (pi: ExtensionAPI) {
251
253
  return lines.slice(0, rows);
252
254
  }
253
255
  const view = getView(GROUPS[group]!, filters());
254
- const { mode, summary, series, compare } = view;
256
+ const { mode, summary, compare } = view;
255
257
  const first = compare
256
258
  ? `Today ${formatCost(compare.today)} · This week ${formatCost(compare.week)}/day ${colorDelta(percentChange(compare.week, compare.lastWeek))} vs last week · This month ${formatCost(compare.month)}/day ${colorDelta(percentChange(compare.month, compare.lastMonth))} vs last month`
257
259
  : `Cost ${formatCost(summary.stats.cost)}`;
@@ -266,15 +268,24 @@ export default function (pi: ExtensionAPI) {
266
268
  rowCount = body.length;
267
269
  cursor = Math.min(cursor, Math.max(0, rowCount - 1));
268
270
  const selected = body[cursor];
269
- const costs = selected && series?.rows.get(seriesKey(selected.key, selected.parent));
270
- const daily = selected
271
- ? series?.total.map((d, i) => ({ ...d, cost: costs?.get(i) ?? 0 }))
272
- : series?.total;
273
- const spark = daily && sparkline(daily, width);
271
+ const contextDay = dayFilter()?.key ?? (mode === "day" ? selected?.key : undefined);
272
+ const contextLabel = contextDay?.slice(5);
273
+ const spark = sparkline(allDaily(), width);
274
274
  if (spark)
275
275
  lines.push(
276
276
  truncateToWidth(
277
- `${theme.fg("dim", `${spark.first} `)}${theme.fg("accent", spark.bars)}${theme.fg("dim", ` ${spark.last}`)}`,
277
+ theme.fg("dim", `${spark.first} `) +
278
+ spark.bars
279
+ .map((bar) =>
280
+ theme.fg(
281
+ contextLabel === undefined || bar.label === contextLabel
282
+ ? "accent"
283
+ : "borderMuted",
284
+ bar.char,
285
+ ),
286
+ )
287
+ .join("") +
288
+ theme.fg("dim", ` ${spark.last}`),
278
289
  width,
279
290
  ),
280
291
  );
@@ -338,7 +349,10 @@ export default function (pi: ExtensionAPI) {
338
349
  row.parent === undefined ? [] : [{ mode: "provider", key: row.parent }];
339
350
  selected.push({ mode: rowMode, key: row.key });
340
351
  stack.push({ filters: selected, group, cursor, top });
341
- group = rowMode === "day" ? 1 : 0;
352
+ // Land on the first grouping that is not already filtered.
353
+ const used = new Set(filters().map((f) => f.mode));
354
+ group = GROUPS.findIndex((g) => !used.has(g));
355
+ if (group < 0) group = dayFilter() ? 1 : 0;
342
356
  cursor = top = 0;
343
357
  } else if ((data === "[" || data === "]") && filters().at(-1)?.mode === "day") {
344
358
  const filter = filters().at(-1)!;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-usage",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "description": "Minimal extension for token usage and cost per provider, model and project.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/usage.ts CHANGED
@@ -28,7 +28,7 @@ export type Stats = {
28
28
  cacheWrite: number;
29
29
  };
30
30
 
31
- export function emptyStats(): Stats {
31
+ function emptyStats(): Stats {
32
32
  return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
33
33
  }
34
34
 
@@ -146,15 +146,18 @@ export function dayKey(ts: number): string {
146
146
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
147
147
  }
148
148
 
149
+ export function startOfDay(ts: number): number {
150
+ const date = new Date(ts);
151
+ date.setHours(0, 0, 0, 0);
152
+ return date.getTime();
153
+ }
154
+
149
155
  export function dayWindow(key: string, offset = 0): { since: number; until: number } {
150
156
  const date = new Date(`${key}T00:00`);
151
157
  date.setDate(date.getDate() + offset);
152
- date.setHours(0, 0, 0, 0);
153
- const since = date.getTime();
158
+ const since = startOfDay(date.getTime());
154
159
  date.setDate(date.getDate() + 1);
155
- // A skipped midnight can leave 01:00 on the next calendar day.
156
- date.setHours(0, 0, 0, 0);
157
- return { since, until: date.getTime() };
160
+ return { since, until: startOfDay(date.getTime()) };
158
161
  }
159
162
 
160
163
  // UTC ordinals count local calendar days without DST changing their length.
@@ -191,16 +194,13 @@ export function comparison(records: UsageRecord[], now = Date.now()) {
191
194
  const { since: today, until } = dayWindow(dayKey(now));
192
195
  const week = new Date(today);
193
196
  week.setDate(week.getDate() - ((week.getDay() + 6) % 7));
194
- week.setHours(0, 0, 0, 0);
195
- const weekStart = week.getTime();
197
+ const weekStart = startOfDay(week.getTime());
196
198
  const lastWeek = dayWindow(dayKey(weekStart), -7).since;
197
199
  const month = new Date(today);
198
200
  month.setDate(1);
199
- month.setHours(0, 0, 0, 0);
200
- const monthStart = month.getTime();
201
+ const monthStart = startOfDay(month.getTime());
201
202
  month.setMonth(month.getMonth() - 1);
202
- month.setHours(0, 0, 0, 0);
203
- const lastMonth = month.getTime();
203
+ const lastMonth = startOfDay(month.getTime());
204
204
  let todayCost = 0,
205
205
  weekCost = 0,
206
206
  lastWeekCost = 0,
@@ -302,8 +302,6 @@ export type Summary = {
302
302
  requests: number;
303
303
  /** Distinct session ids (files) seen in the window. */
304
304
  sessions: number;
305
- /** cacheRead / (input + cacheRead + cacheWrite); 0 without any tokens. */
306
- hit: number;
307
305
  };
308
306
 
309
307
  /** Totals for the summary block: one pass over [sinceMs, untilMs). */
@@ -317,13 +315,7 @@ export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinit
317
315
  requests++;
318
316
  sessions.add(record.sessionId);
319
317
  }
320
- const cacheTotal = stats.input + stats.cacheRead + stats.cacheWrite;
321
- return {
322
- stats,
323
- requests,
324
- sessions: sessions.size,
325
- hit: cacheTotal > 0 ? stats.cacheRead / cacheTotal : 0,
326
- };
318
+ return { stats, requests, sessions: sessions.size };
327
319
  }
328
320
 
329
321
  export type DailyCost = { label: string; cost: number };
@@ -364,13 +356,8 @@ export function buildDailySeries(
364
356
  return { total, rows: costs };
365
357
  }
366
358
 
367
- /** Sum `perBar` consecutive daily buckets into one bar, labeled by its first day. */
368
- export function bucketCosts(days: DailyCost[], perBar: number): DailyCost[] {
369
- if (perBar <= 1) return days;
370
- const bars: DailyCost[] = [];
371
- for (let i = 0; i < days.length; i += perBar) {
372
- const group = days.slice(i, i + perBar);
373
- bars.push({ label: group[0]!.label, cost: group.reduce((sum, d) => sum + d.cost, 0) });
374
- }
375
- return bars;
359
+ /** Total cost per local calendar day from the first recorded day through today. */
360
+ export function dailyTotals(records: UsageRecord[], now = Date.now()): DailyCost[] {
361
+ const { since, until } = usageWindow(records, undefined, now);
362
+ return buildDailySeries(records, since, until, "day").total;
376
363
  }