@deathbeam/pi-usage 0.0.2 → 0.0.4
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 +20 -0
- package/index.ts +213 -142
- package/package.json +1 -1
- package/usage.ts +207 -31
package/README.md
CHANGED
|
@@ -2,6 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
Use the `/usage` command for a fullscreen dashboard of token usage and costs.
|
|
4
4
|
|
|
5
|
+
## Keys
|
|
6
|
+
|
|
7
|
+
| Key | Action |
|
|
8
|
+
| ------------------- | ------------------------------------------------------------- |
|
|
9
|
+
| Tab, Shift+Tab | Cycle periods |
|
|
10
|
+
| ← / → | Cycle periods, or step the last filter if it is a time bucket |
|
|
11
|
+
| `v` | Cycle provider, model, project, day, week, and month groups |
|
|
12
|
+
| Enter | Open the selected row |
|
|
13
|
+
| Esc | Go back, or close when at the top level |
|
|
14
|
+
| `q` | Close |
|
|
15
|
+
| ↑ / ↓, `j` / `k` | Move the cursor |
|
|
16
|
+
| Page Up / Page Down | Move by a page |
|
|
17
|
+
| `g` / `G` | Move to the first / last row |
|
|
18
|
+
|
|
19
|
+
Switching periods removes time filters and keeps provider, model, and project filters. The sparkline shows daily costs for the selected row.
|
|
20
|
+
|
|
21
|
+
Weeks start on Monday in local time. Time rows include days without usage. `/day` uses the days in the visible window, including today. Δ compares that pace with the next older row. A rise from zero is shown as `▲new`.
|
|
22
|
+
|
|
23
|
+
The summary compares the current window with the same number of calendar days immediately before it. All has no comparison unless a time bucket is open.
|
|
24
|
+
|
|
5
25
|
## Installation
|
|
6
26
|
|
|
7
27
|
```sh
|
package/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** /usage — fullscreen token usage and cost dashboard
|
|
1
|
+
/** /usage — fullscreen token usage and cost dashboard. */
|
|
2
2
|
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
@@ -7,16 +7,37 @@ import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
|
7
7
|
import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
8
8
|
import {
|
|
9
9
|
bucketCosts,
|
|
10
|
+
buildDailySeries,
|
|
10
11
|
buildRows,
|
|
12
|
+
cacheView,
|
|
13
|
+
clearTimeFilters,
|
|
11
14
|
collectUsage,
|
|
12
|
-
|
|
15
|
+
dayKey,
|
|
16
|
+
isTimeFilter,
|
|
17
|
+
isTimeMode,
|
|
18
|
+
matchesFilter,
|
|
19
|
+
percentChange,
|
|
20
|
+
previousSummary,
|
|
21
|
+
seriesKey,
|
|
22
|
+
stepFilter,
|
|
13
23
|
summarize,
|
|
24
|
+
usageWindow,
|
|
25
|
+
type DailyCost,
|
|
14
26
|
type GroupMode,
|
|
15
27
|
type GroupRow,
|
|
16
28
|
type Stats,
|
|
29
|
+
type UsageFilter,
|
|
17
30
|
type UsageRecord,
|
|
18
31
|
} from "./usage.ts";
|
|
19
32
|
|
|
33
|
+
type Column = {
|
|
34
|
+
label: string;
|
|
35
|
+
width: number;
|
|
36
|
+
cell: (stats: Stats, requests: number, totalCost: number, row?: GroupRow) => string;
|
|
37
|
+
};
|
|
38
|
+
type BodyRow = GroupRow & { parent?: string };
|
|
39
|
+
type Frame = { filters: UsageFilter[]; group: number; cursor: number; top: number };
|
|
40
|
+
|
|
20
41
|
const PERIODS = [
|
|
21
42
|
{ label: "Today", days: 1 },
|
|
22
43
|
{ label: "7d", days: 7 },
|
|
@@ -24,19 +45,44 @@ const PERIODS = [
|
|
|
24
45
|
{ label: "All", days: Infinity },
|
|
25
46
|
] as const;
|
|
26
47
|
|
|
27
|
-
const GROUPS = ["provider", "model", "project"] as const satisfies readonly GroupMode[];
|
|
28
|
-
const GROUP_LABELS: Record<GroupMode, string> = {
|
|
29
|
-
|
|
30
|
-
provider: "Provider / Model",
|
|
48
|
+
const GROUPS = ["provider", "model", "project", "day", "week", "month"] as const satisfies readonly GroupMode[];
|
|
49
|
+
const GROUP_LABELS: Record<GroupMode, string> = {
|
|
50
|
+
provider: "Provider",
|
|
31
51
|
model: "Model",
|
|
32
52
|
project: "Project",
|
|
53
|
+
day: "Day",
|
|
54
|
+
week: "Week",
|
|
55
|
+
month: "Month",
|
|
33
56
|
};
|
|
34
57
|
|
|
58
|
+
const COLUMNS: Column[] = [
|
|
59
|
+
{
|
|
60
|
+
label: "Cost",
|
|
61
|
+
width: 10,
|
|
62
|
+
cell: (s, _r, _t, row) => formatCost(s.cost, row?.perDay !== undefined),
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
label: "Share",
|
|
66
|
+
width: 13,
|
|
67
|
+
cell: (s, _r, totalCost) => {
|
|
68
|
+
const share = totalCost > 0 ? s.cost / totalCost : 0;
|
|
69
|
+
const filled = Math.round(8 * share);
|
|
70
|
+
return "█".repeat(filled) + "·".repeat(8 - filled) + " " + `${Math.round(100 * share)}%`.padStart(4);
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
{ label: "Reqs", width: 6, cell: (_s, requests) => formatTokens(requests) },
|
|
74
|
+
{ label: "In", width: 7, cell: (s) => formatTokens(s.input) },
|
|
75
|
+
{ label: "Out", width: 7, cell: (s) => formatTokens(s.output) },
|
|
76
|
+
// Cost already prices read/write differently; one combined token column is enough.
|
|
77
|
+
{ label: "Cache", width: 7, cell: (s) => formatTokens(s.cacheRead + s.cacheWrite) },
|
|
78
|
+
{ label: "Hit%", width: 5, cell: (s) => hitPct(s) },
|
|
79
|
+
];
|
|
80
|
+
|
|
35
81
|
const SPARK_BARS = "▁▂▃▄▅▆▇█";
|
|
36
82
|
const MIN_NAME_WIDTH = 12;
|
|
37
83
|
|
|
38
|
-
function formatCost(cost: number): string {
|
|
39
|
-
if (cost === 0) return "-";
|
|
84
|
+
function formatCost(cost: number, showZero = false): string {
|
|
85
|
+
if (cost === 0) return showZero ? "$0.00" : "-";
|
|
40
86
|
if (cost < 0.01) return `$${cost.toFixed(4)}`;
|
|
41
87
|
if (cost < 100) return `$${cost.toFixed(2)}`;
|
|
42
88
|
return `$${Math.round(cost).toLocaleString("en-US")}`;
|
|
@@ -50,53 +96,28 @@ function formatTokens(count: number): string {
|
|
|
50
96
|
return `${(count / 1_000_000_000).toFixed(1)}B`;
|
|
51
97
|
}
|
|
52
98
|
|
|
53
|
-
/** Start of the `days`-day window ending today; 0 for All. */
|
|
54
|
-
function periodStart(days: number): number {
|
|
55
|
-
if (days === Infinity) return 0;
|
|
56
|
-
const start = new Date();
|
|
57
|
-
start.setHours(0, 0, 0, 0);
|
|
58
|
-
start.setDate(start.getDate() - (days - 1));
|
|
59
|
-
return start.getTime();
|
|
60
|
-
}
|
|
61
|
-
|
|
62
99
|
function hitPct(stats: Stats): string {
|
|
63
100
|
const total = stats.input + stats.cacheRead + stats.cacheWrite;
|
|
64
101
|
return total > 0 ? `${Math.round((100 * stats.cacheRead) / total)}%` : "-";
|
|
65
102
|
}
|
|
66
103
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const COLUMNS: Column[] = [
|
|
70
|
-
{ label: "Cost", width: 10, cell: (s) => formatCost(s.cost) },
|
|
71
|
-
// Cost already prices read/write differently; one combined token column is enough.
|
|
72
|
-
{
|
|
73
|
-
label: "Share",
|
|
74
|
-
width: 13,
|
|
75
|
-
cell: (s, _r, totalCost) => {
|
|
76
|
-
const share = totalCost > 0 ? s.cost / totalCost : 0;
|
|
77
|
-
const filled = Math.round(8 * share);
|
|
78
|
-
return "█".repeat(filled) + "·".repeat(8 - filled) + " " + `${Math.round(100 * share)}%`.padStart(4);
|
|
79
|
-
},
|
|
80
|
-
},
|
|
81
|
-
{ label: "Reqs", width: 6, cell: (_s, requests) => formatTokens(requests) },
|
|
82
|
-
{ label: "In", width: 7, cell: (s) => formatTokens(s.input) },
|
|
83
|
-
{ label: "Out", width: 7, cell: (s) => formatTokens(s.output) },
|
|
84
|
-
{ label: "Cache", width: 7, cell: (s) => formatTokens(s.cacheRead + s.cacheWrite) },
|
|
85
|
-
{ label: "Hit%", width: 5, cell: (s) => hitPct(s) },
|
|
86
|
-
];
|
|
87
|
-
|
|
88
|
-
/** Widths fit the worst case ($999,999 / 999.9B); the name column shrinks first, then Share, then Hit%. */
|
|
89
|
-
function layout(width: number): { nameWidth: number; columns: Column[] } {
|
|
104
|
+
function layout(width: number, allColumns: Column[]): { nameWidth: number; columns: Column[] } {
|
|
90
105
|
const used = (cols: Column[]) => cols.reduce((sum, c) => sum + c.width + 1, 0);
|
|
91
|
-
let columns =
|
|
92
|
-
|
|
93
|
-
|
|
106
|
+
let columns = allColumns;
|
|
107
|
+
for (const label of ["Share", "Hit%", "Cache", "Out", "In", "Reqs", "Δ", "/day"]) {
|
|
108
|
+
if (width - used(columns) >= MIN_NAME_WIDTH) break;
|
|
109
|
+
columns = columns.filter((c) => c.label !== label);
|
|
110
|
+
}
|
|
94
111
|
return { nameWidth: Math.max(4, width - used(columns)), columns };
|
|
95
112
|
}
|
|
96
113
|
|
|
97
114
|
const padWidth = (s: string, w: number): string => s + " ".repeat(Math.max(0, w - visibleWidth(s)));
|
|
98
115
|
|
|
99
116
|
function displayName(mode: GroupMode, name: string): string {
|
|
117
|
+
if (mode === "day") return `${name} ${new Date(`${name}T00:00`).toLocaleDateString("en-US", { weekday: "short" })}`;
|
|
118
|
+
if (mode === "week") return `${name} wk`;
|
|
119
|
+
if (mode === "month")
|
|
120
|
+
return `${name} ${new Date(`${name}-01T00:00`).toLocaleDateString("en-US", { month: "short" })}`;
|
|
100
121
|
if (mode !== "project") return name;
|
|
101
122
|
if (!name) return "(no cwd)";
|
|
102
123
|
const home = homedir();
|
|
@@ -108,46 +129,23 @@ function fitLabel(name: string, nameWidth: number): string {
|
|
|
108
129
|
return visibleWidth(name) > nameWidth ? truncateToWidth(name, nameWidth, "…") : name;
|
|
109
130
|
}
|
|
110
131
|
|
|
111
|
-
function tableLine(
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
totalCost: number,
|
|
118
|
-
): string {
|
|
119
|
-
const label = fitLabel(name, nameWidth);
|
|
120
|
-
return [padWidth(label, nameWidth), ...columns.map((c) => padWidth(c.cell(stats, requests, totalCost), c.width))]
|
|
132
|
+
function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCost: number): string {
|
|
133
|
+
const label = fitLabel(row.name, nameWidth);
|
|
134
|
+
return [
|
|
135
|
+
padWidth(label, nameWidth),
|
|
136
|
+
...columns.map((c) => padWidth(fitLabel(c.cell(row.stats, row.requests, totalCost, row), c.width), c.width)),
|
|
137
|
+
]
|
|
121
138
|
.join(" ")
|
|
122
139
|
.trimEnd();
|
|
123
140
|
}
|
|
124
141
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
records: UsageRecord[],
|
|
128
|
-
days: number,
|
|
129
|
-
width: number,
|
|
130
|
-
): { first: string; bars: string; last: string } | undefined {
|
|
131
|
-
if (days === 1) return undefined;
|
|
132
|
-
let dayCount = days;
|
|
133
|
-
if (days === Infinity) {
|
|
134
|
-
let first = Infinity;
|
|
135
|
-
for (const record of records) if (record.ts < first) first = record.ts;
|
|
136
|
-
if (first === Infinity) return undefined;
|
|
137
|
-
const firstDay = new Date(first);
|
|
138
|
-
firstDay.setHours(0, 0, 0, 0);
|
|
139
|
-
const today = new Date();
|
|
140
|
-
today.setHours(0, 0, 0, 0);
|
|
141
|
-
dayCount = Math.max(1, Math.round((today.getTime() - firstDay.getTime()) / 86_400_000) + 1);
|
|
142
|
-
}
|
|
143
|
-
const daily = dailyCosts(records, dayCount);
|
|
142
|
+
function sparkline(daily: DailyCost[], width: number): { first: string; bars: string; last: string } | undefined {
|
|
143
|
+
if (daily.length <= 1) return undefined;
|
|
144
144
|
const first = daily[0]!.label;
|
|
145
145
|
const last = daily[daily.length - 1]!.label;
|
|
146
|
-
|
|
147
|
-
const bars = bucketCosts(daily, Math.ceil(dayCount / Math.max(1, width - 12)));
|
|
146
|
+
const bars = bucketCosts(daily, Math.ceil(daily.length / Math.max(1, width - 12)));
|
|
148
147
|
let max = 0;
|
|
149
148
|
for (const bar of bars) if (bar.cost > max) max = bar.cost;
|
|
150
|
-
if (max <= 0) return undefined;
|
|
151
149
|
return {
|
|
152
150
|
first,
|
|
153
151
|
bars: bars.map((d) => (d.cost <= 0 ? " " : SPARK_BARS[Math.max(1, Math.round((7 * d.cost) / max))])).join(""),
|
|
@@ -155,14 +153,11 @@ function sparkline(
|
|
|
155
153
|
};
|
|
156
154
|
}
|
|
157
155
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
function flatten(rows: GroupRow[]): BodyRow[] {
|
|
156
|
+
function flatten(rows: GroupRow[], mode: GroupMode): BodyRow[] {
|
|
161
157
|
const body: BodyRow[] = [];
|
|
162
158
|
for (const row of rows) {
|
|
163
|
-
body.push({
|
|
164
|
-
for (const child of row.children ?? [])
|
|
165
|
-
body.push({ name: ` ${child.name}`, stats: child.stats, requests: child.requests, dim: true });
|
|
159
|
+
body.push({ ...row, name: displayName(mode, row.name) });
|
|
160
|
+
for (const child of row.children ?? []) body.push({ ...child, name: ` ${child.name}`, parent: row.key });
|
|
166
161
|
}
|
|
167
162
|
return body;
|
|
168
163
|
}
|
|
@@ -191,33 +186,82 @@ export default function (pi: ExtensionAPI) {
|
|
|
191
186
|
} as const;
|
|
192
187
|
await ctx.ui.custom((tui, theme, keys, done) => {
|
|
193
188
|
let period = 0;
|
|
194
|
-
let group
|
|
189
|
+
let group = 0;
|
|
195
190
|
let cursor = 0;
|
|
196
191
|
let top = 0;
|
|
197
192
|
let rowCount = 0;
|
|
198
193
|
let viewHeight = 1; // set on first render; 1 keeps page keys sane before it
|
|
194
|
+
let body: BodyRow[] = [];
|
|
195
|
+
const stack: Frame[] = [];
|
|
196
|
+
const filters = () => stack.flatMap((frame) => frame.filters);
|
|
197
|
+
const timeIsInnermost = () => isTimeFilter(filters().at(-1));
|
|
198
|
+
const derive = (source: UsageRecord[]) => {
|
|
199
|
+
const active = filters();
|
|
200
|
+
const records = source.filter((record) =>
|
|
201
|
+
active.every((f) => isTimeMode(f.mode) || matchesFilter(record, f)),
|
|
202
|
+
);
|
|
203
|
+
const window = usageWindow(records, PERIODS[period].days, active);
|
|
204
|
+
const mode = GROUPS[group]!;
|
|
205
|
+
const summary = summarize(records, window.since, window.until);
|
|
206
|
+
const compare =
|
|
207
|
+
window.days > 0 &&
|
|
208
|
+
(active.some((f) => isTimeMode(f.mode)) || PERIODS[period].days !== Infinity);
|
|
209
|
+
const previous = compare ? previousSummary(records, window.since, window.days) : undefined;
|
|
210
|
+
const body = flatten(buildRows(records, window.since, mode, window.until), mode);
|
|
211
|
+
const series = buildDailySeries(records, window.since, window.until, mode, body);
|
|
212
|
+
return { records, window, mode, summary, previous, body, series };
|
|
213
|
+
};
|
|
214
|
+
const getView = cacheView(() => derive(state.records!));
|
|
215
|
+
const changePeriod = (offset: number) => {
|
|
216
|
+
period = (period + offset + PERIODS.length) % PERIODS.length;
|
|
217
|
+
clearTimeFilters(stack);
|
|
218
|
+
cursor = top = 0;
|
|
219
|
+
};
|
|
199
220
|
render = () => tui.requestRender();
|
|
200
221
|
void loaded.then(render);
|
|
222
|
+
const colorDelta = (delta: number | undefined): string => {
|
|
223
|
+
if (delta === undefined) return "-";
|
|
224
|
+
if (delta === 0) return "0%";
|
|
225
|
+
const text = Number.isFinite(delta)
|
|
226
|
+
? `${delta > 0 ? "▲" : "▼"}${Math.round(Math.abs(delta))}%`
|
|
227
|
+
: "▲new";
|
|
228
|
+
return theme.fg(delta > 0 ? "error" : "success", text);
|
|
229
|
+
};
|
|
230
|
+
const timeColumns: Column[] = [
|
|
231
|
+
{
|
|
232
|
+
label: "/day",
|
|
233
|
+
width: 10,
|
|
234
|
+
cell: (_s, _r, _t, row) => (row?.perDay === undefined ? "-" : formatCost(row.perDay, true)),
|
|
235
|
+
},
|
|
236
|
+
{ label: "Δ", width: 9, cell: (_s, _r, _t, row) => colorDelta(row?.delta) },
|
|
237
|
+
];
|
|
201
238
|
const title = (width: number): string => {
|
|
202
|
-
const
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
).join(" ");
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
239
|
+
const tab = (label: string, active: boolean) =>
|
|
240
|
+
active ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `);
|
|
241
|
+
const left = stack.length
|
|
242
|
+
? theme.fg("accent", theme.bold("Usage")) +
|
|
243
|
+
" › " +
|
|
244
|
+
[PERIODS[period].label, ...filters().map((f) => displayName(f.mode, f.key))].join(" › ")
|
|
245
|
+
: `${theme.fg("accent", theme.bold("Usage"))} ${PERIODS.map(({ label }, i) => tab(label, i === period)).join(" ")}`;
|
|
246
|
+
const right = GROUPS.map((g, i) => tab(GROUP_LABELS[g], i === group)).join(" ");
|
|
247
|
+
const leftWidth = Math.max(0, width - visibleWidth(right) - 1);
|
|
248
|
+
return truncateToWidth(
|
|
249
|
+
truncateToWidth(left, leftWidth, "…") +
|
|
250
|
+
" ".repeat(
|
|
251
|
+
Math.max(1, width - Math.min(visibleWidth(left), leftWidth) - visibleWidth(right)),
|
|
252
|
+
) +
|
|
253
|
+
right,
|
|
254
|
+
width,
|
|
255
|
+
);
|
|
218
256
|
};
|
|
219
257
|
const footer = (width: number): string =>
|
|
220
|
-
truncateToWidth(
|
|
258
|
+
truncateToWidth(
|
|
259
|
+
theme.fg(
|
|
260
|
+
"dim",
|
|
261
|
+
`enter open · esc back · v group · tab period · ←→ ${timeIsInnermost() ? "bucket" : "period"} · q close · ↑↓ scroll`,
|
|
262
|
+
),
|
|
263
|
+
width,
|
|
264
|
+
);
|
|
221
265
|
return {
|
|
222
266
|
render(width: number) {
|
|
223
267
|
const rows = tui.terminal.rows;
|
|
@@ -235,14 +279,33 @@ export default function (pi: ExtensionAPI) {
|
|
|
235
279
|
lines.push(rule, footer(width));
|
|
236
280
|
return lines.slice(0, rows);
|
|
237
281
|
}
|
|
238
|
-
const
|
|
239
|
-
const mode =
|
|
240
|
-
const
|
|
282
|
+
const view = getView(period, GROUPS[group]!, filters());
|
|
283
|
+
const { window, mode, summary, previous, series } = view;
|
|
284
|
+
const label =
|
|
285
|
+
window.days === 1 && dayKey(window.since) === dayKey(Date.now())
|
|
286
|
+
? "yesterday"
|
|
287
|
+
: `prev ${window.days}d`;
|
|
288
|
+
const trend = previous
|
|
289
|
+
? ` ${colorDelta(percentChange(summary.stats.cost, previous.stats.cost))} vs ${label}`
|
|
290
|
+
: "";
|
|
241
291
|
lines.push(
|
|
242
|
-
|
|
243
|
-
|
|
292
|
+
truncateToWidth(
|
|
293
|
+
`Cost ${formatCost(summary.stats.cost)}${trend} · ${formatCost(window.days ? summary.stats.cost / window.days : 0)}/day · Reqs ${formatTokens(summary.requests)} · Sessions ${formatTokens(summary.sessions)}`,
|
|
294
|
+
width,
|
|
295
|
+
),
|
|
296
|
+
truncateToWidth(
|
|
297
|
+
`In ${formatTokens(summary.stats.input)} · Out ${formatTokens(summary.stats.output)} · Cache ${formatTokens(summary.stats.cacheRead + summary.stats.cacheWrite)} · Hit ${hitPct(summary.stats)}`,
|
|
298
|
+
width,
|
|
299
|
+
),
|
|
244
300
|
);
|
|
245
|
-
|
|
301
|
+
body = view.body;
|
|
302
|
+
rowCount = body.length;
|
|
303
|
+
cursor = Math.min(cursor, Math.max(0, rowCount - 1));
|
|
304
|
+
const selected = body[cursor];
|
|
305
|
+
const daily = selected
|
|
306
|
+
? (series.rows.get(seriesKey(selected.key, selected.parent)) ?? series.total)
|
|
307
|
+
: series.total;
|
|
308
|
+
const spark = sparkline(daily, width);
|
|
246
309
|
if (spark)
|
|
247
310
|
lines.push(
|
|
248
311
|
truncateToWidth(
|
|
@@ -250,12 +313,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
250
313
|
width,
|
|
251
314
|
),
|
|
252
315
|
);
|
|
253
|
-
const { nameWidth, columns } = layout(
|
|
316
|
+
const { nameWidth, columns } = layout(
|
|
317
|
+
width,
|
|
318
|
+
isTimeMode(mode) ? [COLUMNS[0]!, ...timeColumns, ...COLUMNS.slice(1)] : COLUMNS,
|
|
319
|
+
);
|
|
320
|
+
const header = mode === "provider" ? "Provider / Model" : GROUP_LABELS[mode];
|
|
254
321
|
lines.push(
|
|
255
322
|
theme.fg(
|
|
256
323
|
"muted",
|
|
257
324
|
[
|
|
258
|
-
padWidth(fitLabel(
|
|
325
|
+
padWidth(fitLabel(header, nameWidth), nameWidth),
|
|
259
326
|
...columns.map((c) => padWidth(c.label, c.width)),
|
|
260
327
|
]
|
|
261
328
|
.join(" ")
|
|
@@ -263,59 +330,63 @@ export default function (pi: ExtensionAPI) {
|
|
|
263
330
|
),
|
|
264
331
|
);
|
|
265
332
|
// Fixed top: title, rule, summary, sparkline, column header. Fixed bottom: totals, rule, footer.
|
|
266
|
-
const body = flatten(buildRows(state.records, since, mode)).map((row) => ({
|
|
267
|
-
...row,
|
|
268
|
-
name: displayName(mode, row.name),
|
|
269
|
-
}));
|
|
270
|
-
rowCount = body.length;
|
|
271
333
|
viewHeight = Math.max(0, rows - lines.length - 3);
|
|
272
|
-
cursor = Math.min(cursor, Math.max(0, rowCount - 1));
|
|
273
334
|
top = Math.max(0, Math.min(top, rowCount - viewHeight));
|
|
274
335
|
if (cursor < top) top = cursor;
|
|
275
336
|
if (viewHeight > 0 && cursor >= top + viewHeight) top = cursor - viewHeight + 1;
|
|
276
337
|
const visible = body.slice(top, top + viewHeight);
|
|
277
338
|
if (rowCount === 0) lines.push(theme.fg("dim", " No usage in this period"));
|
|
278
339
|
for (const [i, row] of visible.entries()) {
|
|
279
|
-
let line = tableLine(
|
|
280
|
-
nameWidth,
|
|
281
|
-
columns,
|
|
282
|
-
row.name,
|
|
283
|
-
row.stats,
|
|
284
|
-
row.requests,
|
|
285
|
-
summary.stats.cost,
|
|
286
|
-
);
|
|
340
|
+
let line = tableLine(nameWidth, columns, row, summary.stats.cost);
|
|
287
341
|
if (top + i === cursor) line = theme.bg("selectedBg", line);
|
|
288
|
-
else if (row.
|
|
289
|
-
lines.push(
|
|
342
|
+
else if (row.parent !== undefined) line = theme.fg("dim", line);
|
|
343
|
+
lines.push(line);
|
|
290
344
|
}
|
|
345
|
+
const total = { key: "", name: "Total", stats: summary.stats, requests: summary.requests };
|
|
291
346
|
lines.push(
|
|
292
|
-
theme.bold(
|
|
293
|
-
tableLine(
|
|
294
|
-
nameWidth,
|
|
295
|
-
columns,
|
|
296
|
-
"Total",
|
|
297
|
-
summary.stats,
|
|
298
|
-
summary.requests,
|
|
299
|
-
summary.stats.cost,
|
|
300
|
-
),
|
|
301
|
-
),
|
|
347
|
+
theme.bold(tableLine(nameWidth, columns, total, summary.stats.cost)),
|
|
302
348
|
rule,
|
|
303
349
|
footer(width),
|
|
304
350
|
);
|
|
305
|
-
return lines
|
|
351
|
+
return lines
|
|
352
|
+
.slice(0, rows)
|
|
353
|
+
.map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width) : line));
|
|
306
354
|
},
|
|
307
355
|
invalidate() {},
|
|
308
356
|
handleInput(data: string) {
|
|
309
|
-
if (
|
|
357
|
+
if (data === "q") {
|
|
310
358
|
done(undefined);
|
|
311
359
|
return;
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
360
|
+
} else if (keys.matches(data, "tui.select.cancel")) {
|
|
361
|
+
const frame = stack.pop();
|
|
362
|
+
if (!frame) {
|
|
363
|
+
done(undefined);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
({ group, cursor, top } = frame);
|
|
367
|
+
tui.requestRender();
|
|
368
|
+
return;
|
|
369
|
+
} else if (keys.matches(data, "tui.select.confirm") && body[cursor]) {
|
|
370
|
+
const row = body[cursor]!;
|
|
371
|
+
const rowMode = row.parent === undefined ? GROUPS[group]! : "model";
|
|
372
|
+
const selected: UsageFilter[] =
|
|
373
|
+
row.parent === undefined ? [] : [{ mode: "provider", key: row.parent }];
|
|
374
|
+
selected.push({ mode: rowMode, key: row.key });
|
|
375
|
+
stack.push({ filters: selected, group, cursor, top });
|
|
376
|
+
group = isTimeMode(rowMode) ? 0 : GROUPS.indexOf("day");
|
|
377
|
+
cursor = top = 0;
|
|
378
|
+
} else if ((matchesKey(data, "right") || matchesKey(data, "left")) && timeIsInnermost()) {
|
|
379
|
+
const active = filters();
|
|
380
|
+
const next = stepFilter(active, matchesKey(data, "right") ? 1 : -1);
|
|
381
|
+
if (next !== undefined) active.at(-1)!.key = next;
|
|
382
|
+
} else if (matchesKey(data, "tab") || matchesKey(data, "right")) {
|
|
383
|
+
changePeriod(1);
|
|
384
|
+
} else if (matchesKey(data, "shift+tab") || matchesKey(data, "left")) {
|
|
385
|
+
changePeriod(-1);
|
|
386
|
+
} else if (data === "v") {
|
|
387
|
+
group = (group + 1) % GROUPS.length;
|
|
388
|
+
cursor = top = 0;
|
|
389
|
+
} else if (keys.matches(data, "tui.select.up") || data === "k") cursor -= 1;
|
|
319
390
|
else if (keys.matches(data, "tui.select.down") || data === "j") cursor += 1;
|
|
320
391
|
else if (matchesKey(data, "pageUp")) cursor -= Math.max(1, viewHeight);
|
|
321
392
|
else if (matchesKey(data, "pageDown")) cursor += Math.max(1, viewHeight);
|
package/package.json
CHANGED
package/usage.ts
CHANGED
|
@@ -129,12 +129,135 @@ function addStats(stats: Stats, record: UsageRecord): void {
|
|
|
129
129
|
stats.cacheWrite += record.cacheWrite;
|
|
130
130
|
}
|
|
131
131
|
|
|
132
|
-
|
|
132
|
+
type TimeMode = "day" | "week" | "month";
|
|
133
|
+
export type GroupMode = "provider" | "model" | "project" | TimeMode;
|
|
134
|
+
export type UsageFilter = { mode: GroupMode; key: string };
|
|
135
|
+
|
|
136
|
+
export const isTimeMode = (mode: GroupMode): mode is TimeMode => mode === "day" || mode === "week" || mode === "month";
|
|
137
|
+
|
|
138
|
+
export function isTimeFilter(filter: UsageFilter | undefined): filter is UsageFilter & { mode: TimeMode } {
|
|
139
|
+
return filter !== undefined && isTimeMode(filter.mode);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function clearTimeFilters(stack: { filters: UsageFilter[] }[]): void {
|
|
143
|
+
for (let i = stack.length - 1; i >= 0; i--) {
|
|
144
|
+
stack[i]!.filters = stack[i]!.filters.filter((filter) => !isTimeMode(filter.mode));
|
|
145
|
+
if (!stack[i]!.filters.length) stack.splice(i, 1);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function cacheView<T>(derive: () => T) {
|
|
150
|
+
let cached: { key: string; value: T } | undefined;
|
|
151
|
+
return (period: number, mode: GroupMode, filters: UsageFilter[], now = Date.now()): T => {
|
|
152
|
+
const key = JSON.stringify([period, mode, filters, dayKey(now)]);
|
|
153
|
+
if (!cached || cached.key !== key) cached = { key, value: derive() };
|
|
154
|
+
return cached.value;
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function dayKey(ts: number): string {
|
|
159
|
+
const d = new Date(ts);
|
|
160
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function bucketStart(ts: number, mode: TimeMode): number {
|
|
164
|
+
const d = new Date(ts);
|
|
165
|
+
d.setHours(0, 0, 0, 0);
|
|
166
|
+
if (mode === "week") d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
|
|
167
|
+
if (mode === "month") d.setDate(1);
|
|
168
|
+
d.setHours(0, 0, 0, 0);
|
|
169
|
+
return d.getTime();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function bucketKey(ts: number, mode: TimeMode): string {
|
|
173
|
+
const key = dayKey(bucketStart(ts, mode));
|
|
174
|
+
return mode === "month" ? key.slice(0, 7) : key;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function bucketWindow(key: string, mode: TimeMode, offset = 0): { since: number; until: number } {
|
|
178
|
+
const date = new Date(`${mode === "month" ? key + "-01" : key}T00:00`);
|
|
179
|
+
const shift = (n: number) => {
|
|
180
|
+
if (mode === "month") date.setMonth(date.getMonth() + n);
|
|
181
|
+
else date.setDate(date.getDate() + n * (mode === "week" ? 7 : 1));
|
|
182
|
+
// A skipped midnight can leave 01:00 on the next calendar day.
|
|
183
|
+
date.setHours(0, 0, 0, 0);
|
|
184
|
+
};
|
|
185
|
+
shift(offset);
|
|
186
|
+
const since = date.getTime();
|
|
187
|
+
shift(1);
|
|
188
|
+
return { since, until: date.getTime() };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function stepFilter(filters: UsageFilter[], offset: number, now = Date.now()): string | undefined {
|
|
192
|
+
const last = filters.at(-1);
|
|
193
|
+
if (!isTimeFilter(last)) return undefined;
|
|
194
|
+
let { since, until } = bucketWindow(last.key, last.mode, offset);
|
|
195
|
+
const key = bucketKey(since, last.mode);
|
|
196
|
+
if (key > bucketKey(now, last.mode)) return undefined;
|
|
197
|
+
for (const outer of filters.slice(0, -1)) {
|
|
198
|
+
if (!isTimeMode(outer.mode)) continue;
|
|
199
|
+
const window = bucketWindow(outer.key, outer.mode);
|
|
200
|
+
since = Math.max(since, window.since);
|
|
201
|
+
until = Math.min(until, window.until);
|
|
202
|
+
}
|
|
203
|
+
return since < until ? key : undefined;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// UTC ordinals count local calendar days without DST changing their length.
|
|
207
|
+
export function windowDays(since: number, until: number): number {
|
|
208
|
+
if (since >= until) return 0;
|
|
209
|
+
const ordinal = (ts: number) => {
|
|
210
|
+
const d = new Date(ts);
|
|
211
|
+
return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) / 86_400_000;
|
|
212
|
+
};
|
|
213
|
+
return ordinal(until - 1) - ordinal(since) + 1;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function percentChange(current: number, previous: number): number {
|
|
217
|
+
return previous === 0 ? (current === 0 ? 0 : Infinity) : ((current - previous) / previous) * 100;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function recordKey(record: UsageRecord, mode: GroupMode): string {
|
|
221
|
+
return isTimeMode(mode) ? bucketKey(record.ts, mode) : mode === "project" ? record.cwd : record[mode];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function matchesFilter(record: UsageRecord, filter: UsageFilter): boolean {
|
|
225
|
+
return recordKey(record, filter.mode) === filter.key;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export function usageWindow(records: UsageRecord[], days: number, filters: UsageFilter[], now = Date.now()) {
|
|
229
|
+
const { since: today, until: end } = bucketWindow(dayKey(now), "day");
|
|
230
|
+
const timeFilters = filters.filter((f) => isTimeMode(f.mode));
|
|
231
|
+
let since = today;
|
|
232
|
+
let until = end;
|
|
233
|
+
if (timeFilters.length) {
|
|
234
|
+
since = 0;
|
|
235
|
+
for (const filter of timeFilters) {
|
|
236
|
+
const window = bucketWindow(filter.key, filter.mode as TimeMode);
|
|
237
|
+
since = Math.max(since, window.since);
|
|
238
|
+
until = Math.min(until, window.until);
|
|
239
|
+
}
|
|
240
|
+
} else if (days === Infinity) {
|
|
241
|
+
let first = Infinity;
|
|
242
|
+
for (const record of records) if (record.ts < end) first = Math.min(first, record.ts);
|
|
243
|
+
since = first === Infinity ? end : bucketWindow(dayKey(first), "day").since;
|
|
244
|
+
} else {
|
|
245
|
+
since = bucketWindow(dayKey(now), "day", 1 - days).since;
|
|
246
|
+
}
|
|
247
|
+
return { since, until, days: windowDays(since, until) };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function previousSummary(records: UsageRecord[], since: number, days: number): Summary {
|
|
251
|
+
return summarize(records, bucketWindow(dayKey(since), "day", -days).since, since);
|
|
252
|
+
}
|
|
133
253
|
|
|
134
254
|
export type GroupRow = {
|
|
255
|
+
key: string;
|
|
135
256
|
name: string;
|
|
136
257
|
stats: Stats;
|
|
137
258
|
requests: number;
|
|
259
|
+
perDay?: number;
|
|
260
|
+
delta?: number;
|
|
138
261
|
/** Nested model rows; only produced by provider grouping. */
|
|
139
262
|
children?: GroupRow[];
|
|
140
263
|
};
|
|
@@ -148,16 +271,18 @@ type Tally = { stats: Stats; requests: number; models?: Map<string, Tally>; prov
|
|
|
148
271
|
|
|
149
272
|
const newTally = (): Tally => ({ stats: emptyStats(), requests: 0 });
|
|
150
273
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
274
|
+
export function buildRows(
|
|
275
|
+
records: UsageRecord[],
|
|
276
|
+
sinceMs = 0,
|
|
277
|
+
mode: GroupMode = "provider",
|
|
278
|
+
untilMs = Infinity,
|
|
279
|
+
): GroupRow[] {
|
|
280
|
+
if (isTimeMode(mode) && (!Number.isFinite(sinceMs) || !Number.isFinite(untilMs)))
|
|
281
|
+
throw new RangeError("Time grouping requires a finite window");
|
|
157
282
|
const groups = new Map<string, Tally>();
|
|
158
283
|
for (const record of records) {
|
|
159
|
-
if (record.ts < sinceMs) continue;
|
|
160
|
-
const key =
|
|
284
|
+
if (record.ts < sinceMs || record.ts >= untilMs) continue;
|
|
285
|
+
const key = recordKey(record, mode);
|
|
161
286
|
let group = groups.get(key);
|
|
162
287
|
if (!group) {
|
|
163
288
|
group = newTally();
|
|
@@ -175,7 +300,34 @@ export function buildRows(records: UsageRecord[], sinceMs = 0, mode: GroupMode =
|
|
|
175
300
|
model.requests++;
|
|
176
301
|
}
|
|
177
302
|
}
|
|
303
|
+
if (isTimeMode(mode)) {
|
|
304
|
+
if (sinceMs < untilMs) {
|
|
305
|
+
let key = bucketKey(sinceMs, mode);
|
|
306
|
+
const last = bucketKey(untilMs - 1, mode);
|
|
307
|
+
while (key <= last) {
|
|
308
|
+
if (!groups.has(key)) groups.set(key, newTally());
|
|
309
|
+
key = bucketKey(bucketWindow(key, mode).until, mode);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
const rows = [...groups]
|
|
313
|
+
.map(([key, group]): GroupRow => {
|
|
314
|
+
const window = bucketWindow(key, mode);
|
|
315
|
+
const days = windowDays(Math.max(sinceMs, window.since), Math.min(untilMs, window.until));
|
|
316
|
+
return {
|
|
317
|
+
key,
|
|
318
|
+
name: key,
|
|
319
|
+
stats: group.stats,
|
|
320
|
+
requests: group.requests,
|
|
321
|
+
perDay: days ? group.stats.cost / days : 0,
|
|
322
|
+
};
|
|
323
|
+
})
|
|
324
|
+
.sort((a, b) => b.key.localeCompare(a.key));
|
|
325
|
+
for (let i = 0; i + 1 < rows.length; i++)
|
|
326
|
+
rows[i]!.delta = percentChange(rows[i]!.perDay!, rows[i + 1]!.perDay!);
|
|
327
|
+
return rows;
|
|
328
|
+
}
|
|
178
329
|
const toRow = ([name, group]: [string, Tally]): GroupRow => ({
|
|
330
|
+
key: name,
|
|
179
331
|
name: mode === "model" && group.providers!.size > 1 ? `${name} (${group.providers!.size})` : name,
|
|
180
332
|
stats: group.stats,
|
|
181
333
|
requests: group.requests,
|
|
@@ -193,13 +345,13 @@ export type Summary = {
|
|
|
193
345
|
hit: number;
|
|
194
346
|
};
|
|
195
347
|
|
|
196
|
-
/** Totals for the summary block: one pass over
|
|
197
|
-
export function summarize(records: UsageRecord[], sinceMs = 0): Summary {
|
|
348
|
+
/** Totals for the summary block: one pass over [sinceMs, untilMs). */
|
|
349
|
+
export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinity): Summary {
|
|
198
350
|
const stats = emptyStats();
|
|
199
351
|
let requests = 0;
|
|
200
352
|
const sessions = new Set<string>();
|
|
201
353
|
for (const record of records) {
|
|
202
|
-
if (record.ts < sinceMs) continue;
|
|
354
|
+
if (record.ts < sinceMs || record.ts >= untilMs) continue;
|
|
203
355
|
addStats(stats, record);
|
|
204
356
|
requests++;
|
|
205
357
|
sessions.add(record.sessionId);
|
|
@@ -215,29 +367,53 @@ export function summarize(records: UsageRecord[], sinceMs = 0): Summary {
|
|
|
215
367
|
|
|
216
368
|
export type DailyCost = { label: string; cost: number };
|
|
217
369
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
370
|
+
export const seriesKey = (key: string, parent?: string): string => JSON.stringify([key, parent ?? null]);
|
|
371
|
+
|
|
372
|
+
export function buildDailySeries(
|
|
373
|
+
records: UsageRecord[],
|
|
374
|
+
since: number,
|
|
375
|
+
until: number,
|
|
376
|
+
mode: GroupMode,
|
|
377
|
+
rows: { key: string; parent?: string }[],
|
|
378
|
+
): { total: DailyCost[]; rows: Map<string, DailyCost[]> } {
|
|
379
|
+
const days = windowDays(since, until);
|
|
380
|
+
const total: DailyCost[] = [];
|
|
381
|
+
const positions = new Map<string, number>();
|
|
382
|
+
let cursor = since;
|
|
226
383
|
for (let i = 0; i < days; i++) {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
});
|
|
232
|
-
cursor.setDate(cursor.getDate() - 1);
|
|
384
|
+
const key = dayKey(cursor);
|
|
385
|
+
positions.set(key, i);
|
|
386
|
+
total.push({ label: key.slice(5), cost: 0 });
|
|
387
|
+
cursor = bucketWindow(key, "day").until;
|
|
233
388
|
}
|
|
389
|
+
const costs = new Map<string, Map<number, number>>();
|
|
390
|
+
const add = (key: string, index: number, cost: number) => {
|
|
391
|
+
let values = costs.get(key);
|
|
392
|
+
if (!values) costs.set(key, (values = new Map()));
|
|
393
|
+
values.set(index, (values.get(index) ?? 0) + cost);
|
|
394
|
+
};
|
|
234
395
|
for (const record of records) {
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
396
|
+
if (record.ts < since || record.ts >= until) continue;
|
|
397
|
+
const index = positions.get(dayKey(record.ts));
|
|
398
|
+
if (index === undefined) continue;
|
|
399
|
+
total[index]!.cost += record.cost;
|
|
400
|
+
const key = recordKey(record, mode);
|
|
401
|
+
add(seriesKey(key), index, record.cost);
|
|
402
|
+
if (mode === "provider") add(seriesKey(record.model, record.provider), index, record.cost);
|
|
403
|
+
}
|
|
404
|
+
const result = new Map<string, DailyCost[]>();
|
|
405
|
+
for (const row of rows) {
|
|
406
|
+
const key = seriesKey(row.key, row.parent);
|
|
407
|
+
const values = costs.get(key);
|
|
408
|
+
const bucket = isTimeMode(mode) ? bucketWindow(row.key, mode) : { since, until };
|
|
409
|
+
const start = windowDays(since, Math.max(since, bucket.since));
|
|
410
|
+
const end = windowDays(since, Math.min(until, bucket.until));
|
|
411
|
+
result.set(
|
|
412
|
+
key,
|
|
413
|
+
total.slice(start, end).map((day, i) => ({ label: day.label, cost: values?.get(start + i) ?? 0 })),
|
|
414
|
+
);
|
|
239
415
|
}
|
|
240
|
-
return
|
|
416
|
+
return { total, rows: result };
|
|
241
417
|
}
|
|
242
418
|
|
|
243
419
|
/** Sum `perBar` consecutive daily buckets into one bar, labeled by its first day. */
|