@deathbeam/pi-usage 0.0.12 → 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 +3 -20
- package/index.ts +113 -96
- package/package.json +1 -1
- package/src/format.ts +87 -0
- package/src/summary.ts +613 -0
- package/src/usage.ts +29 -51
package/README.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# [@deathbeam/pi-usage](https://www.npmjs.com/package/@deathbeam/pi-usage)
|
|
2
2
|
|
|
3
|
-
Use the `/usage` command for a fullscreen dashboard of token usage and cost per
|
|
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
|
+
|
|
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.
|
|
4
6
|
|
|
5
7
|
## Installation
|
|
6
8
|
|
|
@@ -10,25 +12,6 @@ pi install npm:@deathbeam/pi-usage # this package
|
|
|
10
12
|
pi install git:github.com/deathbeam/pi-packages # all my packages
|
|
11
13
|
```
|
|
12
14
|
|
|
13
|
-
## Keys
|
|
14
|
-
|
|
15
|
-
| Key | Action |
|
|
16
|
-
| --------------------- | -------------------------------------------- |
|
|
17
|
-
| Tab, Shift+Tab, ← / → | Cycle groups. Inside an open day, skip day. |
|
|
18
|
-
| `[` / `]` | Step the day when it is the innermost filter |
|
|
19
|
-
| Enter | Open the selected row |
|
|
20
|
-
| Esc | Go back, or close when at the top level |
|
|
21
|
-
| `q` | Close |
|
|
22
|
-
| ↑ / ↓, `j` / `k` | Move the cursor |
|
|
23
|
-
| Page Up / Page Down | Move by a page |
|
|
24
|
-
| `g` / `G` | Move to the first / last row |
|
|
25
|
-
|
|
26
|
-
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.
|
|
27
|
-
|
|
28
|
-
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.
|
|
29
|
-
|
|
30
|
-
Compaction and branch summaries are counted under `(summaries)`.
|
|
31
|
-
|
|
32
15
|
## Development
|
|
33
16
|
|
|
34
17
|
From the repo root:
|
package/index.ts
CHANGED
|
@@ -1,26 +1,36 @@
|
|
|
1
1
|
/** /usage — fullscreen token usage and cost dashboard. */
|
|
2
2
|
|
|
3
|
-
import { homedir } from "node:os";
|
|
4
3
|
import { basename, dirname, join } from "node:path";
|
|
5
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
|
|
6
5
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
7
6
|
import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
7
|
+
import {
|
|
8
|
+
clip,
|
|
9
|
+
deltaText,
|
|
10
|
+
displayName,
|
|
11
|
+
fitLabel,
|
|
12
|
+
formatCost,
|
|
13
|
+
formatTokens,
|
|
14
|
+
hitPct,
|
|
15
|
+
padWidth,
|
|
16
|
+
shareBar,
|
|
17
|
+
} from "./src/format.ts";
|
|
18
|
+
import { summaryLines, summaryModel, type SummaryModel } from "./src/summary.ts";
|
|
8
19
|
import {
|
|
9
20
|
buildRows,
|
|
10
21
|
cacheView,
|
|
11
22
|
collectUsage,
|
|
12
|
-
comparison,
|
|
13
23
|
dailyTotals,
|
|
14
24
|
dayKey,
|
|
15
25
|
dayWindow,
|
|
16
26
|
matchesFilter,
|
|
17
|
-
percentChange,
|
|
18
27
|
summarize,
|
|
19
28
|
usageWindow,
|
|
20
29
|
type DailyCost,
|
|
21
30
|
type GroupMode,
|
|
22
31
|
type GroupRow,
|
|
23
32
|
type Stats,
|
|
33
|
+
type Summary,
|
|
24
34
|
type UsageFilter,
|
|
25
35
|
type UsageRecord,
|
|
26
36
|
} from "./src/usage.ts";
|
|
@@ -28,19 +38,25 @@ import {
|
|
|
28
38
|
type Column = {
|
|
29
39
|
label: string;
|
|
30
40
|
width: number;
|
|
31
|
-
cell: (stats: Stats, requests: number, totalCost: number, row
|
|
41
|
+
cell: (stats: Stats, requests: number, totalCost: number, row: GroupRow | undefined, theme: Theme) => string;
|
|
32
42
|
};
|
|
33
43
|
type BodyRow = GroupRow & { parent?: string };
|
|
34
44
|
type Frame = { filters: UsageFilter[]; group: number; cursor: number; top: number };
|
|
35
45
|
type SparkBar = { label: string; char: string };
|
|
46
|
+
type ViewMode = "summary" | GroupMode;
|
|
47
|
+
type TableView = { mode: GroupMode; summary: Summary; body: BodyRow[] };
|
|
48
|
+
type SummaryView = { mode: "summary"; model: SummaryModel };
|
|
36
49
|
|
|
37
50
|
const GROUPS = ["day", "provider", "model", "project"] as const satisfies readonly GroupMode[];
|
|
51
|
+
/** Tab order; Summary is a view, not a grouping, so it has no rows to open. */
|
|
52
|
+
const VIEWS: readonly ViewMode[] = ["summary", ...GROUPS];
|
|
38
53
|
const GROUP_LABELS: Record<GroupMode, string> = {
|
|
39
54
|
day: "Day",
|
|
40
55
|
provider: "Provider",
|
|
41
56
|
model: "Model",
|
|
42
57
|
project: "Project",
|
|
43
58
|
};
|
|
59
|
+
const VIEW_LABELS: Record<ViewMode, string> = { summary: "Summary", ...GROUP_LABELS };
|
|
44
60
|
|
|
45
61
|
const COLUMNS: Column[] = [
|
|
46
62
|
{
|
|
@@ -51,42 +67,20 @@ const COLUMNS: Column[] = [
|
|
|
51
67
|
{
|
|
52
68
|
label: "Share",
|
|
53
69
|
width: 13,
|
|
54
|
-
cell: (s, _r, totalCost) =>
|
|
55
|
-
const share = totalCost > 0 ? s.cost / totalCost : 0;
|
|
56
|
-
const filled = Math.round(8 * share);
|
|
57
|
-
return "█".repeat(filled) + "·".repeat(8 - filled) + " " + `${Math.round(100 * share)}%`.padStart(4);
|
|
58
|
-
},
|
|
70
|
+
cell: (s, _r, totalCost, _row, theme) => shareBar(s.cost, totalCost, theme),
|
|
59
71
|
},
|
|
60
72
|
{ label: "Reqs", width: 6, cell: (_s, requests) => formatTokens(requests) },
|
|
61
73
|
{ label: "In", width: 7, cell: (s) => formatTokens(s.input) },
|
|
62
74
|
{ label: "Out", width: 7, cell: (s) => formatTokens(s.output) },
|
|
63
75
|
// Cost already prices read/write differently; one combined token column is enough.
|
|
64
76
|
{ label: "Cache", width: 7, cell: (s) => formatTokens(s.cacheRead + s.cacheWrite) },
|
|
65
|
-
{ label: "Hit%", width: 5, cell: (s) => hitPct(s) },
|
|
77
|
+
{ label: "Hit%", width: 5, cell: (s, _r, _t, _row, theme) => hitPct(s, theme) },
|
|
66
78
|
];
|
|
67
79
|
|
|
68
80
|
const SPARK_BARS = "▁▂▃▄▅▆▇█";
|
|
69
81
|
const MIN_NAME_WIDTH = 12;
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
if (cost === 0) return "$0.00";
|
|
73
|
-
if (cost < 0.01) return `$${cost.toFixed(4)}`;
|
|
74
|
-
if (cost < 100) return `$${cost.toFixed(2)}`;
|
|
75
|
-
return `$${Math.round(cost).toLocaleString("en-US")}`;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function formatTokens(count: number): string {
|
|
79
|
-
if (count === 0) return "-";
|
|
80
|
-
if (count < 1000) return String(count);
|
|
81
|
-
if (count < 1_000_000) return `${(count / 1000).toFixed(count < 10_000 ? 1 : 0)}k`;
|
|
82
|
-
if (count < 1_000_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
|
|
83
|
-
return `${(count / 1_000_000_000).toFixed(1)}B`;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
function hitPct(stats: Stats): string {
|
|
87
|
-
const total = stats.input + stats.cacheRead + stats.cacheWrite;
|
|
88
|
-
return total > 0 ? `${Math.round((100 * stats.cacheRead) / total)}%` : "-";
|
|
89
|
-
}
|
|
82
|
+
/** Columns the title keeps beside the tab bar; the rest goes to the tabs around the active one. */
|
|
83
|
+
const TITLE_WIDTH = 8;
|
|
90
84
|
|
|
91
85
|
function layout(width: number, allColumns: Column[]): { nameWidth: number; columns: Column[] } {
|
|
92
86
|
function used(cols: Column[]): number {
|
|
@@ -100,28 +94,13 @@ function layout(width: number, allColumns: Column[]): { nameWidth: number; colum
|
|
|
100
94
|
return { nameWidth: Math.max(4, width - used(columns)), columns };
|
|
101
95
|
}
|
|
102
96
|
|
|
103
|
-
function
|
|
104
|
-
return s + " ".repeat(Math.max(0, w - visibleWidth(s)));
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
function displayName(mode: GroupMode, name: string): string {
|
|
108
|
-
if (mode === "day") return `${name} ${new Date(`${name}T00:00`).toLocaleDateString("en-US", { weekday: "short" })}`;
|
|
109
|
-
if (mode !== "project") return name;
|
|
110
|
-
if (!name) return "(no cwd)";
|
|
111
|
-
const home = homedir();
|
|
112
|
-
return name === home || name.startsWith(home + "/") ? "~" + name.slice(home.length) : name;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/** Truncate a name to its column so ANSI codes and padding stay width-correct. */
|
|
116
|
-
function fitLabel(name: string, nameWidth: number): string {
|
|
117
|
-
return visibleWidth(name) > nameWidth ? truncateToWidth(name, nameWidth, "…") : name;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCost: number): string {
|
|
97
|
+
function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCost: number, theme: Theme): string {
|
|
121
98
|
const label = fitLabel(row.name, nameWidth);
|
|
122
99
|
return [
|
|
123
100
|
padWidth(label, nameWidth),
|
|
124
|
-
...columns.map((c) =>
|
|
101
|
+
...columns.map((c) =>
|
|
102
|
+
padWidth(fitLabel(c.cell(row.stats, row.requests, totalCost, row, theme), c.width), c.width),
|
|
103
|
+
),
|
|
125
104
|
]
|
|
126
105
|
.join(" ")
|
|
127
106
|
.trimEnd();
|
|
@@ -142,10 +121,10 @@ function sparkline(daily: DailyCost[], width: number): { first: string; last: st
|
|
|
142
121
|
};
|
|
143
122
|
}
|
|
144
123
|
|
|
145
|
-
function flatten(rows: GroupRow[], mode: GroupMode): BodyRow[] {
|
|
124
|
+
function flatten(rows: GroupRow[], mode: GroupMode, theme: Theme): BodyRow[] {
|
|
146
125
|
const body: BodyRow[] = [];
|
|
147
126
|
for (const row of rows) {
|
|
148
|
-
body.push({ ...row, name: displayName(mode, row.name) });
|
|
127
|
+
body.push({ ...row, name: displayName(mode, row.name, theme) });
|
|
149
128
|
for (const child of row.children ?? []) body.push({ ...child, name: ` ${child.name}`, parent: row.key });
|
|
150
129
|
}
|
|
151
130
|
return body;
|
|
@@ -153,7 +132,7 @@ function flatten(rows: GroupRow[], mode: GroupMode): BodyRow[] {
|
|
|
153
132
|
|
|
154
133
|
export default function (pi: ExtensionAPI) {
|
|
155
134
|
pi.registerCommand("usage", {
|
|
156
|
-
description: "Show token usage and cost
|
|
135
|
+
description: "Show token usage and cost: summary, day, provider, model and project views",
|
|
157
136
|
handler: async (_args, ctx) => {
|
|
158
137
|
if (ctx.mode !== "tui") return;
|
|
159
138
|
const state: { records?: UsageRecord[]; done: number; total: number } = {
|
|
@@ -197,17 +176,23 @@ export default function (pi: ExtensionAPI) {
|
|
|
197
176
|
function dayFilter() {
|
|
198
177
|
return filters().findLast((f) => f.mode === "day");
|
|
199
178
|
}
|
|
200
|
-
function derive(source: UsageRecord[]) {
|
|
179
|
+
function derive(source: UsageRecord[]): TableView | SummaryView {
|
|
201
180
|
const active = filters();
|
|
202
181
|
const records = source.filter((record) =>
|
|
203
182
|
active.every((f) => f.mode === "day" || matchesFilter(record, f)),
|
|
204
183
|
);
|
|
205
184
|
const day = active.findLast((f) => f.mode === "day")?.key;
|
|
206
185
|
const window = usageWindow(records, day);
|
|
207
|
-
const mode =
|
|
186
|
+
const mode = VIEWS[group]!;
|
|
187
|
+
if (mode === "summary") {
|
|
188
|
+
const scoped = records.filter(
|
|
189
|
+
(record) => record.ts >= window.since && record.ts < window.until,
|
|
190
|
+
);
|
|
191
|
+
return { mode, model: summaryModel(scoped, day === undefined, Date.now(), window) };
|
|
192
|
+
}
|
|
208
193
|
const summary = summarize(records, window.since, window.until);
|
|
209
|
-
const body = flatten(buildRows(records, window.since, mode, window.until), mode);
|
|
210
|
-
return { mode, summary, body
|
|
194
|
+
const body = flatten(buildRows(records, window.since, mode, window.until), mode, theme);
|
|
195
|
+
return { mode, summary, body };
|
|
211
196
|
}
|
|
212
197
|
const getView = cacheView(() => derive(state.records!));
|
|
213
198
|
let allDays: DailyCost[] | undefined;
|
|
@@ -222,15 +207,33 @@ export default function (pi: ExtensionAPI) {
|
|
|
222
207
|
abort.abort();
|
|
223
208
|
done(undefined);
|
|
224
209
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
210
|
+
const deltaColumn: Column = {
|
|
211
|
+
label: "Δ",
|
|
212
|
+
width: 9,
|
|
213
|
+
cell: (_s, _r, _t, row, _theme) => deltaText(row?.delta, theme),
|
|
214
|
+
};
|
|
215
|
+
/** Tabs around the active one that fit `budget`; the active tab is never dropped. */
|
|
216
|
+
function windowTabs(tabs: { text: string; active: boolean }[], budget: number): string[] {
|
|
217
|
+
const active = Math.max(
|
|
218
|
+
0,
|
|
219
|
+
tabs.findIndex((entry) => entry.active),
|
|
220
|
+
);
|
|
221
|
+
let lo = active;
|
|
222
|
+
let hi = active;
|
|
223
|
+
let used = visibleWidth(tabs[active]!.text);
|
|
224
|
+
while (true) {
|
|
225
|
+
const next = tabs[hi + 1];
|
|
226
|
+
const prev = tabs[lo - 1];
|
|
227
|
+
if (next !== undefined && used + 1 + visibleWidth(next.text) <= budget) {
|
|
228
|
+
hi += 1;
|
|
229
|
+
used += 1 + visibleWidth(next.text);
|
|
230
|
+
} else if (prev !== undefined && used + 1 + visibleWidth(prev.text) <= budget) {
|
|
231
|
+
lo -= 1;
|
|
232
|
+
used += 1 + visibleWidth(prev.text);
|
|
233
|
+
} else break;
|
|
234
|
+
}
|
|
235
|
+
return tabs.slice(lo, hi + 1).map((entry) => entry.text);
|
|
232
236
|
}
|
|
233
|
-
const deltaColumn: Column = { label: "Δ", width: 9, cell: (_s, _r, _t, row) => colorDelta(row?.delta) };
|
|
234
237
|
function title(width: number): string {
|
|
235
238
|
function tab(label: string, active: boolean): string {
|
|
236
239
|
return active ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `);
|
|
@@ -240,12 +243,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
240
243
|
filters()
|
|
241
244
|
.map((f) => ` › ${displayName(f.mode, f.key)}`)
|
|
242
245
|
.join("");
|
|
243
|
-
const tabs =
|
|
244
|
-
|
|
245
|
-
|
|
246
|
+
const tabs = VIEWS.map((g, i) => ({
|
|
247
|
+
text: g === "day" && dayFilter() ? "" : tab(VIEW_LABELS[g], i === group),
|
|
248
|
+
active: i === group,
|
|
249
|
+
})).filter((entry) => entry.text !== "");
|
|
250
|
+
const budget = Math.max(1, width - Math.min(visibleWidth(left), TITLE_WIDTH) - 1);
|
|
251
|
+
const shown = windowTabs(tabs, budget).join(" ");
|
|
246
252
|
const hint = theme.fg("dim", " (tab/←→)");
|
|
247
253
|
const right =
|
|
248
|
-
|
|
254
|
+
shown +
|
|
255
|
+
(visibleWidth(left) + visibleWidth(shown) + visibleWidth(hint) + 1 <= width ? hint : "");
|
|
249
256
|
const leftWidth = Math.max(0, width - visibleWidth(right) - 1);
|
|
250
257
|
return truncateToWidth(
|
|
251
258
|
truncateToWidth(left, leftWidth, "…") +
|
|
@@ -256,11 +263,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
256
263
|
width,
|
|
257
264
|
);
|
|
258
265
|
}
|
|
259
|
-
function footer(width: number): string {
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
266
|
+
function footer(width: number, mode?: ViewMode): string {
|
|
267
|
+
const parts = [
|
|
268
|
+
...(mode !== undefined && mode !== "summary" ? ["enter open"] : []),
|
|
269
|
+
"esc back",
|
|
270
|
+
"tab/←→ view",
|
|
271
|
+
...(dayFilter() ? ["[ ] day"] : []),
|
|
272
|
+
"q close",
|
|
273
|
+
"↑↓ scroll",
|
|
274
|
+
];
|
|
275
|
+
return truncateToWidth(theme.fg("dim", parts.join(" · ")), width);
|
|
264
276
|
}
|
|
265
277
|
return {
|
|
266
278
|
render(width: number) {
|
|
@@ -279,15 +291,22 @@ export default function (pi: ExtensionAPI) {
|
|
|
279
291
|
lines.push(rule, footer(width));
|
|
280
292
|
return lines.slice(0, rows);
|
|
281
293
|
}
|
|
282
|
-
const view = getView(
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
294
|
+
const view = getView(VIEWS[group]!, filters());
|
|
295
|
+
if (view.mode === "summary") {
|
|
296
|
+
const content = summaryLines(view.model, width, theme);
|
|
297
|
+
body = [];
|
|
298
|
+
rowCount = content.length;
|
|
299
|
+
viewHeight = Math.max(1, rows - lines.length - 2);
|
|
300
|
+
// The summary has no cursor: its position is the scroll offset.
|
|
301
|
+
cursor = Math.max(0, Math.min(cursor, Math.max(0, rowCount - viewHeight)));
|
|
302
|
+
top = cursor;
|
|
303
|
+
lines.push(...content.slice(top, top + viewHeight), rule, footer(width, view.mode));
|
|
304
|
+
return clip(lines, width, rows);
|
|
305
|
+
}
|
|
306
|
+
const { mode, summary } = view;
|
|
287
307
|
lines.push(
|
|
288
|
-
truncateToWidth(first, width),
|
|
289
308
|
truncateToWidth(
|
|
290
|
-
`
|
|
309
|
+
`Cost ${formatCost(summary.stats.cost)} · Reqs ${formatTokens(summary.requests)} · Sessions ${formatTokens(summary.sessions)} · Hit ${hitPct(summary.stats, theme)}`,
|
|
291
310
|
width,
|
|
292
311
|
),
|
|
293
312
|
);
|
|
@@ -296,23 +315,22 @@ export default function (pi: ExtensionAPI) {
|
|
|
296
315
|
cursor = Math.min(cursor, Math.max(0, rowCount - 1));
|
|
297
316
|
const selected = body[cursor];
|
|
298
317
|
const contextDay = dayFilter()?.key ?? (mode === "day" ? selected?.key : undefined);
|
|
299
|
-
const contextLabel = contextDay?.slice(5);
|
|
300
318
|
const spark = sparkline(allDaily(), width);
|
|
301
319
|
if (spark)
|
|
302
320
|
lines.push(
|
|
303
321
|
truncateToWidth(
|
|
304
|
-
theme.fg("dim", `${spark.first} `) +
|
|
322
|
+
theme.fg("dim", `${spark.first.slice(5)} `) +
|
|
305
323
|
spark.bars
|
|
306
324
|
.map((bar) =>
|
|
307
325
|
theme.fg(
|
|
308
|
-
|
|
326
|
+
contextDay === undefined || bar.label === contextDay
|
|
309
327
|
? "accent"
|
|
310
328
|
: "borderMuted",
|
|
311
329
|
bar.char,
|
|
312
330
|
),
|
|
313
331
|
)
|
|
314
332
|
.join("") +
|
|
315
|
-
theme.fg("dim", ` ${spark.last}`),
|
|
333
|
+
theme.fg("dim", ` ${spark.last.slice(5)}`),
|
|
316
334
|
width,
|
|
317
335
|
),
|
|
318
336
|
);
|
|
@@ -340,20 +358,18 @@ export default function (pi: ExtensionAPI) {
|
|
|
340
358
|
const visible = body.slice(top, top + viewHeight);
|
|
341
359
|
if (rowCount === 0) lines.push(theme.fg("dim", " No usage"));
|
|
342
360
|
for (const [i, row] of visible.entries()) {
|
|
343
|
-
let line = tableLine(nameWidth, columns, row, summary.stats.cost);
|
|
361
|
+
let line = tableLine(nameWidth, columns, row, summary.stats.cost, theme);
|
|
344
362
|
if (top + i === cursor) line = theme.bg("selectedBg", line);
|
|
345
363
|
else if (row.parent !== undefined) line = theme.fg("dim", line);
|
|
346
364
|
lines.push(line);
|
|
347
365
|
}
|
|
348
366
|
const total = { key: "", name: "Total", stats: summary.stats, requests: summary.requests };
|
|
349
367
|
lines.push(
|
|
350
|
-
theme.bold(tableLine(nameWidth, columns, total, summary.stats.cost)),
|
|
368
|
+
theme.bold(tableLine(nameWidth, columns, total, summary.stats.cost, theme)),
|
|
351
369
|
rule,
|
|
352
|
-
footer(width),
|
|
370
|
+
footer(width, mode),
|
|
353
371
|
);
|
|
354
|
-
return lines
|
|
355
|
-
.slice(0, rows)
|
|
356
|
-
.map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width) : line));
|
|
372
|
+
return clip(lines, width, rows);
|
|
357
373
|
},
|
|
358
374
|
invalidate() {},
|
|
359
375
|
handleInput(data: string) {
|
|
@@ -371,15 +387,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
371
387
|
return;
|
|
372
388
|
} else if (keys.matches(data, "tui.select.confirm") && body[cursor]) {
|
|
373
389
|
const row = body[cursor]!;
|
|
374
|
-
const
|
|
390
|
+
const mode = VIEWS[group]!;
|
|
391
|
+
const rowMode = row.parent === undefined && mode !== "summary" ? mode : "model";
|
|
375
392
|
const selected: UsageFilter[] =
|
|
376
393
|
row.parent === undefined ? [] : [{ mode: "provider", key: row.parent }];
|
|
377
394
|
selected.push({ mode: rowMode, key: row.key });
|
|
378
395
|
stack.push({ filters: selected, group, cursor, top });
|
|
379
396
|
// Land on the first grouping that is not already filtered.
|
|
380
397
|
const used = new Set(filters().map((f) => f.mode));
|
|
381
|
-
group =
|
|
382
|
-
if (group < 0) group = dayFilter() ?
|
|
398
|
+
group = VIEWS.findIndex((g) => g !== "summary" && !used.has(g));
|
|
399
|
+
if (group < 0) group = VIEWS.indexOf(dayFilter() ? "provider" : "day");
|
|
383
400
|
cursor = top = 0;
|
|
384
401
|
} else if ((data === "[" || data === "]") && filters().at(-1)?.mode === "day") {
|
|
385
402
|
const filter = filters().at(-1)!;
|
|
@@ -392,8 +409,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
392
409
|
matchesKey(data, "left")
|
|
393
410
|
) {
|
|
394
411
|
const offset = matchesKey(data, "tab") || matchesKey(data, "right") ? 1 : -1;
|
|
395
|
-
do group = (group + offset +
|
|
396
|
-
while (group ===
|
|
412
|
+
do group = (group + offset + VIEWS.length) % VIEWS.length;
|
|
413
|
+
while (VIEWS[group] === "day" && dayFilter());
|
|
397
414
|
cursor = top = 0;
|
|
398
415
|
} else if (keys.matches(data, "tui.select.up") || data === "k") cursor -= 1;
|
|
399
416
|
else if (keys.matches(data, "tui.select.down") || data === "j") cursor += 1;
|
package/package.json
CHANGED
package/src/format.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/** Text helpers shared by the table views and the Summary view. */
|
|
2
|
+
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
6
|
+
import type { GroupMode, GroupRow, Stats } from "./usage.ts";
|
|
7
|
+
|
|
8
|
+
const BAR_CELLS = 8;
|
|
9
|
+
|
|
10
|
+
export function formatCost(cost: number): string {
|
|
11
|
+
if (cost === 0) return "$0.00";
|
|
12
|
+
if (cost < 0.01) return `$${cost.toFixed(4)}`;
|
|
13
|
+
if (cost < 100) return `$${cost.toFixed(2)}`;
|
|
14
|
+
return `$${Math.round(cost).toLocaleString("en-US")}`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function formatTokens(count: number): string {
|
|
18
|
+
if (count === 0) return "-";
|
|
19
|
+
if (count < 1000) return String(count);
|
|
20
|
+
if (count < 1_000_000) return `${(count / 1000).toFixed(count < 10_000 ? 1 : 0)}k`;
|
|
21
|
+
if (count < 1_000_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
|
|
22
|
+
return `${(count / 1_000_000_000).toFixed(1)}B`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Cache reads as a share of the whole input, colored by how much of the session the cache carried. */
|
|
26
|
+
export function hitPct(stats: Stats, theme: Theme): string {
|
|
27
|
+
const total = stats.input + stats.cacheRead + stats.cacheWrite;
|
|
28
|
+
if (total === 0) return "-";
|
|
29
|
+
const pct = Math.round((100 * stats.cacheRead) / total);
|
|
30
|
+
return theme.fg(pct >= 90 ? "success" : pct >= 75 ? "warning" : "error", `${pct}%`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function padWidth(s: string, w: number): string {
|
|
34
|
+
return s + " ".repeat(Math.max(0, w - visibleWidth(s)));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Truncate a name to its column so ANSI codes and padding stay width-correct. */
|
|
38
|
+
export function fitLabel(name: string, nameWidth: number): string {
|
|
39
|
+
return visibleWidth(name) > nameWidth ? truncateToWidth(name, nameWidth, "…") : name;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Thin bar: heavy for the filled part, light for the rest, so a row reads as a line, not a block. */
|
|
43
|
+
export function shareBar(cost: number, totalCost: number, theme: Theme): string {
|
|
44
|
+
const share = totalCost > 0 ? Math.min(1, Math.max(0, cost / totalCost)) : 0;
|
|
45
|
+
const halves = Math.round(share * BAR_CELLS * 2);
|
|
46
|
+
const full = Math.floor(halves / 2);
|
|
47
|
+
const half = halves % 2 === 1 ? "╸" : "";
|
|
48
|
+
return (
|
|
49
|
+
theme.fg("accent", "━".repeat(full) + half) +
|
|
50
|
+
theme.fg("borderMuted", "─".repeat(BAR_CELLS - full - half.length)) +
|
|
51
|
+
" " +
|
|
52
|
+
`${Math.round(100 * share)}%`.padStart(4)
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** One top list row: name, share bar and cost. */
|
|
57
|
+
export function topLine(row: GroupRow, totalCost: number, nameWidth: number, theme: Theme): string {
|
|
58
|
+
return [
|
|
59
|
+
padWidth(fitLabel(row.name, nameWidth), nameWidth),
|
|
60
|
+
shareBar(row.stats.cost, totalCost, theme),
|
|
61
|
+
formatCost(row.stats.cost).padStart(9),
|
|
62
|
+
].join(" ");
|
|
63
|
+
}
|
|
64
|
+
/** `theme` marks a weekend day; the breadcrumb and list callers leave the weekday suffix plain. */
|
|
65
|
+
export function displayName(mode: GroupMode, name: string, theme?: Theme): string {
|
|
66
|
+
if (mode === "day") {
|
|
67
|
+
const weekday = new Date(`${name}T00:00`).toLocaleDateString("en-US", { weekday: "short" });
|
|
68
|
+
if (theme === undefined || (weekday !== "Sat" && weekday !== "Sun")) return `${name} ${weekday}`;
|
|
69
|
+
return `${name} ${theme.fg("accent", weekday)}`;
|
|
70
|
+
}
|
|
71
|
+
if (mode !== "project") return name;
|
|
72
|
+
if (!name) return "(no cwd)";
|
|
73
|
+
const home = homedir();
|
|
74
|
+
return name === home || name.startsWith(home + "/") ? "~" + name.slice(home.length) : name;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Rise in red, fall in green: the money spent, not the money saved. */
|
|
78
|
+
export function deltaText(delta: number | undefined, theme: Theme): string {
|
|
79
|
+
if (delta === undefined) return "-";
|
|
80
|
+
if (delta === 0) return "0%";
|
|
81
|
+
const text = Number.isFinite(delta) ? `${delta > 0 ? "▲" : "▼"}${Math.round(Math.abs(delta))}%` : "▲new";
|
|
82
|
+
return theme.fg(delta > 0 ? "error" : "success", text);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function clip(lines: string[], width: number, rows: number): string[] {
|
|
86
|
+
return lines.slice(0, rows).map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width) : line));
|
|
87
|
+
}
|
package/src/summary.ts
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
/** The Summary view: data model (totals, trends, streaks, calendar, top lists) and its layout. */
|
|
2
|
+
|
|
3
|
+
import { basename } from "node:path";
|
|
4
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { visibleWidth } from "@earendil-works/pi-tui";
|
|
6
|
+
import { deltaText, displayName, formatCost, formatTokens, hitPct, padWidth, topLine } from "./format.ts";
|
|
7
|
+
import {
|
|
8
|
+
buildRows,
|
|
9
|
+
comparison,
|
|
10
|
+
dailyTotals,
|
|
11
|
+
dayKey,
|
|
12
|
+
percentChange,
|
|
13
|
+
summarize,
|
|
14
|
+
type DailyCost,
|
|
15
|
+
type GroupMode,
|
|
16
|
+
type GroupRow,
|
|
17
|
+
type Stats,
|
|
18
|
+
type TimeWindow,
|
|
19
|
+
type UsageRecord,
|
|
20
|
+
} from "./usage.ts";
|
|
21
|
+
|
|
22
|
+
export type Streaks = { current: number; longest: number };
|
|
23
|
+
|
|
24
|
+
/** `level` is 0 for a day without usage and 1..4 for its cost on a log scale. */
|
|
25
|
+
export type HeatCell = { cost: number; level: number };
|
|
26
|
+
|
|
27
|
+
/** `rows[weekday][week]`, Monday first; a cell is undefined outside the recorded range. */
|
|
28
|
+
export type Heatmap = { header: string; rows: (HeatCell | undefined)[][] };
|
|
29
|
+
|
|
30
|
+
export type Trends = {
|
|
31
|
+
today: number;
|
|
32
|
+
/** Totals and per-day spend so far this week and this month, against the previous ones. */
|
|
33
|
+
week: number;
|
|
34
|
+
weekTotal: number;
|
|
35
|
+
weekDelta: number;
|
|
36
|
+
month: number;
|
|
37
|
+
monthTotal: number;
|
|
38
|
+
monthDelta: number;
|
|
39
|
+
lastMonthTotal: number;
|
|
40
|
+
/** This month's per-day average spread over every day of the month. */
|
|
41
|
+
projection: number;
|
|
42
|
+
};
|
|
43
|
+
|
|
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 };
|
|
53
|
+
|
|
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 };
|
|
57
|
+
type List = { title: string; mode?: GroupMode; rows: GroupRow[] };
|
|
58
|
+
type Section = { title: string; maxColumns: number; cells: (width: number) => Cell[] };
|
|
59
|
+
|
|
60
|
+
export type SummaryModel = {
|
|
61
|
+
stats: Stats;
|
|
62
|
+
requests: number;
|
|
63
|
+
sessions: number;
|
|
64
|
+
activeDays: number;
|
|
65
|
+
perDay: number;
|
|
66
|
+
perSession: number;
|
|
67
|
+
streak: Streaks;
|
|
68
|
+
busiest?: DailyCost;
|
|
69
|
+
/** One entry per local day of the active window. */
|
|
70
|
+
daily: DailyCost[];
|
|
71
|
+
/** Absent when a single day is in context: there is nothing to compare it with. */
|
|
72
|
+
trends?: Trends;
|
|
73
|
+
top: TopLists;
|
|
74
|
+
delegates: Delegates;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const WEEKDAYS = ["Mon", "", "Wed", "", "Fri", "", ""];
|
|
78
|
+
/** Empty first, then four steps: glyph and hue both rise, so a level reads without color. */
|
|
79
|
+
const HEAT_LEVELS = [
|
|
80
|
+
{ glyph: "·", color: "borderMuted" },
|
|
81
|
+
{ glyph: "▪", color: "muted" },
|
|
82
|
+
{ glyph: "■", color: "text" },
|
|
83
|
+
{ glyph: "■", color: "warning" },
|
|
84
|
+
{ glyph: "■", color: "error" },
|
|
85
|
+
] as const;
|
|
86
|
+
const INDENT = " ";
|
|
87
|
+
const COLUMN_GAP = 3;
|
|
88
|
+
/** pi-delegate children persist their own sessions under this id prefix. */
|
|
89
|
+
const DELEGATE_PREFIX = "delegate-";
|
|
90
|
+
/** Narrowest a section may get before it is stacked instead of placed beside another. */
|
|
91
|
+
const MIN_SECTION_WIDTH = 44;
|
|
92
|
+
/** Longest a name column grows; a longer list would push the bar too far from the name. */
|
|
93
|
+
const MAX_NAME_WIDTH = 30;
|
|
94
|
+
/** Space the bar and the cost take in a top list row. */
|
|
95
|
+
const LIST_OVERHEAD = 24;
|
|
96
|
+
/** Two lists share a row while each keeps its names readable. */
|
|
97
|
+
const LISTS_PER_ROW = 2;
|
|
98
|
+
|
|
99
|
+
function emptyStats(): Stats {
|
|
100
|
+
return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function trends(records: UsageRecord[], now: number): Trends {
|
|
104
|
+
const compare = comparison(records, now);
|
|
105
|
+
const date = new Date(now);
|
|
106
|
+
const monthDays = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
|
|
107
|
+
return {
|
|
108
|
+
today: compare.today,
|
|
109
|
+
week: compare.week,
|
|
110
|
+
weekTotal: compare.weekTotal,
|
|
111
|
+
weekDelta: percentChange(compare.week, compare.lastWeek),
|
|
112
|
+
month: compare.month,
|
|
113
|
+
monthTotal: compare.monthTotal,
|
|
114
|
+
monthDelta: percentChange(compare.month, compare.lastMonth),
|
|
115
|
+
lastMonthTotal: compare.lastMonthTotal,
|
|
116
|
+
projection: compare.month * monthDays,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function heading(theme: Theme, text: string): string {
|
|
121
|
+
return theme.fg("accent", theme.bold(text));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Bold value; `accent` marks the headline number of its block. */
|
|
125
|
+
function cellValue(text: string, accent: boolean, theme: Theme): string {
|
|
126
|
+
const value = theme.bold(text);
|
|
127
|
+
return accent ? theme.fg("accent", value) : value;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** `labelWidth` pads the labels of a column so its values line up. */
|
|
131
|
+
function cellText(cell: Cell, theme: Theme, labelWidth = visibleWidth(cell.label)): string {
|
|
132
|
+
return theme.fg("muted", padWidth(cell.label, labelWidth)) + " " + cell.value;
|
|
133
|
+
}
|
|
134
|
+
|
|
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
|
+
}
|
|
142
|
+
const widths = Array.from({ length: count }, () => 0);
|
|
143
|
+
for (const [index, cell] of cells.entries()) {
|
|
144
|
+
const column = index % count;
|
|
145
|
+
widths[column] = Math.max(widths[column]!, visibleWidth(cellText(cell, theme, labels[column]!)) + COLUMN_GAP);
|
|
146
|
+
}
|
|
147
|
+
return labels.map((label, column) => ({ label, width: widths[column]! }));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Label/value pairs in as many aligned columns as `maxColumns` and the width allow. */
|
|
151
|
+
function grid(cells: Cell[], width: number, maxColumns: number, theme: Theme): string[] {
|
|
152
|
+
for (let count = Math.min(cells.length, maxColumns); count > 0; count--) {
|
|
153
|
+
const columns = gridColumns(cells, count, theme);
|
|
154
|
+
const used = columns.reduce((sum, column) => sum + column.width, 0) - COLUMN_GAP;
|
|
155
|
+
if (count > 1 && used > width) continue;
|
|
156
|
+
const rows: string[] = [];
|
|
157
|
+
for (let start = 0; start < cells.length; start += count) {
|
|
158
|
+
rows.push(
|
|
159
|
+
cells
|
|
160
|
+
.slice(start, start + count)
|
|
161
|
+
.map((cell, column) =>
|
|
162
|
+
padWidth(cellText(cell, theme, columns[column]!.label), columns[column]!.width),
|
|
163
|
+
)
|
|
164
|
+
.join("")
|
|
165
|
+
.trimEnd(),
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
return rows;
|
|
169
|
+
}
|
|
170
|
+
return [];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function indent(rows: string[]): string[] {
|
|
174
|
+
return rows.map((row) => INDENT + row);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Month labels over the week columns; a label too close to the next one is dropped instead of colliding. */
|
|
178
|
+
function monthHeader(months: (string | undefined)[], weeks: number): string {
|
|
179
|
+
const chars = Array.from({ length: 4 + weeks * 2 }, () => " ");
|
|
180
|
+
const labels: { start: number; text: string }[] = [];
|
|
181
|
+
for (const [week, month] of months.entries()) if (month) labels.push({ start: 4 + week * 2, text: month });
|
|
182
|
+
for (const [index, label] of labels.entries()) {
|
|
183
|
+
const next = labels[index + 1];
|
|
184
|
+
const end = label.start + label.text.length;
|
|
185
|
+
// One space between labels reads as no gap in a terminal, so each label needs a column of its own.
|
|
186
|
+
if (next !== undefined && next.start - end < 2) continue;
|
|
187
|
+
// The last label may run past the grid: a one-day calendar has only one 2-wide column for `Sep`.
|
|
188
|
+
for (const [i, char] of Array.from(label.text).entries()) chars[label.start + i] = char;
|
|
189
|
+
}
|
|
190
|
+
return chars.join("").trimEnd();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** `05-21 Wed` for a `YYYY-MM-DD` key, matching the sparkline and session list dates. */
|
|
194
|
+
function dayName(key: string): string {
|
|
195
|
+
const weekday = new Date(`${key}T00:00`).toLocaleDateString("en-US", { weekday: "short" });
|
|
196
|
+
return `${key.slice(5)} ${weekday}`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function activity(daily: DailyCost[], width: number, theme: Theme): string[] {
|
|
200
|
+
const weeks = Math.max(1, Math.min(53, Math.floor((width - 4) / 2)));
|
|
201
|
+
const heat = heatmap(daily, weeks);
|
|
202
|
+
const rows = [theme.fg("dim", heat.header)];
|
|
203
|
+
for (const [weekday, row] of heat.rows.entries()) {
|
|
204
|
+
// A one-day window leaves six empty rows; skip them instead of printing bare weekday labels.
|
|
205
|
+
if (row.every((cell) => cell === undefined)) continue;
|
|
206
|
+
const label = WEEKDAYS[weekday]!;
|
|
207
|
+
let line = label ? theme.fg("dim", label.padEnd(4)) : " ".repeat(4);
|
|
208
|
+
for (const cell of row) {
|
|
209
|
+
if (cell === undefined) line += " ";
|
|
210
|
+
else {
|
|
211
|
+
const level = HEAT_LEVELS[cell.level]!;
|
|
212
|
+
line += theme.fg(level.color, `${level.glyph} `);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
rows.push(line.trimEnd());
|
|
216
|
+
}
|
|
217
|
+
const legend = HEAT_LEVELS.map((level) => theme.fg(level.color, level.glyph)).join(" ");
|
|
218
|
+
rows.push(theme.fg("dim", "less ") + legend + theme.fg("dim", " more"));
|
|
219
|
+
return rows;
|
|
220
|
+
}
|
|
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
|
+
|
|
233
|
+
/** Cost, volume and token cells; one group per column so the three start side by side. */
|
|
234
|
+
function kpiGroups(model: SummaryModel, theme: Theme): Cell[][] {
|
|
235
|
+
const { stats } = model;
|
|
236
|
+
return [
|
|
237
|
+
[
|
|
238
|
+
{ label: "Total", value: cellValue(formatCost(stats.cost), true, theme) },
|
|
239
|
+
{ label: "Per day", value: cellValue(formatCost(model.perDay), false, theme) },
|
|
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
|
+
},
|
|
248
|
+
],
|
|
249
|
+
[
|
|
250
|
+
{ label: "Reqs", value: cellValue(formatTokens(model.requests), false, theme) },
|
|
251
|
+
{ label: "Sessions", value: cellValue(formatTokens(model.sessions), false, theme) },
|
|
252
|
+
{ label: "Active days", value: cellValue(formatTokens(model.activeDays), false, theme) },
|
|
253
|
+
],
|
|
254
|
+
[
|
|
255
|
+
{ label: "In", value: cellValue(formatTokens(stats.input), false, theme) },
|
|
256
|
+
{ label: "Out", value: cellValue(formatTokens(stats.output), false, theme) },
|
|
257
|
+
// shortcut: no per-model price table, so cache savings show as the read/write split, not dollars.
|
|
258
|
+
{ label: "Cache R", value: cellValue(formatTokens(stats.cacheRead), false, theme) },
|
|
259
|
+
{ label: "Cache W", value: cellValue(formatTokens(stats.cacheWrite), false, theme) },
|
|
260
|
+
{ label: "Hit", value: cellValue(hitPct(stats, theme), false, theme) },
|
|
261
|
+
],
|
|
262
|
+
];
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Column-major: each group is a column with its labels padded, so every value in a column lines up. */
|
|
266
|
+
function kpiBlock(groups: Cell[][], width: number, theme: Theme): string[] {
|
|
267
|
+
const labelWidths = groups.map((group) => Math.max(...group.map((cell) => visibleWidth(cell.label))));
|
|
268
|
+
const widths = groups.map(
|
|
269
|
+
(group, column) =>
|
|
270
|
+
Math.max(...group.map((cell) => visibleWidth(cellText(cell, theme, labelWidths[column]!)))) + COLUMN_GAP,
|
|
271
|
+
);
|
|
272
|
+
if (widths.reduce((sum, column) => sum + column, 0) - COLUMN_GAP > width)
|
|
273
|
+
return groups.flatMap((group) => grid(group, width, group.length, theme));
|
|
274
|
+
const height = Math.max(...groups.map((group) => group.length));
|
|
275
|
+
return Array.from({ length: height }, (_, row) =>
|
|
276
|
+
groups
|
|
277
|
+
.map((group, column) =>
|
|
278
|
+
padWidth(
|
|
279
|
+
group[row] === undefined ? "" : cellText(group[row]!, theme, labelWidths[column]!),
|
|
280
|
+
widths[column]!,
|
|
281
|
+
),
|
|
282
|
+
)
|
|
283
|
+
.join("")
|
|
284
|
+
.trimEnd(),
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Total, then per day, then the change against the previous period. */
|
|
289
|
+
function trendRows(model: SummaryModel, theme: Theme): TrendRow[] {
|
|
290
|
+
const trends = model.trends!;
|
|
291
|
+
return [
|
|
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
|
+
},
|
|
312
|
+
];
|
|
313
|
+
}
|
|
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
|
+
|
|
336
|
+
function days(count: number): string {
|
|
337
|
+
return `${count} ${count === 1 ? "day" : "days"}`;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function listName(list: List, row: GroupRow): string {
|
|
341
|
+
return list.mode === undefined ? row.name : displayName(list.mode, row.name);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function listBlock(list: List, totalCost: number, width: number, theme: Theme): string[] {
|
|
345
|
+
const bodyWidth = Math.max(1, width - INDENT.length);
|
|
346
|
+
const nameWidth = Math.max(6, Math.min(MAX_NAME_WIDTH, bodyWidth - LIST_OVERHEAD));
|
|
347
|
+
return [
|
|
348
|
+
heading(theme, list.title),
|
|
349
|
+
...indent(list.rows.map((row) => topLine({ ...row, name: listName(list, row) }, totalCost, nameWidth, theme))),
|
|
350
|
+
];
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** A list's width when its longest name keeps its space next to the bar and the cost. */
|
|
354
|
+
function listWidth(list: List, width: number): number {
|
|
355
|
+
const longest = Math.max(0, ...list.rows.map((row) => visibleWidth(listName(list, row))));
|
|
356
|
+
return Math.min(width, INDENT.length + Math.min(MAX_NAME_WIDTH, longest) + LIST_OVERHEAD);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Widths for `count` blocks sharing a row, the last one taking the rounding remainder. */
|
|
360
|
+
function rowWidths(width: number, count: number): number[] {
|
|
361
|
+
const share = Math.floor((width - COLUMN_GAP * (count - 1)) / count);
|
|
362
|
+
return Array.from({ length: count }, (_, column) =>
|
|
363
|
+
column === count - 1 ? width - (share + COLUMN_GAP) * (count - 1) : share,
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** One row of already rendered blocks, each padded to its column width. */
|
|
368
|
+
function sideBySide(blocks: string[][], widths: number[]): string[] {
|
|
369
|
+
const height = Math.max(...blocks.map((block) => block.length));
|
|
370
|
+
const lines: string[] = [];
|
|
371
|
+
for (let line = 0; line < height; line++)
|
|
372
|
+
lines.push(
|
|
373
|
+
blocks
|
|
374
|
+
.map((block, column) => padWidth(block[line] ?? "", widths[column]!))
|
|
375
|
+
.join(" ".repeat(COLUMN_GAP))
|
|
376
|
+
.trimEnd(),
|
|
377
|
+
);
|
|
378
|
+
return lines;
|
|
379
|
+
}
|
|
380
|
+
|
|
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[] {
|
|
383
|
+
return sideBySide(
|
|
384
|
+
lists.map((list, column) => listBlock(list, totalCost, widths[column]!, theme)),
|
|
385
|
+
widths,
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
|
|
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. */
|
|
399
|
+
function sections(items: Section[], width: number, theme: Theme): string[] {
|
|
400
|
+
const count = Math.max(
|
|
401
|
+
1,
|
|
402
|
+
Math.min(items.length, Math.floor((width + COLUMN_GAP) / (MIN_SECTION_WIDTH + COLUMN_GAP))),
|
|
403
|
+
);
|
|
404
|
+
const lines: string[] = [];
|
|
405
|
+
for (let start = 0; start < items.length; start += count) {
|
|
406
|
+
if (lines.length > 0) lines.push("");
|
|
407
|
+
const row = items.slice(start, start + count);
|
|
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);
|
|
417
|
+
lines.push(
|
|
418
|
+
...sideBySide(
|
|
419
|
+
row.map((section, column) => sectionBlock(section, share[column]!, theme)),
|
|
420
|
+
share,
|
|
421
|
+
),
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
return lines;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function streakCells(model: SummaryModel, theme: Theme): Cell[] {
|
|
428
|
+
return [
|
|
429
|
+
{ label: "Current", value: cellValue(days(model.streak.current), false, theme) },
|
|
430
|
+
{ label: "Longest", value: cellValue(days(model.streak.longest), false, theme) },
|
|
431
|
+
{
|
|
432
|
+
label: "Busiest",
|
|
433
|
+
value: cellValue(
|
|
434
|
+
model.busiest ? `${dayName(model.busiest.label)} ${formatCost(model.busiest.cost)}` : "-",
|
|
435
|
+
false,
|
|
436
|
+
theme,
|
|
437
|
+
),
|
|
438
|
+
},
|
|
439
|
+
];
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Consecutive active days; `daily` must be contiguous days ending today, so the trailing run is current. */
|
|
443
|
+
export function streaks(daily: DailyCost[]): Streaks {
|
|
444
|
+
let longest = 0;
|
|
445
|
+
let run = 0;
|
|
446
|
+
for (const day of daily) {
|
|
447
|
+
run = day.cost > 0 ? run + 1 : 0;
|
|
448
|
+
longest = Math.max(longest, run);
|
|
449
|
+
}
|
|
450
|
+
return { current: run, longest };
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export function busiestDay(daily: DailyCost[]): DailyCost | undefined {
|
|
454
|
+
let best: DailyCost | undefined;
|
|
455
|
+
for (const day of daily) {
|
|
456
|
+
if (day.cost > 0 && (best === undefined || day.cost > best.cost)) best = day;
|
|
457
|
+
}
|
|
458
|
+
return best;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** `level` rises with cost on a log scale, so a few expensive days do not flatten every other day. */
|
|
462
|
+
function heatLevel(cost: number, max: number): number {
|
|
463
|
+
if (cost <= 0 || max <= 0) return 0;
|
|
464
|
+
return Math.min(4, Math.max(1, Math.ceil((4 * Math.log1p(cost)) / Math.log1p(max))));
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Local date of a daily label; totals use `YYYY-MM-DD`, tests and callers may pass a bare `MM-DD`. */
|
|
468
|
+
function labelDate(label: string, now: number): Date {
|
|
469
|
+
const full = label.length === 10 ? label : `${new Date(now).getFullYear()}-${label}`;
|
|
470
|
+
return new Date(`${full}T00:00`);
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** `weeks` is the space available; the grid shrinks to the recorded history and ends on its last day. */
|
|
474
|
+
export function heatmap(daily: DailyCost[], weeks: number, now = Date.now()): Heatmap {
|
|
475
|
+
const last = daily.length - 1;
|
|
476
|
+
const end = last >= 0 ? labelDate(daily[last]!.label, now) : new Date(now);
|
|
477
|
+
const today = (end.getDay() + 6) % 7; // Monday = 0
|
|
478
|
+
const columns = Math.max(1, Math.min(weeks, Math.ceil((daily.length + today) / 7)));
|
|
479
|
+
const first = last - today - 7 * (columns - 1);
|
|
480
|
+
const max = daily.reduce((top, day) => Math.max(top, day.cost), 0);
|
|
481
|
+
const rows: (HeatCell | undefined)[][] = [[], [], [], [], [], [], []];
|
|
482
|
+
for (let weekday = 0; weekday < 7; weekday++) {
|
|
483
|
+
for (let week = 0; week < columns; week++) {
|
|
484
|
+
const index = first + week * 7 + weekday;
|
|
485
|
+
if (index < 0 || index > last) {
|
|
486
|
+
rows[weekday]!.push(undefined);
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
const { cost } = daily[index]!;
|
|
490
|
+
rows[weekday]!.push({ cost, level: heatLevel(cost, max) });
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
const months: (string | undefined)[] = [];
|
|
494
|
+
let month = -1;
|
|
495
|
+
for (let week = 0; week < columns; week++) {
|
|
496
|
+
// The week starts on its Monday, but a one-day column shows only its day, so label the first day it shows.
|
|
497
|
+
const date = labelDate(daily[Math.max(0, first + week * 7)]!.label, now);
|
|
498
|
+
months.push(date.getMonth() === month ? undefined : date.toLocaleDateString("en-US", { month: "short" }));
|
|
499
|
+
month = date.getMonth();
|
|
500
|
+
}
|
|
501
|
+
return { header: monthHeader(months, columns), rows };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Top groups by cost, in the same shape the table views use. */
|
|
505
|
+
export function topGroups(
|
|
506
|
+
records: UsageRecord[],
|
|
507
|
+
since: number,
|
|
508
|
+
until: number,
|
|
509
|
+
mode: GroupMode,
|
|
510
|
+
count = 5,
|
|
511
|
+
): GroupRow[] {
|
|
512
|
+
return buildRows(records, since, mode, until).slice(0, count);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Sessions have no grouping of their own; the name pairs the start date with a short id and the project. */
|
|
516
|
+
export function topSessions(records: UsageRecord[], since: number, until: number, count = 5): GroupRow[] {
|
|
517
|
+
const sessions = new Map<string, { cwd: string; start: number; stats: Stats; requests: number }>();
|
|
518
|
+
for (const record of records) {
|
|
519
|
+
if (record.ts < since || record.ts >= until) continue;
|
|
520
|
+
let session = sessions.get(record.sessionId);
|
|
521
|
+
if (!session)
|
|
522
|
+
sessions.set(
|
|
523
|
+
record.sessionId,
|
|
524
|
+
(session = { cwd: record.cwd, start: record.ts, stats: emptyStats(), requests: 0 }),
|
|
525
|
+
);
|
|
526
|
+
session.start = Math.min(session.start, record.ts);
|
|
527
|
+
session.stats.cost += record.cost;
|
|
528
|
+
session.stats.input += record.input;
|
|
529
|
+
session.stats.output += record.output;
|
|
530
|
+
session.stats.cacheRead += record.cacheRead;
|
|
531
|
+
session.stats.cacheWrite += record.cacheWrite;
|
|
532
|
+
session.requests += record.requests;
|
|
533
|
+
}
|
|
534
|
+
return [...sessions]
|
|
535
|
+
.map(([id, session]) => ({
|
|
536
|
+
key: id,
|
|
537
|
+
// The id identifies the session, so it comes before the project and survives a truncated name.
|
|
538
|
+
name: `${dayKey(session.start).slice(5)} ${id.slice(0, 6)} ${basename(session.cwd) || "(no cwd)"}`,
|
|
539
|
+
stats: session.stats,
|
|
540
|
+
requests: session.requests,
|
|
541
|
+
}))
|
|
542
|
+
.sort((a, b) => b.stats.cost - a.stats.cost || b.requests - a.requests)
|
|
543
|
+
.slice(0, count);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* The whole Summary view as data. `records` is the active set: drill-down filters already applied and
|
|
548
|
+
* `window` is the day or history it covers, so a single day in context yields a one-day calendar.
|
|
549
|
+
*/
|
|
550
|
+
export function summaryModel(
|
|
551
|
+
records: UsageRecord[],
|
|
552
|
+
withTrends = true,
|
|
553
|
+
now = Date.now(),
|
|
554
|
+
window?: TimeWindow,
|
|
555
|
+
): SummaryModel {
|
|
556
|
+
const summary = summarize(records);
|
|
557
|
+
const daily = dailyTotals(records, window, now);
|
|
558
|
+
const activeDays = daily.filter((day) => day.cost > 0).length;
|
|
559
|
+
return {
|
|
560
|
+
stats: summary.stats,
|
|
561
|
+
requests: summary.requests,
|
|
562
|
+
sessions: summary.sessions,
|
|
563
|
+
activeDays,
|
|
564
|
+
perDay: activeDays > 0 ? summary.stats.cost / activeDays : 0,
|
|
565
|
+
perSession: summary.sessions > 0 ? summary.stats.cost / summary.sessions : 0,
|
|
566
|
+
streak: streaks(daily),
|
|
567
|
+
busiest: busiestDay(daily),
|
|
568
|
+
daily,
|
|
569
|
+
trends: withTrends ? trends(records, now) : undefined,
|
|
570
|
+
top: {
|
|
571
|
+
models: topGroups(records, 0, Infinity, "model"),
|
|
572
|
+
providers: topGroups(records, 0, Infinity, "provider"),
|
|
573
|
+
projects: topGroups(records, 0, Infinity, "project"),
|
|
574
|
+
sessions: topSessions(records, 0, Infinity),
|
|
575
|
+
},
|
|
576
|
+
delegates: delegateSplit(records),
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
export function summaryLines(model: SummaryModel, width: number, theme: Theme): string[] {
|
|
581
|
+
const bodyWidth = Math.max(1, width - INDENT.length);
|
|
582
|
+
const lines = [heading(theme, "Overview"), ...indent(kpiBlock(kpiGroups(model, theme), bodyWidth, theme))];
|
|
583
|
+
const items: Section[] = [];
|
|
584
|
+
if (model.trends) items.push({ title: "Trends", maxColumns: 1, cells: (w) => trendCells(model, w, theme) });
|
|
585
|
+
items.push({ title: "Streaks", maxColumns: 1, cells: () => streakCells(model, theme) });
|
|
586
|
+
lines.push("", ...sections(items, width, theme));
|
|
587
|
+
if (model.daily.length > 0) {
|
|
588
|
+
lines.push("", heading(theme, "Activity"), ...indent(activity(model.daily, bodyWidth, theme)));
|
|
589
|
+
}
|
|
590
|
+
const lists = (
|
|
591
|
+
[
|
|
592
|
+
{ title: "Models", mode: "model", rows: model.top.models },
|
|
593
|
+
{ title: "Providers", mode: "provider", rows: model.top.providers },
|
|
594
|
+
{ title: "Projects", mode: "project", rows: model.top.projects },
|
|
595
|
+
{ title: "Sessions", rows: model.top.sessions },
|
|
596
|
+
] satisfies List[]
|
|
597
|
+
).filter((list) => list.rows.length > 0);
|
|
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));
|
|
611
|
+
}
|
|
612
|
+
return lines;
|
|
613
|
+
}
|
package/src/usage.ts
CHANGED
|
@@ -55,10 +55,11 @@ export type Summary = {
|
|
|
55
55
|
};
|
|
56
56
|
|
|
57
57
|
export type DailyCost = { label: string; cost: number };
|
|
58
|
+
export type TimeWindow = { since: number; until: number };
|
|
58
59
|
|
|
59
|
-
type Tally = { stats: Stats; requests: number; models?: Map<string, Tally
|
|
60
|
+
type Tally = { stats: Stats; requests: number; models?: Map<string, Tally> };
|
|
60
61
|
|
|
61
|
-
const CACHE_VERSION =
|
|
62
|
+
const CACHE_VERSION = 5;
|
|
62
63
|
|
|
63
64
|
function emptyStats(): Stats {
|
|
64
65
|
return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
@@ -125,8 +126,9 @@ async function sessionFiles(dir: string, out: string[]): Promise<void> {
|
|
|
125
126
|
}
|
|
126
127
|
for (const entry of entries) {
|
|
127
128
|
const path = join(dir, entry.name);
|
|
128
|
-
if (entry.isDirectory())
|
|
129
|
-
|
|
129
|
+
if (entry.isDirectory()) {
|
|
130
|
+
await sessionFiles(path, out);
|
|
131
|
+
} else if (entry.name.endsWith(".jsonl")) out.push(path);
|
|
130
132
|
}
|
|
131
133
|
}
|
|
132
134
|
|
|
@@ -198,10 +200,9 @@ async function parseFile(file: string): Promise<UsageRecord[]> {
|
|
|
198
200
|
provider = String(entry.provider);
|
|
199
201
|
model = String(entry.model);
|
|
200
202
|
} else {
|
|
201
|
-
// Compaction and branch-summary calls carry no model, so their cost gets its own row.
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
model = String(message?.model || entry.model || entry.type || "unknown");
|
|
203
|
+
// Compaction and branch-summary calls carry no model, so their cost gets its own row.
|
|
204
|
+
provider = "(summaries)";
|
|
205
|
+
model = String(entry.type || "unknown");
|
|
205
206
|
}
|
|
206
207
|
const cost = typeof usage.cost === "number" ? usage.cost : num(usage.cost?.total);
|
|
207
208
|
const input = num(usage.input);
|
|
@@ -234,9 +235,8 @@ async function parseFile(file: string): Promise<UsageRecord[]> {
|
|
|
234
235
|
* Files are streamed line by line: the corpus is gigabytes, and reading whole files stalls the event
|
|
235
236
|
* loop and spikes RSS. The recursive scan includes `sessions/delegates`, where pi-delegate children
|
|
236
237
|
* write their own transcripts, so subagent usage is counted with full provider/model attribution and
|
|
237
|
-
* its own cwd.
|
|
238
|
-
*
|
|
239
|
-
* ignored for the same reason: those children also persist their own session files inside the scan.
|
|
238
|
+
* its own cwd. toolResult usage is ignored: those children persist their own session files inside
|
|
239
|
+
* the scan, so counting it would double their cost.
|
|
240
240
|
*
|
|
241
241
|
* shortcut: a file rewritten with the same size and mtime is not re-parsed.
|
|
242
242
|
* shortcut: usage reported by tools whose child sessions live outside this dir is not counted.
|
|
@@ -286,8 +286,9 @@ export async function collectUsage(
|
|
|
286
286
|
|
|
287
287
|
export function cacheView<T>(derive: () => T) {
|
|
288
288
|
let cached: { key: string; value: T } | undefined;
|
|
289
|
-
|
|
290
|
-
|
|
289
|
+
// `scope` is a grouping mode or the name of a non-grouping view.
|
|
290
|
+
return (scope: string, filters: UsageFilter[], now = Date.now()): T => {
|
|
291
|
+
const key = JSON.stringify([scope, filters, dayKey(now)]);
|
|
291
292
|
if (!cached || cached.key !== key) cached = { key, value: derive() };
|
|
292
293
|
return cached.value;
|
|
293
294
|
};
|
|
@@ -304,7 +305,7 @@ export function startOfDay(ts: number): number {
|
|
|
304
305
|
return date.getTime();
|
|
305
306
|
}
|
|
306
307
|
|
|
307
|
-
export function dayWindow(key: string, offset = 0):
|
|
308
|
+
export function dayWindow(key: string, offset = 0): TimeWindow {
|
|
308
309
|
const date = new Date(`${key}T00:00`);
|
|
309
310
|
date.setDate(date.getDate() + offset);
|
|
310
311
|
const since = startOfDay(date.getTime());
|
|
@@ -330,7 +331,7 @@ export function matchesFilter(record: UsageRecord, filter: UsageFilter): boolean
|
|
|
330
331
|
return recordKey(record, filter.mode) === filter.key;
|
|
331
332
|
}
|
|
332
333
|
|
|
333
|
-
export function usageWindow(records: UsageRecord[], day?: string, now = Date.now()) {
|
|
334
|
+
export function usageWindow(records: UsageRecord[], day?: string, now = Date.now()): TimeWindow {
|
|
334
335
|
if (day) return dayWindow(day);
|
|
335
336
|
const until = dayWindow(dayKey(now)).until;
|
|
336
337
|
let first = Infinity;
|
|
@@ -365,9 +366,12 @@ export function comparison(records: UsageRecord[], now = Date.now()) {
|
|
|
365
366
|
return {
|
|
366
367
|
today: todayCost,
|
|
367
368
|
week: weekCost / windowDays(weekStart, until),
|
|
369
|
+
weekTotal: weekCost,
|
|
368
370
|
lastWeek: lastWeekCost / 7,
|
|
369
371
|
month: monthCost / windowDays(monthStart, until),
|
|
372
|
+
monthTotal: monthCost,
|
|
370
373
|
lastMonth: lastMonthCost / windowDays(lastMonth, monthStart),
|
|
374
|
+
lastMonthTotal: lastMonthCost,
|
|
371
375
|
};
|
|
372
376
|
}
|
|
373
377
|
|
|
@@ -387,12 +391,10 @@ export function buildRows(
|
|
|
387
391
|
if (!group) {
|
|
388
392
|
group = newTally();
|
|
389
393
|
if (mode === "provider") group.models = new Map();
|
|
390
|
-
if (mode === "model") group.providers = new Set();
|
|
391
394
|
groups.set(key, group);
|
|
392
395
|
}
|
|
393
396
|
addStats(group.stats, record);
|
|
394
397
|
group.requests += record.requests;
|
|
395
|
-
if (mode === "model") group.providers!.add(record.provider);
|
|
396
398
|
if (mode === "provider") {
|
|
397
399
|
let model = group.models!.get(record.model);
|
|
398
400
|
if (!model) group.models!.set(record.model, (model = newTally()));
|
|
@@ -419,7 +421,7 @@ export function buildRows(
|
|
|
419
421
|
function toRow([name, group]: [string, Tally]): GroupRow {
|
|
420
422
|
return {
|
|
421
423
|
key: name,
|
|
422
|
-
name
|
|
424
|
+
name,
|
|
423
425
|
stats: group.stats,
|
|
424
426
|
requests: group.requests,
|
|
425
427
|
children: group.models && [...group.models].map(toRow).sort(byCost),
|
|
@@ -442,46 +444,22 @@ export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinit
|
|
|
442
444
|
return { stats, requests, sessions: sessions.size };
|
|
443
445
|
}
|
|
444
446
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
export function buildDailySeries(
|
|
450
|
-
records: UsageRecord[],
|
|
451
|
-
since: number,
|
|
452
|
-
until: number,
|
|
453
|
-
mode: GroupMode,
|
|
454
|
-
): { total: DailyCost[]; rows: Map<string, Map<number, number>> } {
|
|
455
|
-
const days = windowDays(since, until);
|
|
456
|
-
const total: DailyCost[] = [];
|
|
447
|
+
/** Total cost per local calendar day in `window`; without one, from the first recorded day through today. */
|
|
448
|
+
export function dailyTotals(records: UsageRecord[], window?: TimeWindow, now = Date.now()): DailyCost[] {
|
|
449
|
+
const { since, until } = window ?? usageWindow(records, undefined, now);
|
|
457
450
|
const positions = new Map<string, number>();
|
|
451
|
+
const total: DailyCost[] = [];
|
|
458
452
|
let cursor = since;
|
|
459
|
-
for (let
|
|
453
|
+
for (let day = windowDays(since, until); day > 0; day--) {
|
|
460
454
|
const key = dayKey(cursor);
|
|
461
|
-
positions.set(key,
|
|
462
|
-
total.push({ label: key
|
|
455
|
+
positions.set(key, total.length);
|
|
456
|
+
total.push({ label: key, cost: 0 });
|
|
463
457
|
cursor = dayWindow(key).until;
|
|
464
458
|
}
|
|
465
|
-
const costs = new Map<string, Map<number, number>>();
|
|
466
|
-
function add(key: string, index: number, cost: number): void {
|
|
467
|
-
let values = costs.get(key);
|
|
468
|
-
if (!values) costs.set(key, (values = new Map()));
|
|
469
|
-
values.set(index, (values.get(index) ?? 0) + cost);
|
|
470
|
-
}
|
|
471
459
|
for (const record of records) {
|
|
472
460
|
if (record.ts < since || record.ts >= until) continue;
|
|
473
461
|
const index = positions.get(dayKey(record.ts));
|
|
474
|
-
if (index
|
|
475
|
-
total[index]!.cost += record.cost;
|
|
476
|
-
const key = recordKey(record, mode);
|
|
477
|
-
add(seriesKey(key), index, record.cost);
|
|
478
|
-
if (mode === "provider") add(seriesKey(record.model, record.provider), index, record.cost);
|
|
462
|
+
if (index !== undefined) total[index]!.cost += record.cost;
|
|
479
463
|
}
|
|
480
|
-
return
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
/** Total cost per local calendar day from the first recorded day through today. */
|
|
484
|
-
export function dailyTotals(records: UsageRecord[], now = Date.now()): DailyCost[] {
|
|
485
|
-
const { since, until } = usageWindow(records, undefined, now);
|
|
486
|
-
return buildDailySeries(records, since, until, "day").total;
|
|
464
|
+
return total;
|
|
487
465
|
}
|