@deathbeam/pi-usage 0.0.4 → 0.0.5
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 +54 -86
- package/package.json +1 -1
- package/usage.ts +61 -113
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 shows the selected row over all history and is hidden when a day is open.
|
|
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
|
@@ -10,16 +10,13 @@ import {
|
|
|
10
10
|
buildDailySeries,
|
|
11
11
|
buildRows,
|
|
12
12
|
cacheView,
|
|
13
|
-
clearTimeFilters,
|
|
14
13
|
collectUsage,
|
|
14
|
+
comparison,
|
|
15
15
|
dayKey,
|
|
16
|
-
|
|
17
|
-
isTimeMode,
|
|
16
|
+
dayWindow,
|
|
18
17
|
matchesFilter,
|
|
19
18
|
percentChange,
|
|
20
|
-
previousSummary,
|
|
21
19
|
seriesKey,
|
|
22
|
-
stepFilter,
|
|
23
20
|
summarize,
|
|
24
21
|
usageWindow,
|
|
25
22
|
type DailyCost,
|
|
@@ -38,28 +35,19 @@ type Column = {
|
|
|
38
35
|
type BodyRow = GroupRow & { parent?: string };
|
|
39
36
|
type Frame = { filters: UsageFilter[]; group: number; cursor: number; top: number };
|
|
40
37
|
|
|
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[];
|
|
38
|
+
const GROUPS = ["day", "provider", "model", "project"] as const satisfies readonly GroupMode[];
|
|
49
39
|
const GROUP_LABELS: Record<GroupMode, string> = {
|
|
40
|
+
day: "Day",
|
|
50
41
|
provider: "Provider",
|
|
51
42
|
model: "Model",
|
|
52
43
|
project: "Project",
|
|
53
|
-
day: "Day",
|
|
54
|
-
week: "Week",
|
|
55
|
-
month: "Month",
|
|
56
44
|
};
|
|
57
45
|
|
|
58
46
|
const COLUMNS: Column[] = [
|
|
59
47
|
{
|
|
60
48
|
label: "Cost",
|
|
61
49
|
width: 10,
|
|
62
|
-
cell: (s
|
|
50
|
+
cell: (s) => formatCost(s.cost),
|
|
63
51
|
},
|
|
64
52
|
{
|
|
65
53
|
label: "Share",
|
|
@@ -81,8 +69,8 @@ const COLUMNS: Column[] = [
|
|
|
81
69
|
const SPARK_BARS = "▁▂▃▄▅▆▇█";
|
|
82
70
|
const MIN_NAME_WIDTH = 12;
|
|
83
71
|
|
|
84
|
-
function formatCost(cost: number
|
|
85
|
-
if (cost === 0) return
|
|
72
|
+
function formatCost(cost: number): string {
|
|
73
|
+
if (cost === 0) return "$0.00";
|
|
86
74
|
if (cost < 0.01) return `$${cost.toFixed(4)}`;
|
|
87
75
|
if (cost < 100) return `$${cost.toFixed(2)}`;
|
|
88
76
|
return `$${Math.round(cost).toLocaleString("en-US")}`;
|
|
@@ -104,7 +92,7 @@ function hitPct(stats: Stats): string {
|
|
|
104
92
|
function layout(width: number, allColumns: Column[]): { nameWidth: number; columns: Column[] } {
|
|
105
93
|
const used = (cols: Column[]) => cols.reduce((sum, c) => sum + c.width + 1, 0);
|
|
106
94
|
let columns = allColumns;
|
|
107
|
-
for (const label of ["Share", "Hit%", "Cache", "Out", "In", "Reqs", "Δ"
|
|
95
|
+
for (const label of ["Share", "Hit%", "Cache", "Out", "In", "Reqs", "Δ"]) {
|
|
108
96
|
if (width - used(columns) >= MIN_NAME_WIDTH) break;
|
|
109
97
|
columns = columns.filter((c) => c.label !== label);
|
|
110
98
|
}
|
|
@@ -115,9 +103,6 @@ const padWidth = (s: string, w: number): string => s + " ".repeat(Math.max(0, w
|
|
|
115
103
|
|
|
116
104
|
function displayName(mode: GroupMode, name: string): string {
|
|
117
105
|
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
106
|
if (mode !== "project") return name;
|
|
122
107
|
if (!name) return "(no cwd)";
|
|
123
108
|
const home = homedir();
|
|
@@ -185,7 +170,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
185
170
|
overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 },
|
|
186
171
|
} as const;
|
|
187
172
|
await ctx.ui.custom((tui, theme, keys, done) => {
|
|
188
|
-
let period = 0;
|
|
189
173
|
let group = 0;
|
|
190
174
|
let cursor = 0;
|
|
191
175
|
let top = 0;
|
|
@@ -194,29 +178,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
194
178
|
let body: BodyRow[] = [];
|
|
195
179
|
const stack: Frame[] = [];
|
|
196
180
|
const filters = () => stack.flatMap((frame) => frame.filters);
|
|
197
|
-
const
|
|
181
|
+
const dayFilter = () => filters().findLast((f) => f.mode === "day");
|
|
198
182
|
const derive = (source: UsageRecord[]) => {
|
|
199
183
|
const active = filters();
|
|
200
184
|
const records = source.filter((record) =>
|
|
201
|
-
active.every((f) =>
|
|
185
|
+
active.every((f) => f.mode === "day" || matchesFilter(record, f)),
|
|
202
186
|
);
|
|
203
|
-
const
|
|
187
|
+
const day = active.findLast((f) => f.mode === "day")?.key;
|
|
188
|
+
const window = usageWindow(records, day);
|
|
204
189
|
const mode = GROUPS[group]!;
|
|
205
190
|
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
191
|
const body = flatten(buildRows(records, window.since, mode, window.until), mode);
|
|
211
|
-
const series = buildDailySeries(records, window.since, window.until, mode
|
|
212
|
-
return {
|
|
192
|
+
const series = day ? undefined : buildDailySeries(records, window.since, window.until, mode);
|
|
193
|
+
return { mode, summary, body, series, compare: day ? undefined : comparison(records) };
|
|
213
194
|
};
|
|
214
195
|
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
|
-
};
|
|
220
196
|
render = () => tui.requestRender();
|
|
221
197
|
void loaded.then(render);
|
|
222
198
|
const colorDelta = (delta: number | undefined): string => {
|
|
@@ -227,23 +203,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
227
203
|
: "▲new";
|
|
228
204
|
return theme.fg(delta > 0 ? "error" : "success", text);
|
|
229
205
|
};
|
|
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
|
-
];
|
|
206
|
+
const deltaColumn: Column = { label: "Δ", width: 9, cell: (_s, _r, _t, row) => colorDelta(row?.delta) };
|
|
238
207
|
const title = (width: number): string => {
|
|
239
208
|
const tab = (label: string, active: boolean) =>
|
|
240
209
|
active ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `);
|
|
241
|
-
const left =
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
const
|
|
210
|
+
const left =
|
|
211
|
+
theme.fg("accent", theme.bold("Usage")) +
|
|
212
|
+
filters()
|
|
213
|
+
.map((f) => ` › ${displayName(f.mode, f.key)}`)
|
|
214
|
+
.join("");
|
|
215
|
+
const tabs = GROUPS.map((g, i) => (i === 0 && dayFilter() ? "" : tab(GROUP_LABELS[g], i === group)))
|
|
216
|
+
.filter(Boolean)
|
|
217
|
+
.join(" ");
|
|
218
|
+
const hint = theme.fg("dim", " (tab/←→)");
|
|
219
|
+
const right =
|
|
220
|
+
tabs + (visibleWidth(left) + visibleWidth(tabs) + visibleWidth(hint) + 1 <= width ? hint : "");
|
|
247
221
|
const leftWidth = Math.max(0, width - visibleWidth(right) - 1);
|
|
248
222
|
return truncateToWidth(
|
|
249
223
|
truncateToWidth(left, leftWidth, "…") +
|
|
@@ -256,10 +230,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
256
230
|
};
|
|
257
231
|
const footer = (width: number): string =>
|
|
258
232
|
truncateToWidth(
|
|
259
|
-
theme.fg(
|
|
260
|
-
"dim",
|
|
261
|
-
`enter open · esc back · v group · tab period · ←→ ${timeIsInnermost() ? "bucket" : "period"} · q close · ↑↓ scroll`,
|
|
262
|
-
),
|
|
233
|
+
theme.fg("dim", "enter open · esc back · tab/←→ group · [ ] day · q close · ↑↓ scroll"),
|
|
263
234
|
width,
|
|
264
235
|
);
|
|
265
236
|
return {
|
|
@@ -279,22 +250,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
279
250
|
lines.push(rule, footer(width));
|
|
280
251
|
return lines.slice(0, rows);
|
|
281
252
|
}
|
|
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
|
-
: "";
|
|
253
|
+
const view = getView(GROUPS[group]!, filters());
|
|
254
|
+
const { mode, summary, series, compare } = view;
|
|
255
|
+
const first = compare
|
|
256
|
+
? `Today ${formatCost(compare.today)} · This week ${formatCost(compare.week)}/day ${colorDelta(percentChange(compare.week, compare.lastWeek))} vs last week · This month ${formatCost(compare.month)}/day ${colorDelta(percentChange(compare.month, compare.lastMonth))} vs last month`
|
|
257
|
+
: `Cost ${formatCost(summary.stats.cost)}`;
|
|
291
258
|
lines.push(
|
|
259
|
+
truncateToWidth(first, width),
|
|
292
260
|
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)}`,
|
|
261
|
+
`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
262
|
width,
|
|
299
263
|
),
|
|
300
264
|
);
|
|
@@ -302,10 +266,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
302
266
|
rowCount = body.length;
|
|
303
267
|
cursor = Math.min(cursor, Math.max(0, rowCount - 1));
|
|
304
268
|
const selected = body[cursor];
|
|
269
|
+
const costs = selected && series?.rows.get(seriesKey(selected.key, selected.parent));
|
|
305
270
|
const daily = selected
|
|
306
|
-
?
|
|
307
|
-
: series
|
|
308
|
-
const spark = sparkline(daily, width);
|
|
271
|
+
? series?.total.map((d, i) => ({ ...d, cost: costs?.get(i) ?? 0 }))
|
|
272
|
+
: series?.total;
|
|
273
|
+
const spark = daily && sparkline(daily, width);
|
|
309
274
|
if (spark)
|
|
310
275
|
lines.push(
|
|
311
276
|
truncateToWidth(
|
|
@@ -315,7 +280,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
315
280
|
);
|
|
316
281
|
const { nameWidth, columns } = layout(
|
|
317
282
|
width,
|
|
318
|
-
|
|
283
|
+
mode === "day" ? [COLUMNS[0]!, deltaColumn, ...COLUMNS.slice(1)] : COLUMNS,
|
|
319
284
|
);
|
|
320
285
|
const header = mode === "provider" ? "Provider / Model" : GROUP_LABELS[mode];
|
|
321
286
|
lines.push(
|
|
@@ -335,7 +300,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
335
300
|
if (cursor < top) top = cursor;
|
|
336
301
|
if (viewHeight > 0 && cursor >= top + viewHeight) top = cursor - viewHeight + 1;
|
|
337
302
|
const visible = body.slice(top, top + viewHeight);
|
|
338
|
-
if (rowCount === 0) lines.push(theme.fg("dim", " No usage
|
|
303
|
+
if (rowCount === 0) lines.push(theme.fg("dim", " No usage"));
|
|
339
304
|
for (const [i, row] of visible.entries()) {
|
|
340
305
|
let line = tableLine(nameWidth, columns, row, summary.stats.cost);
|
|
341
306
|
if (top + i === cursor) line = theme.bg("selectedBg", line);
|
|
@@ -373,18 +338,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
373
338
|
row.parent === undefined ? [] : [{ mode: "provider", key: row.parent }];
|
|
374
339
|
selected.push({ mode: rowMode, key: row.key });
|
|
375
340
|
stack.push({ filters: selected, group, cursor, top });
|
|
376
|
-
group =
|
|
341
|
+
group = rowMode === "day" ? 1 : 0;
|
|
377
342
|
cursor = top = 0;
|
|
378
|
-
} else if ((
|
|
379
|
-
const
|
|
380
|
-
const next =
|
|
381
|
-
if (next
|
|
382
|
-
} else if (
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
343
|
+
} else if ((data === "[" || data === "]") && filters().at(-1)?.mode === "day") {
|
|
344
|
+
const filter = filters().at(-1)!;
|
|
345
|
+
const next = dayKey(dayWindow(filter.key, data === "]" ? 1 : -1).since);
|
|
346
|
+
if (next <= dayKey(Date.now())) filter.key = next;
|
|
347
|
+
} else if (
|
|
348
|
+
matchesKey(data, "tab") ||
|
|
349
|
+
matchesKey(data, "right") ||
|
|
350
|
+
matchesKey(data, "shift+tab") ||
|
|
351
|
+
matchesKey(data, "left")
|
|
352
|
+
) {
|
|
353
|
+
const offset = matchesKey(data, "tab") || matchesKey(data, "right") ? 1 : -1;
|
|
354
|
+
do group = (group + offset + GROUPS.length) % GROUPS.length;
|
|
355
|
+
while (group === 0 && dayFilter());
|
|
388
356
|
cursor = top = 0;
|
|
389
357
|
} else if (keys.matches(data, "tui.select.up") || data === "k") cursor -= 1;
|
|
390
358
|
else if (keys.matches(data, "tui.select.down") || data === "j") cursor += 1;
|
package/package.json
CHANGED
package/usage.ts
CHANGED
|
@@ -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,49 +146,17 @@ 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;
|
|
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);
|
|
149
|
+
export function dayWindow(key: string, offset = 0): { since: number; until: number } {
|
|
150
|
+
const date = new Date(`${key}T00:00`);
|
|
151
|
+
date.setDate(date.getDate() + offset);
|
|
152
|
+
date.setHours(0, 0, 0, 0);
|
|
186
153
|
const since = date.getTime();
|
|
187
|
-
|
|
154
|
+
date.setDate(date.getDate() + 1);
|
|
155
|
+
// A skipped midnight can leave 01:00 on the next calendar day.
|
|
156
|
+
date.setHours(0, 0, 0, 0);
|
|
188
157
|
return { since, until: date.getTime() };
|
|
189
158
|
}
|
|
190
159
|
|
|
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
160
|
// UTC ordinals count local calendar days without DST changing their length.
|
|
207
161
|
export function windowDays(since: number, until: number): number {
|
|
208
162
|
if (since >= until) return 0;
|
|
@@ -218,37 +172,55 @@ export function percentChange(current: number, previous: number): number {
|
|
|
218
172
|
}
|
|
219
173
|
|
|
220
174
|
function recordKey(record: UsageRecord, mode: GroupMode): string {
|
|
221
|
-
return
|
|
175
|
+
return mode === "day" ? dayKey(record.ts) : mode === "project" ? record.cwd : record[mode];
|
|
222
176
|
}
|
|
223
177
|
|
|
224
178
|
export function matchesFilter(record: UsageRecord, filter: UsageFilter): boolean {
|
|
225
179
|
return recordKey(record, filter.mode) === filter.key;
|
|
226
180
|
}
|
|
227
181
|
|
|
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) };
|
|
182
|
+
export function usageWindow(records: UsageRecord[], day?: string, now = Date.now()) {
|
|
183
|
+
if (day) return dayWindow(day);
|
|
184
|
+
const until = dayWindow(dayKey(now)).until;
|
|
185
|
+
let first = Infinity;
|
|
186
|
+
for (const record of records) if (record.ts < until) first = Math.min(first, record.ts);
|
|
187
|
+
return { since: first === Infinity ? until : dayWindow(dayKey(first)).since, until };
|
|
248
188
|
}
|
|
249
189
|
|
|
250
|
-
export function
|
|
251
|
-
|
|
190
|
+
export function comparison(records: UsageRecord[], now = Date.now()) {
|
|
191
|
+
const { since: today, until } = dayWindow(dayKey(now));
|
|
192
|
+
const week = new Date(today);
|
|
193
|
+
week.setDate(week.getDate() - ((week.getDay() + 6) % 7));
|
|
194
|
+
week.setHours(0, 0, 0, 0);
|
|
195
|
+
const weekStart = week.getTime();
|
|
196
|
+
const lastWeek = dayWindow(dayKey(weekStart), -7).since;
|
|
197
|
+
const month = new Date(today);
|
|
198
|
+
month.setDate(1);
|
|
199
|
+
month.setHours(0, 0, 0, 0);
|
|
200
|
+
const monthStart = month.getTime();
|
|
201
|
+
month.setMonth(month.getMonth() - 1);
|
|
202
|
+
month.setHours(0, 0, 0, 0);
|
|
203
|
+
const lastMonth = 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 => ({
|
|
@@ -374,8 +335,7 @@ export function buildDailySeries(
|
|
|
374
335
|
since: number,
|
|
375
336
|
until: number,
|
|
376
337
|
mode: GroupMode,
|
|
377
|
-
|
|
378
|
-
): { total: DailyCost[]; rows: Map<string, DailyCost[]> } {
|
|
338
|
+
): { total: DailyCost[]; rows: Map<string, Map<number, number>> } {
|
|
379
339
|
const days = windowDays(since, until);
|
|
380
340
|
const total: DailyCost[] = [];
|
|
381
341
|
const positions = new Map<string, number>();
|
|
@@ -384,7 +344,7 @@ export function buildDailySeries(
|
|
|
384
344
|
const key = dayKey(cursor);
|
|
385
345
|
positions.set(key, i);
|
|
386
346
|
total.push({ label: key.slice(5), cost: 0 });
|
|
387
|
-
cursor =
|
|
347
|
+
cursor = dayWindow(key).until;
|
|
388
348
|
}
|
|
389
349
|
const costs = new Map<string, Map<number, number>>();
|
|
390
350
|
const add = (key: string, index: number, cost: number) => {
|
|
@@ -401,19 +361,7 @@ export function buildDailySeries(
|
|
|
401
361
|
add(seriesKey(key), index, record.cost);
|
|
402
362
|
if (mode === "provider") add(seriesKey(record.model, record.provider), index, record.cost);
|
|
403
363
|
}
|
|
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 };
|
|
364
|
+
return { total, rows: costs };
|
|
417
365
|
}
|
|
418
366
|
|
|
419
367
|
/** Sum `perBar` consecutive daily buckets into one bar, labeled by its first day. */
|