@deathbeam/pi-usage 0.0.7 → 0.0.9
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 +13 -11
- package/index.ts +42 -21
- package/package.json +1 -4
- package/src/usage.ts +132 -72
package/README.md
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
# [@deathbeam/pi-usage](https://www.npmjs.com/package/@deathbeam/pi-usage)
|
|
2
2
|
|
|
3
|
-
Use the `/usage` command for a fullscreen dashboard of token usage and
|
|
3
|
+
Use the `/usage` command for a fullscreen dashboard of token usage and cost per day, provider, model, and project.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
# Choose one:
|
|
9
|
+
pi install npm:@deathbeam/pi-usage # this package
|
|
10
|
+
pi install git:github.com/deathbeam/pi-packages # all my packages
|
|
11
|
+
```
|
|
4
12
|
|
|
5
13
|
## Keys
|
|
6
14
|
|
|
@@ -19,20 +27,14 @@ Day rows include days without usage. Δ compares cost with the previous day. The
|
|
|
19
27
|
|
|
20
28
|
The summary compares the daily spend so far this week and month with last week and month. Weeks start on Monday in local time. `▲new` means the previous period had no spend.
|
|
21
29
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
```sh
|
|
25
|
-
# Choose one:
|
|
26
|
-
pi install npm:@deathbeam/pi-usage # this package
|
|
27
|
-
pi install git:github.com/deathbeam/pi-packages # all my packages
|
|
28
|
-
```
|
|
30
|
+
Compaction and branch summaries are counted under `pi / summaries`.
|
|
29
31
|
|
|
30
32
|
## Development
|
|
31
33
|
|
|
32
|
-
From
|
|
34
|
+
From the repo root:
|
|
33
35
|
|
|
34
36
|
```sh
|
|
35
37
|
npm install
|
|
36
|
-
npm test
|
|
37
|
-
pi install
|
|
38
|
+
npm test -- packages/pi-usage
|
|
39
|
+
pi install ./packages/pi-usage
|
|
38
40
|
```
|
package/index.ts
CHANGED
|
@@ -32,6 +32,7 @@ type Column = {
|
|
|
32
32
|
};
|
|
33
33
|
type BodyRow = GroupRow & { parent?: string };
|
|
34
34
|
type Frame = { filters: UsageFilter[]; group: number; cursor: number; top: number };
|
|
35
|
+
type SparkBar = { label: string; char: string };
|
|
35
36
|
|
|
36
37
|
const GROUPS = ["day", "provider", "model", "project"] as const satisfies readonly GroupMode[];
|
|
37
38
|
const GROUP_LABELS: Record<GroupMode, string> = {
|
|
@@ -88,7 +89,9 @@ function hitPct(stats: Stats): string {
|
|
|
88
89
|
}
|
|
89
90
|
|
|
90
91
|
function layout(width: number, allColumns: Column[]): { nameWidth: number; columns: Column[] } {
|
|
91
|
-
|
|
92
|
+
function used(cols: Column[]): number {
|
|
93
|
+
return cols.reduce((sum, c) => sum + c.width + 1, 0);
|
|
94
|
+
}
|
|
92
95
|
let columns = allColumns;
|
|
93
96
|
for (const label of ["Share", "Hit%", "Cache", "Out", "In", "Reqs", "Δ"]) {
|
|
94
97
|
if (width - used(columns) >= MIN_NAME_WIDTH) break;
|
|
@@ -97,7 +100,9 @@ function layout(width: number, allColumns: Column[]): { nameWidth: number; colum
|
|
|
97
100
|
return { nameWidth: Math.max(4, width - used(columns)), columns };
|
|
98
101
|
}
|
|
99
102
|
|
|
100
|
-
|
|
103
|
+
function padWidth(s: string, w: number): string {
|
|
104
|
+
return s + " ".repeat(Math.max(0, w - visibleWidth(s)));
|
|
105
|
+
}
|
|
101
106
|
|
|
102
107
|
function displayName(mode: GroupMode, name: string): string {
|
|
103
108
|
if (mode === "day") return `${name} ${new Date(`${name}T00:00`).toLocaleDateString("en-US", { weekday: "short" })}`;
|
|
@@ -122,8 +127,6 @@ function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCos
|
|
|
122
127
|
.trimEnd();
|
|
123
128
|
}
|
|
124
129
|
|
|
125
|
-
type SparkBar = { label: string; char: string };
|
|
126
|
-
|
|
127
130
|
function sparkline(daily: DailyCost[], width: number): { first: string; last: string; bars: SparkBar[] } | undefined {
|
|
128
131
|
const recent = daily.slice(-Math.max(1, width - 12));
|
|
129
132
|
if (recent.length === 0) return undefined;
|
|
@@ -159,14 +162,18 @@ export default function (pi: ExtensionAPI) {
|
|
|
159
162
|
};
|
|
160
163
|
let render = () => {};
|
|
161
164
|
const agentDir = getAgentDir();
|
|
165
|
+
// ctx.sessionManager already resolved --session-dir, the env var and settings.sessionDir.
|
|
166
|
+
const sessionDir = ctx.sessionManager.getSessionDir();
|
|
167
|
+
const abort = new AbortController();
|
|
162
168
|
const loaded = collectUsage(
|
|
163
|
-
|
|
169
|
+
sessionDir,
|
|
164
170
|
(done, total) => {
|
|
165
171
|
state.done = done;
|
|
166
172
|
state.total = total;
|
|
167
173
|
render();
|
|
168
174
|
},
|
|
169
175
|
join(agentDir, "usage-cache.json"),
|
|
176
|
+
abort.signal,
|
|
170
177
|
).then((records) => {
|
|
171
178
|
state.records = records;
|
|
172
179
|
});
|
|
@@ -182,9 +189,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
182
189
|
let viewHeight = 1; // set on first render; 1 keeps page keys sane before it
|
|
183
190
|
let body: BodyRow[] = [];
|
|
184
191
|
const stack: Frame[] = [];
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
192
|
+
function filters() {
|
|
193
|
+
return stack.flatMap((frame) => frame.filters);
|
|
194
|
+
}
|
|
195
|
+
function dayFilter() {
|
|
196
|
+
return filters().findLast((f) => f.mode === "day");
|
|
197
|
+
}
|
|
198
|
+
function derive(source: UsageRecord[]) {
|
|
188
199
|
const active = filters();
|
|
189
200
|
const records = source.filter((record) =>
|
|
190
201
|
active.every((f) => f.mode === "day" || matchesFilter(record, f)),
|
|
@@ -195,24 +206,33 @@ export default function (pi: ExtensionAPI) {
|
|
|
195
206
|
const summary = summarize(records, window.since, window.until);
|
|
196
207
|
const body = flatten(buildRows(records, window.since, mode, window.until), mode);
|
|
197
208
|
return { mode, summary, body, compare: day ? undefined : comparison(records) };
|
|
198
|
-
}
|
|
209
|
+
}
|
|
199
210
|
const getView = cacheView(() => derive(state.records!));
|
|
200
211
|
let allDays: DailyCost[] | undefined;
|
|
201
|
-
|
|
202
|
-
|
|
212
|
+
function allDaily() {
|
|
213
|
+
return (allDays ??= dailyTotals(state.records!));
|
|
214
|
+
}
|
|
215
|
+
render = () => {
|
|
216
|
+
if (!abort.signal.aborted) tui.requestRender();
|
|
217
|
+
};
|
|
203
218
|
void loaded.then(render);
|
|
204
|
-
|
|
219
|
+
function close() {
|
|
220
|
+
abort.abort();
|
|
221
|
+
done(undefined);
|
|
222
|
+
}
|
|
223
|
+
function colorDelta(delta: number | undefined): string {
|
|
205
224
|
if (delta === undefined) return "-";
|
|
206
225
|
if (delta === 0) return "0%";
|
|
207
226
|
const text = Number.isFinite(delta)
|
|
208
227
|
? `${delta > 0 ? "▲" : "▼"}${Math.round(Math.abs(delta))}%`
|
|
209
228
|
: "▲new";
|
|
210
229
|
return theme.fg(delta > 0 ? "error" : "success", text);
|
|
211
|
-
}
|
|
230
|
+
}
|
|
212
231
|
const deltaColumn: Column = { label: "Δ", width: 9, cell: (_s, _r, _t, row) => colorDelta(row?.delta) };
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
active ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `);
|
|
232
|
+
function title(width: number): string {
|
|
233
|
+
function tab(label: string, active: boolean): string {
|
|
234
|
+
return active ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `);
|
|
235
|
+
}
|
|
216
236
|
const left =
|
|
217
237
|
theme.fg("accent", theme.bold("Usage")) +
|
|
218
238
|
filters()
|
|
@@ -233,12 +253,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
233
253
|
right,
|
|
234
254
|
width,
|
|
235
255
|
);
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
truncateToWidth(
|
|
256
|
+
}
|
|
257
|
+
function footer(width: number): string {
|
|
258
|
+
return truncateToWidth(
|
|
239
259
|
theme.fg("dim", "enter open · esc back · tab/←→ group · [ ] day · q close · ↑↓ scroll"),
|
|
240
260
|
width,
|
|
241
261
|
);
|
|
262
|
+
}
|
|
242
263
|
return {
|
|
243
264
|
render(width: number) {
|
|
244
265
|
const rows = tui.terminal.rows;
|
|
@@ -335,12 +356,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
335
356
|
invalidate() {},
|
|
336
357
|
handleInput(data: string) {
|
|
337
358
|
if (data === "q") {
|
|
338
|
-
|
|
359
|
+
close();
|
|
339
360
|
return;
|
|
340
361
|
} else if (keys.matches(data, "tui.select.cancel")) {
|
|
341
362
|
const frame = stack.pop();
|
|
342
363
|
if (!frame) {
|
|
343
|
-
|
|
364
|
+
close();
|
|
344
365
|
return;
|
|
345
366
|
}
|
|
346
367
|
({ group, cursor, top } = frame);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deathbeam/pi-usage",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.9",
|
|
4
4
|
"description": "Minimal extension for token usage and cost per provider, model and project.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -27,9 +27,6 @@
|
|
|
27
27
|
"./index.ts"
|
|
28
28
|
]
|
|
29
29
|
},
|
|
30
|
-
"scripts": {
|
|
31
|
-
"test": "node check.mjs"
|
|
32
|
-
},
|
|
33
30
|
"peerDependencies": {
|
|
34
31
|
"@earendil-works/pi-coding-agent": "*",
|
|
35
32
|
"@earendil-works/pi-tui": "*"
|
package/src/usage.ts
CHANGED
|
@@ -19,6 +19,8 @@ export type UsageRecord = {
|
|
|
19
19
|
cwd: string;
|
|
20
20
|
/** Session id from the session header line; empty when the file has no header. */
|
|
21
21
|
sessionId: string;
|
|
22
|
+
/** Assistant messages this record stands for. */
|
|
23
|
+
requests: number;
|
|
22
24
|
};
|
|
23
25
|
|
|
24
26
|
export type Stats = {
|
|
@@ -29,6 +31,35 @@ export type Stats = {
|
|
|
29
31
|
cacheWrite: number;
|
|
30
32
|
};
|
|
31
33
|
|
|
34
|
+
type CacheEntry = { size: number; mtimeMs: number; records: UsageRecord[] };
|
|
35
|
+
type Cache = { version: number; files: Record<string, CacheEntry> };
|
|
36
|
+
|
|
37
|
+
export type GroupMode = "day" | "provider" | "model" | "project";
|
|
38
|
+
export type UsageFilter = { mode: GroupMode; key: string };
|
|
39
|
+
|
|
40
|
+
export type GroupRow = {
|
|
41
|
+
key: string;
|
|
42
|
+
name: string;
|
|
43
|
+
stats: Stats;
|
|
44
|
+
requests: number;
|
|
45
|
+
delta?: number;
|
|
46
|
+
/** Nested model rows; only produced by provider grouping. */
|
|
47
|
+
children?: GroupRow[];
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export type Summary = {
|
|
51
|
+
stats: Stats;
|
|
52
|
+
requests: number;
|
|
53
|
+
/** Distinct session ids (files) seen in the window. */
|
|
54
|
+
sessions: number;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export type DailyCost = { label: string; cost: number };
|
|
58
|
+
|
|
59
|
+
type Tally = { stats: Stats; requests: number; models?: Map<string, Tally>; providers?: Set<string> };
|
|
60
|
+
|
|
61
|
+
const CACHE_VERSION = 2;
|
|
62
|
+
|
|
32
63
|
function emptyStats(): Stats {
|
|
33
64
|
return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
34
65
|
}
|
|
@@ -37,6 +68,54 @@ function num(value: unknown): number {
|
|
|
37
68
|
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
38
69
|
}
|
|
39
70
|
|
|
71
|
+
/** One record per (day, provider, model, cwd, session); the dashboard groups no finer than a day. */
|
|
72
|
+
function aggregate(records: UsageRecord[]): UsageRecord[] {
|
|
73
|
+
const buckets = new Map<string, UsageRecord>();
|
|
74
|
+
for (const record of records) {
|
|
75
|
+
const key = JSON.stringify([
|
|
76
|
+
startOfDay(record.ts),
|
|
77
|
+
record.provider,
|
|
78
|
+
record.model,
|
|
79
|
+
record.cwd,
|
|
80
|
+
record.sessionId,
|
|
81
|
+
]);
|
|
82
|
+
const bucket = buckets.get(key);
|
|
83
|
+
if (!bucket) {
|
|
84
|
+
buckets.set(key, { ...record });
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
addStats(bucket, record);
|
|
88
|
+
bucket.ts = Math.max(bucket.ts, record.ts);
|
|
89
|
+
bucket.requests += record.requests;
|
|
90
|
+
}
|
|
91
|
+
return [...buckets.values()];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function addStats(stats: Stats, record: UsageRecord): void {
|
|
95
|
+
stats.cost += record.cost;
|
|
96
|
+
stats.input += record.input;
|
|
97
|
+
stats.output += record.output;
|
|
98
|
+
stats.cacheRead += record.cacheRead;
|
|
99
|
+
stats.cacheWrite += record.cacheWrite;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function recordKey(record: UsageRecord, mode: GroupMode): string {
|
|
103
|
+
return mode === "day" ? dayKey(record.ts) : mode === "project" ? record.cwd : record[mode];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function tokens(s: Stats): number {
|
|
107
|
+
return s.input + s.output + s.cacheRead + s.cacheWrite;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Cost descending, then total tokens (so free models still rank by usage). */
|
|
111
|
+
function byCost(a: GroupRow, b: GroupRow): number {
|
|
112
|
+
return b.stats.cost - a.stats.cost || tokens(b.stats) - tokens(a.stats);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function newTally(): Tally {
|
|
116
|
+
return { stats: emptyStats(), requests: 0 };
|
|
117
|
+
}
|
|
118
|
+
|
|
40
119
|
async function sessionFiles(dir: string, out: string[]): Promise<void> {
|
|
41
120
|
let entries;
|
|
42
121
|
try {
|
|
@@ -51,11 +130,6 @@ async function sessionFiles(dir: string, out: string[]): Promise<void> {
|
|
|
51
130
|
}
|
|
52
131
|
}
|
|
53
132
|
|
|
54
|
-
type CacheEntry = { size: number; mtimeMs: number; records: UsageRecord[] };
|
|
55
|
-
type Cache = { version: number; files: Record<string, CacheEntry> };
|
|
56
|
-
|
|
57
|
-
const CACHE_VERSION = 1;
|
|
58
|
-
|
|
59
133
|
async function readCache(file: string): Promise<Record<string, CacheEntry>> {
|
|
60
134
|
try {
|
|
61
135
|
const cache = JSON.parse(await readFile(file, "utf8")) as Cache;
|
|
@@ -84,7 +158,12 @@ async function parseFile(file: string): Promise<UsageRecord[]> {
|
|
|
84
158
|
const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });
|
|
85
159
|
for await (const line of lines) {
|
|
86
160
|
// Cheap prefilter: escaped JSON inside tool results never matches this literal.
|
|
87
|
-
|
|
161
|
+
const isUsage =
|
|
162
|
+
line.includes('"role":"assistant"') ||
|
|
163
|
+
line.includes('"type":"usage"') ||
|
|
164
|
+
line.includes('"type":"compaction"') ||
|
|
165
|
+
line.includes('"type":"branch_summary"');
|
|
166
|
+
if (!isUsage) {
|
|
88
167
|
// The session header (type:"session", cwd, id) is normally the first line.
|
|
89
168
|
if (sessionId === "" && line.includes('"type":"session"')) {
|
|
90
169
|
try {
|
|
@@ -105,19 +184,36 @@ async function parseFile(file: string): Promise<UsageRecord[]> {
|
|
|
105
184
|
} catch {
|
|
106
185
|
continue;
|
|
107
186
|
}
|
|
108
|
-
const
|
|
109
|
-
const usage =
|
|
110
|
-
|
|
187
|
+
const message = entry?.message;
|
|
188
|
+
const usage =
|
|
189
|
+
entry?.type === "message" ? (message?.role === "assistant" ? message.usage : undefined) : entry?.usage;
|
|
190
|
+
if (!usage) continue;
|
|
191
|
+
let provider: string;
|
|
192
|
+
let model: string;
|
|
193
|
+
if (entry.type === "message") {
|
|
194
|
+
if (!message.provider || !message.model) continue;
|
|
195
|
+
provider = String(message.provider);
|
|
196
|
+
model = String(message.model);
|
|
197
|
+
} else if (entry.type === "usage" && entry.provider && entry.model) {
|
|
198
|
+
provider = String(entry.provider);
|
|
199
|
+
model = String(entry.model);
|
|
200
|
+
} else {
|
|
201
|
+
// Compaction and branch-summary calls carry no model, so their cost gets its own row.
|
|
202
|
+
provider = "pi";
|
|
203
|
+
model = "summaries";
|
|
204
|
+
}
|
|
111
205
|
const cost = typeof usage.cost === "number" ? usage.cost : num(usage.cost?.total);
|
|
206
|
+
const stamp = entry.type === "message" ? message.timestamp : entry.timestamp;
|
|
112
207
|
records.push({
|
|
113
|
-
provider
|
|
114
|
-
model
|
|
115
|
-
ts: num(
|
|
208
|
+
provider,
|
|
209
|
+
model,
|
|
210
|
+
ts: typeof stamp === "string" ? num(Date.parse(stamp)) : num(stamp),
|
|
116
211
|
cost,
|
|
117
212
|
input: num(usage.input),
|
|
118
213
|
output: num(usage.output),
|
|
119
214
|
cacheRead: num(usage.cacheRead),
|
|
120
215
|
cacheWrite: num(usage.cacheWrite),
|
|
216
|
+
requests: 1,
|
|
121
217
|
cwd,
|
|
122
218
|
sessionId,
|
|
123
219
|
});
|
|
@@ -142,6 +238,7 @@ export async function collectUsage(
|
|
|
142
238
|
dir: string,
|
|
143
239
|
onProgress?: (done: number, total: number) => void,
|
|
144
240
|
cacheFile?: string,
|
|
241
|
+
signal?: AbortSignal,
|
|
145
242
|
): Promise<UsageRecord[]> {
|
|
146
243
|
const files: string[] = [];
|
|
147
244
|
await sessionFiles(dir, files);
|
|
@@ -150,6 +247,7 @@ export async function collectUsage(
|
|
|
150
247
|
const records: UsageRecord[] = [];
|
|
151
248
|
let dirty = false;
|
|
152
249
|
for (const [done, file] of files.entries()) {
|
|
250
|
+
if (signal?.aborted) return records;
|
|
153
251
|
onProgress?.(done, files.length);
|
|
154
252
|
let info;
|
|
155
253
|
try {
|
|
@@ -166,29 +264,19 @@ export async function collectUsage(
|
|
|
166
264
|
}
|
|
167
265
|
dirty = true;
|
|
168
266
|
try {
|
|
169
|
-
const parsed = await parseFile(file);
|
|
267
|
+
const parsed = aggregate(await parseFile(file));
|
|
170
268
|
next[file] = { size: info.size, mtimeMs: info.mtimeMs, records: parsed };
|
|
171
269
|
for (const record of parsed) records.push(record);
|
|
172
270
|
} catch {
|
|
173
271
|
continue; // unreadable or truncated file: skip it, keep what other files gave
|
|
174
272
|
}
|
|
175
273
|
}
|
|
176
|
-
|
|
274
|
+
// A closed dashboard must not rewrite the cache with a partial scan.
|
|
275
|
+
if (!cacheFile || signal?.aborted) return records;
|
|
177
276
|
if (dirty || Object.keys(next).length !== Object.keys(cached).length) await writeCache(cacheFile, next);
|
|
178
277
|
return records;
|
|
179
278
|
}
|
|
180
279
|
|
|
181
|
-
function addStats(stats: Stats, record: UsageRecord): void {
|
|
182
|
-
stats.cost += record.cost;
|
|
183
|
-
stats.input += record.input;
|
|
184
|
-
stats.output += record.output;
|
|
185
|
-
stats.cacheRead += record.cacheRead;
|
|
186
|
-
stats.cacheWrite += record.cacheWrite;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
export type GroupMode = "day" | "provider" | "model" | "project";
|
|
190
|
-
export type UsageFilter = { mode: GroupMode; key: string };
|
|
191
|
-
|
|
192
280
|
export function cacheView<T>(derive: () => T) {
|
|
193
281
|
let cached: { key: string; value: T } | undefined;
|
|
194
282
|
return (mode: GroupMode, filters: UsageFilter[], now = Date.now()): T => {
|
|
@@ -220,10 +308,10 @@ export function dayWindow(key: string, offset = 0): { since: number; until: numb
|
|
|
220
308
|
// UTC ordinals count local calendar days without DST changing their length.
|
|
221
309
|
export function windowDays(since: number, until: number): number {
|
|
222
310
|
if (since >= until) return 0;
|
|
223
|
-
|
|
311
|
+
function ordinal(ts: number): number {
|
|
224
312
|
const d = new Date(ts);
|
|
225
313
|
return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) / 86_400_000;
|
|
226
|
-
}
|
|
314
|
+
}
|
|
227
315
|
return ordinal(until - 1) - ordinal(since) + 1;
|
|
228
316
|
}
|
|
229
317
|
|
|
@@ -231,10 +319,6 @@ export function percentChange(current: number, previous: number): number {
|
|
|
231
319
|
return previous === 0 ? (current === 0 ? 0 : Infinity) : ((current - previous) / previous) * 100;
|
|
232
320
|
}
|
|
233
321
|
|
|
234
|
-
function recordKey(record: UsageRecord, mode: GroupMode): string {
|
|
235
|
-
return mode === "day" ? dayKey(record.ts) : mode === "project" ? record.cwd : record[mode];
|
|
236
|
-
}
|
|
237
|
-
|
|
238
322
|
export function matchesFilter(record: UsageRecord, filter: UsageFilter): boolean {
|
|
239
323
|
return recordKey(record, filter.mode) === filter.key;
|
|
240
324
|
}
|
|
@@ -280,25 +364,6 @@ export function comparison(records: UsageRecord[], now = Date.now()) {
|
|
|
280
364
|
};
|
|
281
365
|
}
|
|
282
366
|
|
|
283
|
-
export type GroupRow = {
|
|
284
|
-
key: string;
|
|
285
|
-
name: string;
|
|
286
|
-
stats: Stats;
|
|
287
|
-
requests: number;
|
|
288
|
-
delta?: number;
|
|
289
|
-
/** Nested model rows; only produced by provider grouping. */
|
|
290
|
-
children?: GroupRow[];
|
|
291
|
-
};
|
|
292
|
-
|
|
293
|
-
const tokens = (s: Stats): number => s.input + s.output + s.cacheRead + s.cacheWrite;
|
|
294
|
-
|
|
295
|
-
/** Cost descending, then total tokens (so free models still rank by usage). */
|
|
296
|
-
const byCost = (a: GroupRow, b: GroupRow): number => b.stats.cost - a.stats.cost || tokens(b.stats) - tokens(a.stats);
|
|
297
|
-
|
|
298
|
-
type Tally = { stats: Stats; requests: number; models?: Map<string, Tally>; providers?: Set<string> };
|
|
299
|
-
|
|
300
|
-
const newTally = (): Tally => ({ stats: emptyStats(), requests: 0 });
|
|
301
|
-
|
|
302
367
|
export function buildRows(
|
|
303
368
|
records: UsageRecord[],
|
|
304
369
|
sinceMs = 0,
|
|
@@ -319,13 +384,13 @@ export function buildRows(
|
|
|
319
384
|
groups.set(key, group);
|
|
320
385
|
}
|
|
321
386
|
addStats(group.stats, record);
|
|
322
|
-
group.requests
|
|
387
|
+
group.requests += record.requests;
|
|
323
388
|
if (mode === "model") group.providers!.add(record.provider);
|
|
324
389
|
if (mode === "provider") {
|
|
325
390
|
let model = group.models!.get(record.model);
|
|
326
391
|
if (!model) group.models!.set(record.model, (model = newTally()));
|
|
327
392
|
addStats(model.stats, record);
|
|
328
|
-
model.requests
|
|
393
|
+
model.requests += record.requests;
|
|
329
394
|
}
|
|
330
395
|
}
|
|
331
396
|
if (mode === "day") {
|
|
@@ -344,23 +409,18 @@ export function buildRows(
|
|
|
344
409
|
rows[i]!.delta = percentChange(rows[i]!.stats.cost, rows[i + 1]!.stats.cost);
|
|
345
410
|
return rows;
|
|
346
411
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
412
|
+
function toRow([name, group]: [string, Tally]): GroupRow {
|
|
413
|
+
return {
|
|
414
|
+
key: name,
|
|
415
|
+
name: mode === "model" && group.providers!.size > 1 ? `${name} (${group.providers!.size})` : name,
|
|
416
|
+
stats: group.stats,
|
|
417
|
+
requests: group.requests,
|
|
418
|
+
children: group.models && [...group.models].map(toRow).sort(byCost),
|
|
419
|
+
};
|
|
420
|
+
}
|
|
354
421
|
return [...groups].map(toRow).sort(byCost);
|
|
355
422
|
}
|
|
356
423
|
|
|
357
|
-
export type Summary = {
|
|
358
|
-
stats: Stats;
|
|
359
|
-
requests: number;
|
|
360
|
-
/** Distinct session ids (files) seen in the window. */
|
|
361
|
-
sessions: number;
|
|
362
|
-
};
|
|
363
|
-
|
|
364
424
|
/** Totals for the summary block: one pass over [sinceMs, untilMs). */
|
|
365
425
|
export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinity): Summary {
|
|
366
426
|
const stats = emptyStats();
|
|
@@ -369,15 +429,15 @@ export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinit
|
|
|
369
429
|
for (const record of records) {
|
|
370
430
|
if (record.ts < sinceMs || record.ts >= untilMs) continue;
|
|
371
431
|
addStats(stats, record);
|
|
372
|
-
requests
|
|
432
|
+
requests += record.requests;
|
|
373
433
|
sessions.add(record.sessionId);
|
|
374
434
|
}
|
|
375
435
|
return { stats, requests, sessions: sessions.size };
|
|
376
436
|
}
|
|
377
437
|
|
|
378
|
-
export
|
|
379
|
-
|
|
380
|
-
|
|
438
|
+
export function seriesKey(key: string, parent?: string): string {
|
|
439
|
+
return JSON.stringify([key, parent ?? null]);
|
|
440
|
+
}
|
|
381
441
|
|
|
382
442
|
export function buildDailySeries(
|
|
383
443
|
records: UsageRecord[],
|
|
@@ -396,11 +456,11 @@ export function buildDailySeries(
|
|
|
396
456
|
cursor = dayWindow(key).until;
|
|
397
457
|
}
|
|
398
458
|
const costs = new Map<string, Map<number, number>>();
|
|
399
|
-
|
|
459
|
+
function add(key: string, index: number, cost: number): void {
|
|
400
460
|
let values = costs.get(key);
|
|
401
461
|
if (!values) costs.set(key, (values = new Map()));
|
|
402
462
|
values.set(index, (values.get(index) ?? 0) + cost);
|
|
403
|
-
}
|
|
463
|
+
}
|
|
404
464
|
for (const record of records) {
|
|
405
465
|
if (record.ts < since || record.ts >= until) continue;
|
|
406
466
|
const index = positions.get(dayKey(record.ts));
|