@deathbeam/pi-usage 0.0.4 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -17
- package/index.ts +82 -100
- package/package.json +1 -1
- package/usage.ts +67 -132
package/README.md
CHANGED
|
@@ -4,23 +4,20 @@ Use the `/usage` command for a fullscreen dashboard of token usage and costs.
|
|
|
4
4
|
|
|
5
5
|
## Keys
|
|
6
6
|
|
|
7
|
-
| Key
|
|
8
|
-
|
|
|
9
|
-
| Tab, Shift+Tab
|
|
10
|
-
|
|
|
11
|
-
|
|
|
12
|
-
|
|
|
13
|
-
|
|
|
14
|
-
| `
|
|
15
|
-
|
|
|
16
|
-
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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.
|
|
7
|
+
| Key | Action |
|
|
8
|
+
| --------------------- | -------------------------------------------- |
|
|
9
|
+
| Tab, Shift+Tab, ← / → | Cycle groups. Inside an open day, skip day. |
|
|
10
|
+
| `[` / `]` | Step the day when it is the innermost filter |
|
|
11
|
+
| Enter | Open the selected row |
|
|
12
|
+
| Esc | Go back, or close when at the top level |
|
|
13
|
+
| `q` | Close |
|
|
14
|
+
| ↑ / ↓, `j` / `k` | Move the cursor |
|
|
15
|
+
| Page Up / Page Down | Move by a page |
|
|
16
|
+
| `g` / `G` | Move to the first / last row |
|
|
17
|
+
|
|
18
|
+
Day rows include days without usage. Δ compares cost with the previous day. The sparkline always shows total cost per day across all history; the day in context is highlighted.
|
|
19
|
+
|
|
20
|
+
The summary compares the daily spend so far this week and month with last week and month. Weeks start on Monday in local time. `▲new` means the previous period had no spend.
|
|
24
21
|
|
|
25
22
|
## Installation
|
|
26
23
|
|
package/index.ts
CHANGED
|
@@ -6,20 +6,15 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
6
6
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
8
8
|
import {
|
|
9
|
-
bucketCosts,
|
|
10
|
-
buildDailySeries,
|
|
11
9
|
buildRows,
|
|
12
10
|
cacheView,
|
|
13
|
-
clearTimeFilters,
|
|
14
11
|
collectUsage,
|
|
12
|
+
comparison,
|
|
13
|
+
dailyTotals,
|
|
15
14
|
dayKey,
|
|
16
|
-
|
|
17
|
-
isTimeMode,
|
|
15
|
+
dayWindow,
|
|
18
16
|
matchesFilter,
|
|
19
17
|
percentChange,
|
|
20
|
-
previousSummary,
|
|
21
|
-
seriesKey,
|
|
22
|
-
stepFilter,
|
|
23
18
|
summarize,
|
|
24
19
|
usageWindow,
|
|
25
20
|
type DailyCost,
|
|
@@ -38,28 +33,19 @@ type Column = {
|
|
|
38
33
|
type BodyRow = GroupRow & { parent?: string };
|
|
39
34
|
type Frame = { filters: UsageFilter[]; group: number; cursor: number; top: number };
|
|
40
35
|
|
|
41
|
-
const
|
|
42
|
-
{ label: "Today", days: 1 },
|
|
43
|
-
{ label: "7d", days: 7 },
|
|
44
|
-
{ label: "30d", days: 30 },
|
|
45
|
-
{ label: "All", days: Infinity },
|
|
46
|
-
] as const;
|
|
47
|
-
|
|
48
|
-
const GROUPS = ["provider", "model", "project", "day", "week", "month"] as const satisfies readonly GroupMode[];
|
|
36
|
+
const GROUPS = ["day", "provider", "model", "project"] as const satisfies readonly GroupMode[];
|
|
49
37
|
const GROUP_LABELS: Record<GroupMode, string> = {
|
|
38
|
+
day: "Day",
|
|
50
39
|
provider: "Provider",
|
|
51
40
|
model: "Model",
|
|
52
41
|
project: "Project",
|
|
53
|
-
day: "Day",
|
|
54
|
-
week: "Week",
|
|
55
|
-
month: "Month",
|
|
56
42
|
};
|
|
57
43
|
|
|
58
44
|
const COLUMNS: Column[] = [
|
|
59
45
|
{
|
|
60
46
|
label: "Cost",
|
|
61
47
|
width: 10,
|
|
62
|
-
cell: (s
|
|
48
|
+
cell: (s) => formatCost(s.cost),
|
|
63
49
|
},
|
|
64
50
|
{
|
|
65
51
|
label: "Share",
|
|
@@ -81,8 +67,8 @@ const COLUMNS: Column[] = [
|
|
|
81
67
|
const SPARK_BARS = "▁▂▃▄▅▆▇█";
|
|
82
68
|
const MIN_NAME_WIDTH = 12;
|
|
83
69
|
|
|
84
|
-
function formatCost(cost: number
|
|
85
|
-
if (cost === 0) return
|
|
70
|
+
function formatCost(cost: number): string {
|
|
71
|
+
if (cost === 0) return "$0.00";
|
|
86
72
|
if (cost < 0.01) return `$${cost.toFixed(4)}`;
|
|
87
73
|
if (cost < 100) return `$${cost.toFixed(2)}`;
|
|
88
74
|
return `$${Math.round(cost).toLocaleString("en-US")}`;
|
|
@@ -104,7 +90,7 @@ function hitPct(stats: Stats): string {
|
|
|
104
90
|
function layout(width: number, allColumns: Column[]): { nameWidth: number; columns: Column[] } {
|
|
105
91
|
const used = (cols: Column[]) => cols.reduce((sum, c) => sum + c.width + 1, 0);
|
|
106
92
|
let columns = allColumns;
|
|
107
|
-
for (const label of ["Share", "Hit%", "Cache", "Out", "In", "Reqs", "Δ"
|
|
93
|
+
for (const label of ["Share", "Hit%", "Cache", "Out", "In", "Reqs", "Δ"]) {
|
|
108
94
|
if (width - used(columns) >= MIN_NAME_WIDTH) break;
|
|
109
95
|
columns = columns.filter((c) => c.label !== label);
|
|
110
96
|
}
|
|
@@ -115,9 +101,6 @@ const padWidth = (s: string, w: number): string => s + " ".repeat(Math.max(0, w
|
|
|
115
101
|
|
|
116
102
|
function displayName(mode: GroupMode, name: string): string {
|
|
117
103
|
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" })}`;
|
|
121
104
|
if (mode !== "project") return name;
|
|
122
105
|
if (!name) return "(no cwd)";
|
|
123
106
|
const home = homedir();
|
|
@@ -139,17 +122,20 @@ function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCos
|
|
|
139
122
|
.trimEnd();
|
|
140
123
|
}
|
|
141
124
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
|
|
125
|
+
type SparkBar = { label: string; char: string };
|
|
126
|
+
|
|
127
|
+
function sparkline(daily: DailyCost[], width: number): { first: string; last: string; bars: SparkBar[] } | undefined {
|
|
128
|
+
const recent = daily.slice(-Math.max(1, width - 12));
|
|
129
|
+
if (recent.length === 0) return undefined;
|
|
147
130
|
let max = 0;
|
|
148
|
-
for (const
|
|
131
|
+
for (const day of recent) if (day.cost > max) max = day.cost;
|
|
149
132
|
return {
|
|
150
|
-
first,
|
|
151
|
-
|
|
152
|
-
|
|
133
|
+
first: recent[0]!.label,
|
|
134
|
+
last: recent[recent.length - 1]!.label,
|
|
135
|
+
bars: recent.map(({ label, cost }) => ({
|
|
136
|
+
label,
|
|
137
|
+
char: cost <= 0 ? " " : SPARK_BARS[Math.max(1, Math.round((7 * cost) / max))]!,
|
|
138
|
+
})),
|
|
153
139
|
};
|
|
154
140
|
}
|
|
155
141
|
|
|
@@ -185,7 +171,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
185
171
|
overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 },
|
|
186
172
|
} as const;
|
|
187
173
|
await ctx.ui.custom((tui, theme, keys, done) => {
|
|
188
|
-
let period = 0;
|
|
189
174
|
let group = 0;
|
|
190
175
|
let cursor = 0;
|
|
191
176
|
let top = 0;
|
|
@@ -194,29 +179,22 @@ export default function (pi: ExtensionAPI) {
|
|
|
194
179
|
let body: BodyRow[] = [];
|
|
195
180
|
const stack: Frame[] = [];
|
|
196
181
|
const filters = () => stack.flatMap((frame) => frame.filters);
|
|
197
|
-
const
|
|
182
|
+
const dayFilter = () => filters().findLast((f) => f.mode === "day");
|
|
198
183
|
const derive = (source: UsageRecord[]) => {
|
|
199
184
|
const active = filters();
|
|
200
185
|
const records = source.filter((record) =>
|
|
201
|
-
active.every((f) =>
|
|
186
|
+
active.every((f) => f.mode === "day" || matchesFilter(record, f)),
|
|
202
187
|
);
|
|
203
|
-
const
|
|
188
|
+
const day = active.findLast((f) => f.mode === "day")?.key;
|
|
189
|
+
const window = usageWindow(records, day);
|
|
204
190
|
const mode = GROUPS[group]!;
|
|
205
191
|
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
192
|
const body = flatten(buildRows(records, window.since, mode, window.until), mode);
|
|
211
|
-
|
|
212
|
-
return { records, window, mode, summary, previous, body, series };
|
|
193
|
+
return { mode, summary, body, compare: day ? undefined : comparison(records) };
|
|
213
194
|
};
|
|
214
195
|
const getView = cacheView(() => derive(state.records!));
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
clearTimeFilters(stack);
|
|
218
|
-
cursor = top = 0;
|
|
219
|
-
};
|
|
196
|
+
let allDays: DailyCost[] | undefined;
|
|
197
|
+
const allDaily = () => (allDays ??= dailyTotals(state.records!));
|
|
220
198
|
render = () => tui.requestRender();
|
|
221
199
|
void loaded.then(render);
|
|
222
200
|
const colorDelta = (delta: number | undefined): string => {
|
|
@@ -227,23 +205,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
227
205
|
: "▲new";
|
|
228
206
|
return theme.fg(delta > 0 ? "error" : "success", text);
|
|
229
207
|
};
|
|
230
|
-
const
|
|
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
|
-
];
|
|
208
|
+
const deltaColumn: Column = { label: "Δ", width: 9, cell: (_s, _r, _t, row) => colorDelta(row?.delta) };
|
|
238
209
|
const title = (width: number): string => {
|
|
239
210
|
const tab = (label: string, active: boolean) =>
|
|
240
211
|
active ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `);
|
|
241
|
-
const left =
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
const
|
|
212
|
+
const left =
|
|
213
|
+
theme.fg("accent", theme.bold("Usage")) +
|
|
214
|
+
filters()
|
|
215
|
+
.map((f) => ` › ${displayName(f.mode, f.key)}`)
|
|
216
|
+
.join("");
|
|
217
|
+
const tabs = GROUPS.map((g, i) => (i === 0 && dayFilter() ? "" : tab(GROUP_LABELS[g], i === group)))
|
|
218
|
+
.filter(Boolean)
|
|
219
|
+
.join(" ");
|
|
220
|
+
const hint = theme.fg("dim", " (tab/←→)");
|
|
221
|
+
const right =
|
|
222
|
+
tabs + (visibleWidth(left) + visibleWidth(tabs) + visibleWidth(hint) + 1 <= width ? hint : "");
|
|
247
223
|
const leftWidth = Math.max(0, width - visibleWidth(right) - 1);
|
|
248
224
|
return truncateToWidth(
|
|
249
225
|
truncateToWidth(left, leftWidth, "…") +
|
|
@@ -256,10 +232,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
256
232
|
};
|
|
257
233
|
const footer = (width: number): string =>
|
|
258
234
|
truncateToWidth(
|
|
259
|
-
theme.fg(
|
|
260
|
-
"dim",
|
|
261
|
-
`enter open · esc back · v group · tab period · ←→ ${timeIsInnermost() ? "bucket" : "period"} · q close · ↑↓ scroll`,
|
|
262
|
-
),
|
|
235
|
+
theme.fg("dim", "enter open · esc back · tab/←→ group · [ ] day · q close · ↑↓ scroll"),
|
|
263
236
|
width,
|
|
264
237
|
);
|
|
265
238
|
return {
|
|
@@ -279,22 +252,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
279
252
|
lines.push(rule, footer(width));
|
|
280
253
|
return lines.slice(0, rows);
|
|
281
254
|
}
|
|
282
|
-
const view = getView(
|
|
283
|
-
const {
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
: `prev ${window.days}d`;
|
|
288
|
-
const trend = previous
|
|
289
|
-
? ` ${colorDelta(percentChange(summary.stats.cost, previous.stats.cost))} vs ${label}`
|
|
290
|
-
: "";
|
|
255
|
+
const view = getView(GROUPS[group]!, filters());
|
|
256
|
+
const { mode, summary, compare } = view;
|
|
257
|
+
const first = compare
|
|
258
|
+
? `Today ${formatCost(compare.today)} · This week ${formatCost(compare.week)}/day ${colorDelta(percentChange(compare.week, compare.lastWeek))} vs last week · This month ${formatCost(compare.month)}/day ${colorDelta(percentChange(compare.month, compare.lastMonth))} vs last month`
|
|
259
|
+
: `Cost ${formatCost(summary.stats.cost)}`;
|
|
291
260
|
lines.push(
|
|
261
|
+
truncateToWidth(first, width),
|
|
292
262
|
truncateToWidth(
|
|
293
|
-
`
|
|
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)}`,
|
|
263
|
+
`In ${formatTokens(summary.stats.input)} · Out ${formatTokens(summary.stats.output)} · Cache ${formatTokens(summary.stats.cacheRead + summary.stats.cacheWrite)} · Hit ${hitPct(summary.stats)} · Reqs ${formatTokens(summary.requests)} · Sessions ${formatTokens(summary.sessions)}`,
|
|
298
264
|
width,
|
|
299
265
|
),
|
|
300
266
|
);
|
|
@@ -302,20 +268,30 @@ export default function (pi: ExtensionAPI) {
|
|
|
302
268
|
rowCount = body.length;
|
|
303
269
|
cursor = Math.min(cursor, Math.max(0, rowCount - 1));
|
|
304
270
|
const selected = body[cursor];
|
|
305
|
-
const
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
const spark = sparkline(daily, width);
|
|
271
|
+
const contextDay = dayFilter()?.key ?? (mode === "day" ? selected?.key : undefined);
|
|
272
|
+
const contextLabel = contextDay?.slice(5);
|
|
273
|
+
const spark = sparkline(allDaily(), width);
|
|
309
274
|
if (spark)
|
|
310
275
|
lines.push(
|
|
311
276
|
truncateToWidth(
|
|
312
|
-
|
|
277
|
+
theme.fg("dim", `${spark.first} `) +
|
|
278
|
+
spark.bars
|
|
279
|
+
.map((bar) =>
|
|
280
|
+
theme.fg(
|
|
281
|
+
contextLabel === undefined || bar.label === contextLabel
|
|
282
|
+
? "accent"
|
|
283
|
+
: "borderMuted",
|
|
284
|
+
bar.char,
|
|
285
|
+
),
|
|
286
|
+
)
|
|
287
|
+
.join("") +
|
|
288
|
+
theme.fg("dim", ` ${spark.last}`),
|
|
313
289
|
width,
|
|
314
290
|
),
|
|
315
291
|
);
|
|
316
292
|
const { nameWidth, columns } = layout(
|
|
317
293
|
width,
|
|
318
|
-
|
|
294
|
+
mode === "day" ? [COLUMNS[0]!, deltaColumn, ...COLUMNS.slice(1)] : COLUMNS,
|
|
319
295
|
);
|
|
320
296
|
const header = mode === "provider" ? "Provider / Model" : GROUP_LABELS[mode];
|
|
321
297
|
lines.push(
|
|
@@ -335,7 +311,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
335
311
|
if (cursor < top) top = cursor;
|
|
336
312
|
if (viewHeight > 0 && cursor >= top + viewHeight) top = cursor - viewHeight + 1;
|
|
337
313
|
const visible = body.slice(top, top + viewHeight);
|
|
338
|
-
if (rowCount === 0) lines.push(theme.fg("dim", " No usage
|
|
314
|
+
if (rowCount === 0) lines.push(theme.fg("dim", " No usage"));
|
|
339
315
|
for (const [i, row] of visible.entries()) {
|
|
340
316
|
let line = tableLine(nameWidth, columns, row, summary.stats.cost);
|
|
341
317
|
if (top + i === cursor) line = theme.bg("selectedBg", line);
|
|
@@ -373,18 +349,24 @@ export default function (pi: ExtensionAPI) {
|
|
|
373
349
|
row.parent === undefined ? [] : [{ mode: "provider", key: row.parent }];
|
|
374
350
|
selected.push({ mode: rowMode, key: row.key });
|
|
375
351
|
stack.push({ filters: selected, group, cursor, top });
|
|
376
|
-
|
|
352
|
+
// Land on the first grouping that is not already filtered.
|
|
353
|
+
const used = new Set(filters().map((f) => f.mode));
|
|
354
|
+
group = GROUPS.findIndex((g) => !used.has(g));
|
|
355
|
+
if (group < 0) group = dayFilter() ? 1 : 0;
|
|
377
356
|
cursor = top = 0;
|
|
378
|
-
} else if ((
|
|
379
|
-
const
|
|
380
|
-
const next =
|
|
381
|
-
if (next
|
|
382
|
-
} else if (
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
357
|
+
} else if ((data === "[" || data === "]") && filters().at(-1)?.mode === "day") {
|
|
358
|
+
const filter = filters().at(-1)!;
|
|
359
|
+
const next = dayKey(dayWindow(filter.key, data === "]" ? 1 : -1).since);
|
|
360
|
+
if (next <= dayKey(Date.now())) filter.key = next;
|
|
361
|
+
} else if (
|
|
362
|
+
matchesKey(data, "tab") ||
|
|
363
|
+
matchesKey(data, "right") ||
|
|
364
|
+
matchesKey(data, "shift+tab") ||
|
|
365
|
+
matchesKey(data, "left")
|
|
366
|
+
) {
|
|
367
|
+
const offset = matchesKey(data, "tab") || matchesKey(data, "right") ? 1 : -1;
|
|
368
|
+
do group = (group + offset + GROUPS.length) % GROUPS.length;
|
|
369
|
+
while (group === 0 && dayFilter());
|
|
388
370
|
cursor = top = 0;
|
|
389
371
|
} else if (keys.matches(data, "tui.select.up") || data === "k") cursor -= 1;
|
|
390
372
|
else if (keys.matches(data, "tui.select.down") || data === "j") cursor += 1;
|
package/package.json
CHANGED
package/usage.ts
CHANGED
|
@@ -28,7 +28,7 @@ export type Stats = {
|
|
|
28
28
|
cacheWrite: number;
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
-
|
|
31
|
+
function emptyStats(): Stats {
|
|
32
32
|
return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
33
33
|
}
|
|
34
34
|
|
|
@@ -129,27 +129,13 @@ function addStats(stats: Stats, record: UsageRecord): void {
|
|
|
129
129
|
stats.cacheWrite += record.cacheWrite;
|
|
130
130
|
}
|
|
131
131
|
|
|
132
|
-
type
|
|
133
|
-
export type GroupMode = "provider" | "model" | "project" | TimeMode;
|
|
132
|
+
export type GroupMode = "day" | "provider" | "model" | "project";
|
|
134
133
|
export type UsageFilter = { mode: GroupMode; key: string };
|
|
135
134
|
|
|
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
135
|
export function cacheView<T>(derive: () => T) {
|
|
150
136
|
let cached: { key: string; value: T } | undefined;
|
|
151
|
-
return (
|
|
152
|
-
const key = JSON.stringify([
|
|
137
|
+
return (mode: GroupMode, filters: UsageFilter[], now = Date.now()): T => {
|
|
138
|
+
const key = JSON.stringify([mode, filters, dayKey(now)]);
|
|
153
139
|
if (!cached || cached.key !== key) cached = { key, value: derive() };
|
|
154
140
|
return cached.value;
|
|
155
141
|
};
|
|
@@ -160,47 +146,18 @@ export function dayKey(ts: number): string {
|
|
|
160
146
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
161
147
|
}
|
|
162
148
|
|
|
163
|
-
function
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
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;
|
|
149
|
+
export function startOfDay(ts: number): number {
|
|
150
|
+
const date = new Date(ts);
|
|
151
|
+
date.setHours(0, 0, 0, 0);
|
|
152
|
+
return date.getTime();
|
|
175
153
|
}
|
|
176
154
|
|
|
177
|
-
export function
|
|
178
|
-
const date = new Date(`${
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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;
|
|
155
|
+
export function dayWindow(key: string, offset = 0): { since: number; until: number } {
|
|
156
|
+
const date = new Date(`${key}T00:00`);
|
|
157
|
+
date.setDate(date.getDate() + offset);
|
|
158
|
+
const since = startOfDay(date.getTime());
|
|
159
|
+
date.setDate(date.getDate() + 1);
|
|
160
|
+
return { since, until: startOfDay(date.getTime()) };
|
|
204
161
|
}
|
|
205
162
|
|
|
206
163
|
// UTC ordinals count local calendar days without DST changing their length.
|
|
@@ -218,37 +175,52 @@ export function percentChange(current: number, previous: number): number {
|
|
|
218
175
|
}
|
|
219
176
|
|
|
220
177
|
function recordKey(record: UsageRecord, mode: GroupMode): string {
|
|
221
|
-
return
|
|
178
|
+
return mode === "day" ? dayKey(record.ts) : mode === "project" ? record.cwd : record[mode];
|
|
222
179
|
}
|
|
223
180
|
|
|
224
181
|
export function matchesFilter(record: UsageRecord, filter: UsageFilter): boolean {
|
|
225
182
|
return recordKey(record, filter.mode) === filter.key;
|
|
226
183
|
}
|
|
227
184
|
|
|
228
|
-
export function usageWindow(records: UsageRecord[],
|
|
229
|
-
|
|
230
|
-
const
|
|
231
|
-
let
|
|
232
|
-
|
|
233
|
-
|
|
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) };
|
|
185
|
+
export function usageWindow(records: UsageRecord[], day?: string, now = Date.now()) {
|
|
186
|
+
if (day) return dayWindow(day);
|
|
187
|
+
const until = dayWindow(dayKey(now)).until;
|
|
188
|
+
let first = Infinity;
|
|
189
|
+
for (const record of records) if (record.ts < until) first = Math.min(first, record.ts);
|
|
190
|
+
return { since: first === Infinity ? until : dayWindow(dayKey(first)).since, until };
|
|
248
191
|
}
|
|
249
192
|
|
|
250
|
-
export function
|
|
251
|
-
|
|
193
|
+
export function comparison(records: UsageRecord[], now = Date.now()) {
|
|
194
|
+
const { since: today, until } = dayWindow(dayKey(now));
|
|
195
|
+
const week = new Date(today);
|
|
196
|
+
week.setDate(week.getDate() - ((week.getDay() + 6) % 7));
|
|
197
|
+
const weekStart = startOfDay(week.getTime());
|
|
198
|
+
const lastWeek = dayWindow(dayKey(weekStart), -7).since;
|
|
199
|
+
const month = new Date(today);
|
|
200
|
+
month.setDate(1);
|
|
201
|
+
const monthStart = startOfDay(month.getTime());
|
|
202
|
+
month.setMonth(month.getMonth() - 1);
|
|
203
|
+
const lastMonth = startOfDay(month.getTime());
|
|
204
|
+
let todayCost = 0,
|
|
205
|
+
weekCost = 0,
|
|
206
|
+
lastWeekCost = 0,
|
|
207
|
+
monthCost = 0,
|
|
208
|
+
lastMonthCost = 0;
|
|
209
|
+
for (const record of records) {
|
|
210
|
+
if (record.ts >= until) continue;
|
|
211
|
+
if (record.ts >= today) todayCost += record.cost;
|
|
212
|
+
if (record.ts >= weekStart) weekCost += record.cost;
|
|
213
|
+
else if (record.ts >= lastWeek) lastWeekCost += record.cost;
|
|
214
|
+
if (record.ts >= monthStart) monthCost += record.cost;
|
|
215
|
+
else if (record.ts >= lastMonth) lastMonthCost += record.cost;
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
today: todayCost,
|
|
219
|
+
week: weekCost / windowDays(weekStart, until),
|
|
220
|
+
lastWeek: lastWeekCost / 7,
|
|
221
|
+
month: monthCost / windowDays(monthStart, until),
|
|
222
|
+
lastMonth: lastMonthCost / windowDays(lastMonth, monthStart),
|
|
223
|
+
};
|
|
252
224
|
}
|
|
253
225
|
|
|
254
226
|
export type GroupRow = {
|
|
@@ -256,7 +228,6 @@ export type GroupRow = {
|
|
|
256
228
|
name: string;
|
|
257
229
|
stats: Stats;
|
|
258
230
|
requests: number;
|
|
259
|
-
perDay?: number;
|
|
260
231
|
delta?: number;
|
|
261
232
|
/** Nested model rows; only produced by provider grouping. */
|
|
262
233
|
children?: GroupRow[];
|
|
@@ -277,7 +248,7 @@ export function buildRows(
|
|
|
277
248
|
mode: GroupMode = "provider",
|
|
278
249
|
untilMs = Infinity,
|
|
279
250
|
): GroupRow[] {
|
|
280
|
-
if (
|
|
251
|
+
if (mode === "day" && (!Number.isFinite(sinceMs) || !Number.isFinite(untilMs)))
|
|
281
252
|
throw new RangeError("Time grouping requires a finite window");
|
|
282
253
|
const groups = new Map<string, Tally>();
|
|
283
254
|
for (const record of records) {
|
|
@@ -300,30 +271,20 @@ export function buildRows(
|
|
|
300
271
|
model.requests++;
|
|
301
272
|
}
|
|
302
273
|
}
|
|
303
|
-
if (
|
|
274
|
+
if (mode === "day") {
|
|
304
275
|
if (sinceMs < untilMs) {
|
|
305
|
-
let key =
|
|
306
|
-
const last =
|
|
276
|
+
let key = dayKey(sinceMs);
|
|
277
|
+
const last = dayKey(untilMs - 1);
|
|
307
278
|
while (key <= last) {
|
|
308
279
|
if (!groups.has(key)) groups.set(key, newTally());
|
|
309
|
-
key =
|
|
280
|
+
key = dayKey(dayWindow(key).until);
|
|
310
281
|
}
|
|
311
282
|
}
|
|
312
283
|
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
|
-
})
|
|
284
|
+
.map(([key, group]): GroupRow => ({ key, name: key, stats: group.stats, requests: group.requests }))
|
|
324
285
|
.sort((a, b) => b.key.localeCompare(a.key));
|
|
325
286
|
for (let i = 0; i + 1 < rows.length; i++)
|
|
326
|
-
rows[i]!.delta = percentChange(rows[i]!.
|
|
287
|
+
rows[i]!.delta = percentChange(rows[i]!.stats.cost, rows[i + 1]!.stats.cost);
|
|
327
288
|
return rows;
|
|
328
289
|
}
|
|
329
290
|
const toRow = ([name, group]: [string, Tally]): GroupRow => ({
|
|
@@ -341,8 +302,6 @@ export type Summary = {
|
|
|
341
302
|
requests: number;
|
|
342
303
|
/** Distinct session ids (files) seen in the window. */
|
|
343
304
|
sessions: number;
|
|
344
|
-
/** cacheRead / (input + cacheRead + cacheWrite); 0 without any tokens. */
|
|
345
|
-
hit: number;
|
|
346
305
|
};
|
|
347
306
|
|
|
348
307
|
/** Totals for the summary block: one pass over [sinceMs, untilMs). */
|
|
@@ -356,13 +315,7 @@ export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinit
|
|
|
356
315
|
requests++;
|
|
357
316
|
sessions.add(record.sessionId);
|
|
358
317
|
}
|
|
359
|
-
|
|
360
|
-
return {
|
|
361
|
-
stats,
|
|
362
|
-
requests,
|
|
363
|
-
sessions: sessions.size,
|
|
364
|
-
hit: cacheTotal > 0 ? stats.cacheRead / cacheTotal : 0,
|
|
365
|
-
};
|
|
318
|
+
return { stats, requests, sessions: sessions.size };
|
|
366
319
|
}
|
|
367
320
|
|
|
368
321
|
export type DailyCost = { label: string; cost: number };
|
|
@@ -374,8 +327,7 @@ export function buildDailySeries(
|
|
|
374
327
|
since: number,
|
|
375
328
|
until: number,
|
|
376
329
|
mode: GroupMode,
|
|
377
|
-
|
|
378
|
-
): { total: DailyCost[]; rows: Map<string, DailyCost[]> } {
|
|
330
|
+
): { total: DailyCost[]; rows: Map<string, Map<number, number>> } {
|
|
379
331
|
const days = windowDays(since, until);
|
|
380
332
|
const total: DailyCost[] = [];
|
|
381
333
|
const positions = new Map<string, number>();
|
|
@@ -384,7 +336,7 @@ export function buildDailySeries(
|
|
|
384
336
|
const key = dayKey(cursor);
|
|
385
337
|
positions.set(key, i);
|
|
386
338
|
total.push({ label: key.slice(5), cost: 0 });
|
|
387
|
-
cursor =
|
|
339
|
+
cursor = dayWindow(key).until;
|
|
388
340
|
}
|
|
389
341
|
const costs = new Map<string, Map<number, number>>();
|
|
390
342
|
const add = (key: string, index: number, cost: number) => {
|
|
@@ -401,28 +353,11 @@ export function buildDailySeries(
|
|
|
401
353
|
add(seriesKey(key), index, record.cost);
|
|
402
354
|
if (mode === "provider") add(seriesKey(record.model, record.provider), index, record.cost);
|
|
403
355
|
}
|
|
404
|
-
|
|
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
|
-
);
|
|
415
|
-
}
|
|
416
|
-
return { total, rows: result };
|
|
356
|
+
return { total, rows: costs };
|
|
417
357
|
}
|
|
418
358
|
|
|
419
|
-
/**
|
|
420
|
-
export function
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
for (let i = 0; i < days.length; i += perBar) {
|
|
424
|
-
const group = days.slice(i, i + perBar);
|
|
425
|
-
bars.push({ label: group[0]!.label, cost: group.reduce((sum, d) => sum + d.cost, 0) });
|
|
426
|
-
}
|
|
427
|
-
return bars;
|
|
359
|
+
/** Total cost per local calendar day from the first recorded day through today. */
|
|
360
|
+
export function dailyTotals(records: UsageRecord[], now = Date.now()): DailyCost[] {
|
|
361
|
+
const { since, until } = usageWindow(records, undefined, now);
|
|
362
|
+
return buildDailySeries(records, since, until, "day").total;
|
|
428
363
|
}
|